【问题标题】:not saving custom fields to django-allauth - no luck from previous posts没有将自定义字段保存到 django-allauth - 以前的帖子没有运气
【发布时间】:2014-08-26 01:30:19
【问题描述】:

我正在尝试创建自定义字段供用户在使用 django-allauth 注册时输入。我已经提到了几篇关于此的帖子,但我无法将我的自定义表单保存到我的数据库中。我确实在我的 signup.html 页面上获得了一个组合表单,其中包含用户名、密码 1 和 2、电子邮件以及我的城市和学校的额外字段,但我无法将额外的字段保存到数据库中。我已经运行了 syncdb 并且可以在管理区域中看到我的用户配置文件表。

这个建议是我最接近答案的,但我不明白如何实现它:“你不能使用 UserProfileForm 到 allauth.SIGNUP_FORM_CLASS。你需要从 SignUpForm 扩展它并编写一个保存方法将接受新创建的用户作为唯一参数,”来自这篇文章: Custom registration form for use with django-allauth

我还尝试将这些帖子的建议整合到此表单中: Django Allauth not saving custom form How to customize user profile when using django-allauth

这是我的代码: 模型.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
# A required line - links a UserProfile to User.
user = models.OneToOneField(User)

# The additional attributes we wish to include.
school = models.CharField(max_length=128)
city = models.CharField(max_length=128)

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

Forms.py

 from django import forms
 from django.contrib.auth.models import User
 from myapp.models import UserProfile
 from django.forms.widgets import HiddenInput
class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('city', 'school')

def signup(self, request, user):
 user=User.objects.get(email=request.email)
 city=request.POST.get('city','')
 school=request.POST.get('school','')
 userprofile_obj = UserProfile(user=user,city=city,school=school)
 userprofile_obj.save()

Settings.py

 ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.UserProfileForm'

我的模板是 django-allauth 模板中的基本 Signup.html,我没有为此创建视图,尽管我尝试从 tangowithdjango 用户身份验证部分注册视图中创建一个,这给出了类似的行为(不是保存到数据库中)。

谢谢, 凯莉

【问题讨论】:

    标签: python django forms django-allauth


    【解决方案1】:

    不确定这对于原始发布者是否仍然是一个活跃的问题/问题:如果是这样,对于遇到此问题的其他任何人,需要纠正一些事情以至少朝着正确的方向前进:

    • 我没有看到调用超类的__init__() 方法?例如:

      def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs)

    • 在注册方法中使用用户参数。它应该被填充;不要重新加载它。
    • 确保两个对象正确链接(我没有使用 Django 来构建我的配置文件表,所以 YMMV 但我设置了 user.profile = Profile(...); 然后在最后执行 user.profile.save()我的 signup() 方法。
    • 从 clean_data 表单中获取要放入配置文件的值(例如 self.cleaned_data['city'] 而不是 POST。

    然后开始调试:你的 signup() 方法触发了吗?它得到什么?执行 profile.save() 方法时会发生什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2017-03-22
      相关资源
      最近更新 更多