Render User Selected Communities (as Checkboxes) in Multiple Choice Form

103 wyświetlenia
Przejdź do pierwszej nieodczytanej wiadomości

JJ Zolper

nieprzeczytany,
25 lis 2013, 00:13:5725.11.2013
do django...@googlegroups.com
Hello,

Hopefully it becomes clear as well from my code but, here is what is going on. There is an Athlete registration form which has a long list of choices or communities in the form of a multiple choices that the user can select to then become a part of the communities they select. Then what I'm trying to do is in my EditProfile view basically render this long list of multiple choices again but obviously it would make sense to show the user what ones they have selected/are already in, be able to deselect from this group to remove themselves from the ones they selected on registration, or to select new ones to then be added to those communities.

My EditProfile view:

# AU Athlete Edit Profile

def EditProfile(request):

    if request.user.is_authenticated():

        contexterror = {}

        context = {}

        contexterror = {'Error': 'Error'}

        # Since it is the generic view know we know if the user in the request is a specific group this way

        if request.user.groups.filter(name='Athletes').exists():

            # Since it is the generic view know we know if the user in the request is in 'Athletes' / member of of the 'Athletes' Group

            if request.method == 'POST':

                userprofile = UserProfileUpdateForm(request.POST, instance=request.user)

                athleteprofile = AthleteProfileUpdateForm(request.POST, instance=request.user.profile)

                # Need to make it so it checks the forms properly and saves the info if its correct

                if userprofile.is_valid() and athleteprofile.is_valid():

                    # Do something with the user selected athlete groups below

                    athletegroupsids = request.POST.getlist('athletecommunities')

                    # Iterate though all the athlete group names and collect the objects which we can use to add the request.user to those athlete groups

                    for athletegroupLOWERCASEname in athletegroupsids:

                        # Filter through all the communities and take the check box selection id which is lowercase and compare it to the communityurl which is the lowercase name

                        AthleteCommunities = Community.objects.get(url = athletegroupLOWERCASEname)

                        # Check to make sure we have one athlete community that we want to add the athlete to

                        # Get the name of the athlete community

                        AthleteCommunityName = AthleteCommunities.name

                        # By taking the desired athlete community name and filtering down the Athlete Group name be then add the user to the group

                        AddAthleteToGroup = Group.objects.get(name=AthleteCommunityName)

                        AddAthleteToGroup.user_set.add(request.user.athlete.athleteuser)

                    # Now the user has been added to all the groups they selected and notifications will go when a post is made in each respective group

                    # Save the two forms to the database

                    userprofile.save() and athleteprofile.save()

                return HttpResponseRedirect('/profile/')

            else:

                user = request.user

                profile = user.profile

                userprofile = UserProfileUpdateForm(instance = user)

                athleteprofile = AthleteProfileUpdateForm(instance = profile)

                context = {'AthleteProfileUpdateForm': athleteprofile, 'UserProfileUpdateForm': userprofile}

            return render_to_response('editprofile.html', context, context_instance = RequestContext(request))

        return render_to_response('editprofile.html', contexterror, context_instance = RequestContext(request))

    return HttpResponseRedirect('/login/')



My forms.py:


from django import forms

from django.forms import ModelForm

from django.contrib.auth.models import User

from athletesunited.athletes.models import Athlete


# Athlete Community Choices

ATHLETECOMMUNITIESCHOICES = (('archery', 'Archery',), ('mensbasketball', 'Men\'s Basketball',), ('womensbasketball', 'Women\'s Basketball',), ('baseball', 'Baseball',), ('cardio', 'Cardio',), ('cheerleading', 'Cheerleading',), ('crochet', 'Crochet',), ('dieting', 'Dieting',), ('football', 'Football',), ('golf', 'Golf',), ('gymnastics', 'Gymnastics',), ('hockey', 'Hockey',), ('injuryrecovery', 'Injury Recovery',), ('lacrosse', 'Lacrosse',), ('lifting', 'Lifting',), ('rugby', 'Rugby',), ('racing', 'Racing',), ('swimming', 'Swimming',), ('soccer', 'Soccer',), ('skateboarding', 'Skateboarding',), ('tennis', 'Tennis',),  ('wrestling', 'Wrestling',))


# Athlete Update Profile Form

class AthleteProfileUpdateForm(ModelForm):

    athletebirthday = forms.CharField(label=(u'Athlete Birthday:'))

    athleteurl = forms.CharField(label=(u'Athlete Url:'))

    #athletecommunities = forms.MultipleChoiceField(label=(u'Athlete Communities:'), widget=forms.CheckboxSelectMultiple, required=False, choices=ATHLETECOMMUNITIESCHOICES)

    

    class Meta:

        model = Athlete

        exclude = ('athleteuser',)

        fields = ['athletebirthday', 'athleteurl', 'athletecommunities', 'athletecolleges',]


    def selected_athlete_communities(self):

        return [athletecommunities[0] for athletecommunities in ATHLETECOMMUNITIESCHOICES]



My model for the athlete:


from django.contrib.auth.models import User


# Athlete User

class Athlete(models.Model):

    athleteuser = models.OneToOneField(User)

    athletebirthday = models.DateField()

    athleteurl = models.CharField(max_length=30)              # Must limit to a-z && A-Z && and 0-9 chars

    athletecommunities = models.ManyToManyField('communities.Community')

    athletecolleges = models.ManyToManyField('colleges.College')

    

    User.profile = property(lambda u: Athlete.objects.get_or_create(athleteuser=u)[0])


    def __unicode__(self):

        return self.athleteuser.first_name + " " + self.athleteuser.last_name


The relevant parts of my template for editprofile, just simply showing the form is all:


                    <form action="" method="post">{% csrf_token %}

                    {% for field in AthleteProfileUpdateForm %}

                    {{ field.label }}

                    {{ field }}

                    {{ field.error }}

                    <p>

                    {% endfor %}


                    <input type="submit" alt="post" value="Update" />

                    </form>



As you can see from the pictures, when I do athleteprofile = AthleteProfileUpdateForm(instance = profile) in my view in the picture named "showingcommunities" you can see there is this little box that has greyed out some community names. This is great and occurs when this line  "athletecommunities = forms.MultipleChoiceField(label=(u'Athlete Communities:'), widget=forms.CheckboxSelectMultiple, required=False, choices=ATHLETECOMMUNITIESCHOICES)" is commented out in my update athlete profile form. I was really optimistic when I saw this as I could see that indeed I was rendering which communities the user is actually in. However, when I add this following line back to my forms "athletecommunities = forms.MultipleChoiceField(label=(u'Athlete Communities:'), widget=forms.CheckboxSelectMultiple, required=False, choices=ATHLETECOMMUNITIESCHOICES)" you would see the second picture "notshowingcommunities" because basically there are the checkboxes but the ones the user is actually in are not rendering. What I mean is the checkboxes that correspond to what communities the user selected do not show up as checked. They all show up as empty.

I have used a BooleanField before as a flag and it does hold its value, I can see the checked box in i.e. an edit form if on creation of that object the user checks the box. I would really hate to have to make about 20 boolean fields for an athlete to correspond to my communities. Not to mention every time I want to add a community I would have to add more fields on the model, when I'd prefer to just add to my ATHLETECOMMUNITIESCHOICES the new communities. I've been trying a lot but I really can't seem to find a resource that helps me simply just render what options were selected on this multiplechoicefield, I tried modelmultiplechoicefield as well.

Thanks for helping, also if you have a better and nicer form concept I can try please let me know. Even though these checkboxes could work I'm not super satisfied with how this looks, I'd have to think up more ideas probably because I don't usually build websites that require an interface with a large relationship such as my athlete being in multiple communities and selecting and deselecting.

JJ



JJ Zolper

nieprzeczytany,
25 lis 2013, 00:18:5625.11.2013
do django...@googlegroups.com

I was so focused on posting the code I forgot to attach the pictures, now I'm putting them in.

JJ Zolper

nieprzeczytany,
26 lis 2013, 09:48:0326.11.2013
do django...@googlegroups.com

I know it's sort of a need by case basis but has anyone tried to do this before? Has anyone tried to render the choices a user has selected previously by rendering checked check boxes on a multiple choice field?

Thanks,

JJ

JJ Zolper

nieprzeczytany,
27 lis 2013, 23:30:2927.11.2013
do django...@googlegroups.com
So I guess no one knows what to do? No one has ever dealt with the multiple choice field or multiple choice selections and the UX for it?
Odpowiedz wszystkim
Odpowiedz autorowi
Przekaż
Nowe wiadomości: 0