[英]Django - User Profile field won't change after form submit
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. 我是Django的初学者,因此我确定这是一个较小的修复程序。 I've been trying to get this to work the past few days.
在过去的几天里,我一直在努力使它工作。
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 表格
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()])
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
允许使用null,因此对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'])
: 如果表单的
discipline
字段是forms.ChoiceField
并具有(id, name)
元组作为选择,则form.cleaned_data['discipline']
将产生学科ID,您将使用Discipline.objects.get(id=form.cleaned_data['discipline'])
获得正确的Discipline
实例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()
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.