Django - 用户配置文件字段在表单提交后不会更改

时间:2021-08-13 20:15:01

I'm trying to have a part of my user profile change after my form is submitted. The user profile has a discipline field, and I want the user to be able to modify it. When I click submit now, nothing changes.

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

I am a beginner at Django, so I am sure this is a minor fix. I've been trying to get this to work the past few days.

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

views.py

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 user profile

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

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

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 个解决方案

#1


1  

Ok should have read better. The first problem:

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

# 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

Since your Profile.primary_discipline allows nulls, the call to request.user.profile.save() doesn't raise an IntegrityError, so nothing happens indeed.

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

Now you didn't post your DisciplineChoiceForm so we don't know what form.cleaned_data['discipline'] points to, but that's obviously not going to work - what you want is to get the actual (saved) Discipline instance.

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

If your form's discipline field is a forms.ChoiceField and has (id, name) tuples as choices, then form.cleaned_data['discipline'] will yield the discipline id, and you'll get the correct Discipline instance with Discipline.objects.get(id=form.cleaned_data['discipline']):

如果你的表单的学科字段是一个forms.ChoiceField并且有(id,name)元组作为选项,那么form.cleaned_data ['discipline']将产生一个纪律id,你将获得带有Discipline.objects的正确的Discipline实例。得到(ID = form.cleaned_data [ '纪律']):

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

but you might be better using a forms.ModelChoiceField instead which will directly return the selected Discipline instance in which case you can simplify your code to:

但是你最好使用forms.ModelChoiceField来直接返回所选的Discipline实例,在这种情况下你可以简化你的代码:

discipline = form.cleaned_data['discipline']
request.user.profile.primaryDiscipline = discipline
request.user.profile.save()

#1


1  

Ok should have read better. The first problem:

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

# 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

Since your Profile.primary_discipline allows nulls, the call to request.user.profile.save() doesn't raise an IntegrityError, so nothing happens indeed.

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

Now you didn't post your DisciplineChoiceForm so we don't know what form.cleaned_data['discipline'] points to, but that's obviously not going to work - what you want is to get the actual (saved) Discipline instance.

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

If your form's discipline field is a forms.ChoiceField and has (id, name) tuples as choices, then form.cleaned_data['discipline'] will yield the discipline id, and you'll get the correct Discipline instance with Discipline.objects.get(id=form.cleaned_data['discipline']):

如果你的表单的学科字段是一个forms.ChoiceField并且有(id,name)元组作为选项,那么form.cleaned_data ['discipline']将产生一个纪律id,你将获得带有Discipline.objects的正确的Discipline实例。得到(ID = form.cleaned_data [ '纪律']):

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

but you might be better using a forms.ModelChoiceField instead which will directly return the selected Discipline instance in which case you can simplify your code to:

但是你最好使用forms.ModelChoiceField来直接返回所选的Discipline实例,在这种情况下你可以简化你的代码:

discipline = form.cleaned_data['discipline']
request.user.profile.primaryDiscipline = discipline
request.user.profile.save()