我想用UserProfile模型扩展我的用户模型。此UserProfile模型包含ForeignKey字段。在表单中,我想使用ModelChoiceField来预填充此表单字段。
每当我提交表格时,我都会
break
任何帮助将不胜感激!
我的代码:
models.py
ValueError at /accounts/register/
Cannot assign "'13'": "UserProfile.course" must be a "Course" instance.
forms.py
class Course(models.Model):
course_accid = models.CharField(max_length=10)
def __str__(self):
return self.course_accid
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
course = models.ForeignKey(Course)
def __unicode__(self):
return self.user.username
def user_registered_callback(sender, user, request, **kwargs):
profile = UserProfile(user = user)
profile.website = request.POST["website"]
profile.course = Course.objects.get(pk=request.POST["course"]),
profile.save()
答案 0 :(得分:0)
因此,发生的问题是 JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//done, parse result
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error
}
});
Volley.newRequestQueue(context).add(request);
需要设置为course
个实例,其前一步是course
,之前是forms.py
ModelChoiceField
。之所以这样,是因为查询它,就像你用queryset
做的那样,实际上只是搜索匹配的字符串,而不是实际的对象。
如果你把它分成两步,
class = [some_method_for_getting_a_class_object]
UserProfile.class = class
然后它应该摆脱那个错误。