Django - 用户个人资料字段在表单提交后不会更改

时间:2015-06-25 06:59:23

标签: python django forms

我提交表单后尝试更改用户个人资料的一部分。用户配置文件有一个学科字段,我希望用户能够修改它。当我现在点击提交时,没有任何变化。

我是Django的初学者,所以我确信这是一个小修复。我过去几天一直试图让这个工作。

views.py

@login_required
def change_discipline(request):
    context = RequestContext(request)
    if request.method == 'POST':
    #     #create a form instance and populate it with data from the request
        form = DisciplineChoiceForm(request.POST)
        if form.is_valid():
             #process data in form.clean_data
            discipline = Discipline(name=form.cleaned_data['discipline'])
            request.user.profile.primaryDiscipline = discipline
            request.user.save()
            request.user.profile.save()
            return render_to_response('changediscipline.html', { 'form': form }, context)
else:
    form = DisciplineChoiceForm(request.POST)

return render_to_response('changediscipline.html', {'form': form}, context )

models.py 用户个人资料

class UserProfile(models.Model):
    #this line is required. Links MyUser to a User Model
    user = models.OneToOneField(User, related_name ="profile")
#Additional Attributes we wish to include
date_of_birth = models.FloatField(blank=False)
phone = models.CharField(max_length=10, blank = True)
city = models.CharField(max_length=40, blank = True)
state = models.CharField(max_length=2, blank = True)
zipCode = models.CharField(max_length=5, blank = True)
admin = models.BooleanField(default=False, blank = True)
mentor = models.BooleanField(default=False, blank = True)
mentee = models.BooleanField(default=False, blank = True)
# profilepicture = models.ImageField()
#is_staff = True
tagline = models.CharField(max_length=70, blank = True, default="Let's do this!")
interests = models.ManyToManyField(Interest, related_name="interest", symmetrical = False)
primaryDiscipline = models.ForeignKey(Discipline, default=False, blank = True)
addtlDisciplines = models.ManyToManyField(Discipline, related_name="disciplines", symmetrical=False)

HTML

<div class = "container">
  <h1>Choose a Discipline in {{interest}}</h1>
  <form action="{% url 'myapp:change_discipline'  %}" method="POST" id="discipline-select">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
  </form>
    <!-- {% csrf_token %}
    <select id="id_interest" name="discipline">
      <option disabled selected> -- select an option -- </option>
      {% for d in disciplines %}
      <option value={{d.id}}>{{d.name}}</option>
      {% endfor %}
    </select>
    <input type="submit" value="Load Disciplines"/>
  </form> -->
</div> 

forms.py

class DisciplineChoiceForm(forms.Form):
def __init__(self, interest, *args, **kwargs):
    super(DisciplineChoiceForm, self).__init__(*args, **kwargs)
    self.fields['discipline'] = forms.ChoiceField(choices = [(o.id, str(o)) for o in Discipline.objects.all()])

1 个答案:

答案 0 :(得分:1)

好的应该读得更好。第一个问题:

# this creates an unsaved Discipline instance
discipline = Discipline(name=form.cleaned_data['discipline'])
# and assign it to request.user.profile
request.user.profile.primaryDiscipline = discipline

由于Profile.primary_discipline允许空值,因此对request.user.profile.save()的调用不会引发IntegrityError,因此确实没有任何反应。

现在你没有发布你的DisciplineChoiceForm,所以我们不知道form.cleaned_data['discipline']指向的是什么,但这显然不起作用 - 你想要的是获得实际的(已保存的){ {1}}实例。

如果您的表单的Discipline字段为discipline并且有forms.ChoiceField个元组作为选项,那么(id, name)将产生纪律ID,您将获得正确的{ {1}} form.cleaned_data['discipline']的实例:

Discipline

但您可能最好使用forms.ModelChoiceField而不是直接返回选定的Discipline.objects.get(id=form.cleaned_data['discipline'])实例,在这种情况下,您可以将代码简化为:

discipline = Discipline.objects.get(id=form.cleaned_data['discipline'])
request.user.profile.primaryDiscipline = discipline
request.user.profile.save()