Emil George James
Emil George James

Reputation: 1261

Django ChoiceField saves None value after editing?

I have a Model as follows,

gender = (
    ('Male', 'Male'),
    ('Female', 'Female'),
    )

class UserProfile(models.Model):
    profile_id = models.CharField(max_length=60, blank=True,default='',)
    gender = models.CharField(max_length=60, blank=True, default='',
                              choices=gender,verbose_name="gender")

I have a modelform as follows for that model,

 class UserProfileForm(forms.ModelForm):

def __init__(self, *args, **kargs):
    super(UserProfileForm, self).__init__(*args, **kargs)
   class Meta:
       model = UserProfile
       fields = '__all__'

And views for editing form,

  def userprofile_edit(request, pk):
       userprofile = UserProfile.objects.get(pk=pk)
       form = UserProfileForm(request.POST or None,instance=userprofile)

       if request.method == "POST":
          form = UserProfileForm(request.POST or None,instance=userprofile)
         if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('userprofile')
         else:
           form = UserProfileForm(instance=userprofile)
      else:
          form = UserProfileForm(request.POST or None,instance=userprofile)
      return render(request,'userprofiles/user_edit.html', {'form':form,'userprofile': userprofile})

And Template for Edit userprofile form,

    <div class="col-md-3">
       <div class="form-group">
             <label>Gender <star>*</star></label>
             <select name="gender" required class="selectpicker" value="{{ userprofile.gender }}"  data-title="{{ userprofile.gender }}" data-style="btn-default btn-block" data-menu-style="dropdown-blue">
{% for Male,Female in form.fields.gender.choices %}
   <option value="{{ Male }}"{% if form.fields.gender.value == Male %} selected{% endif %}>{{ Female }}</option>
{% endfor %}
</select>

The Problem is only while editing the userprofile form,when I click the submit button for this form, it raises "This field is required". When I click the choicefield and select an option, it works. But if I didn't select an option it saves a None.I wanted to know how to pass values to selectfield. Please help?

Upvotes: 2

Views: 1264

Answers (2)

Raja Simon
Raja Simon

Reputation: 10315

You have declare gender default as "" empty string. So in your form just put the empty string if user doesn't select any...

<option selected="selected" value=""></option>

Upvotes: 2

AR7
AR7

Reputation: 376

Since you are using a model form, there is no need to write an HTML for the form, anyways you are returning the form from the view.You can write it as:

<div>
 <form action="your url" method="POST">
 {% csrf_token %}
  {{ form.as_p }}
<butoon type="submit">Update</button>
</form>

The only possibility the choice field is coming as blank, is that it might not be selected.

Upvotes: 0

Related Questions