通过在一个页面上扩展字段来更新用户信息

时间:2015-08-22 20:40:06

标签: django django-forms

我想更新当前的用户个人资料。用户具有一对一的UserExtend模型,因此我想在同一个提交事件上更新扩展字段。

class UserExtend(models.Model):
    user = models.OneToOneField(User)
    town = models.CharField(max_length=100, blank=True)
    age = models.IntegerField(blank=True)
    organization = models.CharField(max_length=100, blank=True)
    tel = models.CharField(max_length=15, blank=True)

    def __unicode__(self):
        return unicode(self.user)

这是我的views.py

def ProfileUpdateView(request):
    user = request.user
    user_form = UserForm(request.POST or None, initial={
        'first_name': user.first_name,
        'last_name': user.last_name,
        'email': user.email
    })
    user_extend_form = UserExtendForm(request.POST or None, initial={
        'user': user,
    })
    contacts = Contact.objects.get(activity=True)
    tels = contacts.tel.all()
    bg = Background.objects.get(activity=True)
    botlinks = Bottom_navigation.objects.all()
    if user_form.is_valid() and user_extend_form.is_valid():
        user_form.save()
        user_extend_form.save()
    c = {'form': user_form, 'extend_form': user_extend_form, 'contacts': contacts, 'tels': tels, 'bg': bg,
         'botlinks': botlinks}
    return render(request, 'posts/user_form.html', c)

和forms.py

class UserForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']

class UserExtendForm(forms.ModelForm):
    user = forms.ModelChoiceField(queryset=User.objects.all(),widget=forms.HiddenInput())

    class Meta:
        model = UserExtend
        fields = '__all__'

可以看出,我决定不重写我的ModelForm def函数,而是使用一个提交按钮在模板中传递两个表单。一切都按预期呈现,但是当我点击提交时,我收到如下错误:

Traceback:
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/srv/webapps/saunaflame/core/posts/views.py" in ProfileUpdateView
  89.         user_form.save()
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/forms/models.py" in save
  463.                              construct=False)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/forms/models.py" in save_instance
  105.         instance.save()
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in save
  710.                        force_update=force_update, update_fields=update_fields)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  738.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  822.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  861.                                using=using, raw=raw)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  920.         return query.get_compiler(using=using).execute_sql(return_id)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  974.                 cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
  124.             return self.cursor.execute(query, args)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/MySQLdb/cursors.py" in execute
  205.             self.errorhandler(self, exc, value)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: IntegrityError at /posts/profile/update/
Exception Value: (1062, "Duplicate entry '' for key 'username'")

为什么django试图覆盖我的User实例的用户名字段,如果我没有将其传递给表单? 有没有更好的方法来更新用户信息与扩展单个页面上的字段? 感谢名单。

1 个答案:

答案 0 :(得分:0)

这与两种形式无关。这是因为你传递初始值,然后保存表单,所以它自然会尝试使用这些值创建一个新实例,即使它们与现有数据冲突。

您应该使用level = graythresh(RGB); BW = im2bw(RGB,level); 参数而不是initial,以便Django知道更新现有实例。

instance