python - 不保存某些字段的数据

标签 python django

您好,我正在尝试将新注册用户保存到数据库中。除了 native 用户模型之外,我还有一个带有附加字段的配置文件模型,这是我的问题,注册后名为“性别”和“生日”的字段不会保存到数据库中,但用户和配置文件是使用相应字段创建的。

模型.py

class Profile(models.Model):

    GENDER_CHOICES = [
        ('male', 'Male'),
        ('female', 'Female'),
        ('other', 'Other'),
    ]
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image_prof = models.ImageField(
        default='default.jpg', upload_to='profile_pics')
    gender = models.CharField(
        max_length=100,
        choices=GENDER_CHOICES,
        default='male',)

    birthday = models.DateField(name='birthday', null=True)


    def __str__(self):
        return f'{self.user.username} Profile'


    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

View .py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm,  ProfileGenderBirthdayForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        bg_form = ProfileGenderBirthdayForm(request.POST)
        if form.is_valid():
            user = form.save()
            if bg_form.is_valid():
                user.profile.save()
            username = form.cleaned_data.get('username')
            messages.success(
                request, f'{username} Your account has been created! You can now log in')
            return redirect('login')
    else:
        form = UserRegisterForm()
        bg_form = ProfileGenderBirthdayForm()

    context = {
        'form': form,
        'bg_form': bg_form}

    return render(request, 'users/register.html', context)

html

{% extends "indi/base.html" %} {% load crispy_forms_tags %} {% block content %}
<div class="content-section">
  <form method="POST">
    {% csrf_token %}
    <fieldset class="form-group">
      <legend class="border-bottom mb-4">Join Today</legend>
      {{ form | crispy }}
      {{ bg_form | crispy }}
       </fieldset>

    <div class="form-group">
      <button class="btn btn-outline-info" type="submit">Sign Up</button>
    </div>
  </form>
  <div class="border-top pt-3">
    <small class="text-muted">
      Already Have An Account?
      <a class="ml-2" href="{% url 'login' %}">Sign In</a>
    </small>
  </div>
</div>
{% endblock content %}

非常感谢

最佳答案

您永远不会保存个人资料表单。应该是:

if form.is_valid() and bg_form.is_valid():
    user = form.save()
    profile = bg_form.save(commit=False)
    profile.user = user
    profile.save()

关于python - 不保存某些字段的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224256/

相关文章:

python - 在安装之前检查可用的 pip 包版本

python - Python 的 asyncio 中 Future 对象是如何使用的?

python - 我可以使用 Numba、矢量化或多处理加速这种空气动力学计算吗?

python - 使用 Visual Studio 2019 和 Windows 10 编译 MKL 库时出现模块未找到错误

Django:根据最新的子模型字段订购QuerySet

从模块导入函数而从另一个模块导入类时出现 Python 导入错误 (ModuleNotFoundError)

python /Django : Why does importing a module right before using it prevent a circular import?

python - Django Rest Framework 中的 to_representation() 可以访问普通字段吗

django - 在 Django 模板中有条件地扩展 base.html

python - 将用户添加到 django 中的组