RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1431720
Accepted
Guardian45
Guardian45
Asked:2022-07-21 17:43:38 +0000 UTC2022-07-21 17:43:38 +0000 UTC 2022-07-21 17:43:38 +0000 UTC

Django通过函数注册和授权

  • 772

我找不到问题的解决方案。

该站点要求用户在其他字段中注册。并通过电子邮件授权。我通过一个附加模型添加了这些字段:

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  phone = models.IntegerField('Телефон', null=True, blank=True)
  country = models.CharField('Страна', max_length=100, null=True, blank=True)
  city = models.CharField('Город', max_length=100, null=True, blank=True)
  adress = models.CharField('Улица и дом', max_length=300, null=True, blank=True)
  zip_code = models.IntegerField('Почтовый индекс', null=True, blank=True)
  birth_day = models.DateField('День рождения', null=True, blank=True)
  avatar = models.ImageField('Аватар', upload_to='avatar', null=True, blank=True)
  agreement = models.BooleanField('Согласие на обработку', default=True)
  comment = models.TextField('Комментарии', max_length=3000, null=True, blank=True)

  @receiver(post_save, sender=User)
  def create_user_profile(sender, instance, created, **kwargs):
    if created:
      Profile.objects.create(user=instance)

  @receiver(post_save, sender=User)
  def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

  def admin_display(self):
    return self.user.last_name + ' ' + self.user.first_name

接下来,我制作了 2 个表格在模板中显示:

class ProfileForm(forms.ModelForm):
  class Meta:
    model = Profile
    exclude = ('comment', 'register_date', 'avatar', 'password', )
    widgets = {
      'phone': forms.NumberInput(attrs={'placeholder': '9XXXXXXXXX', 'class': 'form-control', 'id': 'phone'}),
      'country': forms.TextInput(attrs={'placeholder': 'Россия', 'class': 'form-control', 'id': 'country'}),
      'city': forms.TextInput(attrs={'placeholder': 'Москва', 'class': 'form-control', 'id': 'city'}),
      'adress': forms.TextInput(attrs={'placeholder': 'Ленина 25', 'class': 'form-control', 'id': 'adress'}),
      'zip_code': forms.TextInput(attrs={'placeholder': '101000', 'class': 'form-control', 'id': 'zip_code'}),
      'agreement': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexSwitchCheckChecked'}),
      'birth_day': DateInput(attrs={'class': 'form-control', 'id': 'birth_day'}),
    }


class UserForm(forms.ModelForm):
  class Meta:
    model = User
    fields = ('first_name', 'last_name', 'email', 'password',)
    widgets = {
      'first_name': forms.TextInput(attrs={'placeholder': 'Иван', 'class': 'form-control', 'id': 'first_name'}),
      'last_name': forms.TextInput(attrs={'placeholder': 'Петров', 'class': 'form-control', 'id': 'last_name'}),
      'email': forms.EmailInput(attrs={'placeholder': 'ivan_petrov@email.ru', 'class': 'form-control', 'id': 'email'}),
      'password': forms.PasswordInput(attrs={'placeholder': 'Пароль', 'class': 'form-control', 'id': 'password'}),
    }

这是视图中的内容:

def registration(request):
  if request.method == 'POST':
    form = UserForm(request.POST)
    if form.is_valid():
      instance = form.save(commit=False)
      instance.username = request.POST['email']
      instance.set_password(request.POST['password'])
      instance.save()
      return redirect('registration')
    else:
      form = UserForm(request.POST)
      profile_form = ProfileForm(request.POST)
      context = {
        'form': form,
        'profile_form': profile_form,
      }
    return render(request, 'user_registration.html', context)
  else:
    form = UserForm()
    profile_form = ProfileForm()
    context = {
      'form': form,
      'profile_form': profile_form,
    }
    return render(request, 'user_registration.html', context)

我没有显示用户名字段。相反,我在那里添加了一封电子邮件。用户已创建。由于某种原因,只有密码没有加密。并且该用户无法登录。我收到登录名/密码匹配错误。而且我找不到登录功能的示例。请帮我解决一下这个。

django авторизация
  • 1 1 个回答
  • 43 Views

1 个回答

  • Voted
  1. Best Answer
    Za Ars
    2022-07-21T19:54:17Z2022-07-21T19:54:17Z

    在保存用户之前,请执行user.set_password(<пароль>)

    接下来,由于错误:

        form = UserForm(request.POST)
        if form.is_valid():
          instance = form.save(commit=False)
          instance.username = request.POST['email']
    

    已经错了instance.username = request.POST['email']。表单收到的名称不正确(该字段为username空)。因此,会发生错误。以及其他领域。

    你能用clean表格来做吗?cleaded_data['username'] = cleacned_data['email']


    升级版:

    简而言之,您需要从django.contrib.auth.models.AbstractUser类比创建一个模型django.contrib.auth.models.User,删除所有不必要的,并将生成的模型指定为setttings.py( AUTH_USER_MODEL) 中的用户模型。

    在您的情况下,新模型将如下所示

    
    class MyUser(AbstractUser):
        """
        An abstract base class implementing a fully featured User model with
        admin-compliant permissions.
    
        Username and password are required. Other fields are optional.
        """
        username = None
        EMAIL_FIELD = 'email'
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['email']
    

    在这种情况下,要在ForeignKeyand中表示与用户的关系ManyToMany,OneToOneField最好使用get_user_model(),一般情况下最好使用该函数,而不是指定特定的类。


    更多信息可以custom user model django在搜索引擎中找到,下面是一个示例链接

    例子

    • 0

相关问题

  • Django views.py 如何编写过滤器来显示文章的评论

  • 为什么 Sales 字段没有到达前面,即使它们已添加到序列化程序中

  • 注销而不进入 /exit 页面

  • Django 调试服务器未启动

  • 如果页面长时间打开,则 CSRF cookie 未设置 Django

  • 如何删除通过外键链接到另一个模型的图像

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5