1

please help to solve the problem.

There is a table with the data about the user. the table has a related field 'gender'. you want to display a form with a drop-down list to select the gender.

models.py:

class Gender(models.Model):     
    gender = models.CharField(
        max_length=10, 
        blank=False,
    )   
class UserProfile(User):
    nickname = models.CharField(
        'Отображаемое имя',
        max_length=30, 
        blank=False,
    )
    gender = models.ForeignKey(
        Gender,
        #default=1,
        null=True,
    )

views.py:

def personal_data_page(request):
    entry_user_profile = UserProfile.objects.get(user_ptr_id__exact=request.user.id)    
    form = PersonalDataForm(instance=entry_user_profile)    

    t = loader.get_template('personal_data_page.html')
    c = RequestContext(request, {
        'form': form,
    })
    return HttpResponse(t.render(c)) 

forms.py:

class PersonalDataForm(forms.ModelForm):    
    class Meta:
        model = UserProfile
        fields = (
            'nickname', 
            'gender',  
        )

personal_data_page.html:

<div class="cell">
    <label class="label">{{ form.gender.label }}</label>

    {{ form.gender }}

    {{ form.gender.errors }}
</div>

the problem is that the line outputs

1

. and I need to output is something like:

<select>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>
user3607370
  • 237
  • 1
  • 10

1 Answers1

1

Why would you make a UserProfile model with a ForeignKey to a Gender table? Just simply include the gender in the UserProfile.

And what are you looking for is called a choice_field.

Here is an example: ChoiceField in Django model

And here is the documentation: https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices.

Also, here is some docs about using a widget with choices: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

EDIT

If you realy want to keep the Gender table:

class PersonalDataForm(forms.ModelForm):    
    class Meta:
        model = UserProfile
        fields = (
            'nickname', 
            'gender',  
        )
        widgets = {'gender': forms.ModelChoiceField(queryset = 
                                                    Gender.objects.all())}

, assuming that you have defined __unicode__ for Gender

See more here:

  1. Specifying widget for model form extra field (Django)
  2. Django, ModelChoiceField() and initial value
Community
  • 1
  • 1
Mihai Zamfir
  • 2,167
  • 4
  • 22
  • 37
  • I need to do through foreignKey, but not through the choices – user3607370 May 16 '14 at 13:52
  • 1
    made an edit for you. PS: Please learn English at a basic level if you want to be a part of the international community and expect to receive answers in English. We need do understand your question first of all – Mihai Zamfir May 16 '14 at 14:08