简体   繁体   English

Django保存具有唯一约束的表单

[英]Django saving a form with unique constraint

I have a simple Profile model linked to Djang user model that keep alias.我有一个简单的 Profile 模型链接到保留别名的 Djang 用户模型。

Alias has a unique constraint in the model. Alias 在模型中具有唯一约束。

To update the alias, I created a model form, but can't figure out how to exclude the unique constraint when the user just push the submit button with no change to the alias.为了更新别名,我创建了一个模型表单,但是当用户只是按下提交按钮而不更改别名时,我无法弄清楚如何排除唯一约束。 The form raise an error because of unique constraint.由于唯一约束,该表单引发错误。

Here's the model and form definition with part of the view that handle the form:这是模型和表单定义以及处理表单的部分视图:

models.py模型.py

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

    alias = models.CharField(
        "Alias",
        max_length=50,
        unique=True,
        null=True
    )

forms.py表格.py

class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        fields = ['alias', ]

And the views.py和 views.py

def membership(request):
    if request.method != 'POST':
        profile = Profile.objects.get(user=request.user)
        form = ProfileForm(initial={'alias': profile.alias, 'user': request.user})
    elif request.POST.get('profile_update', None) == 'profile_update':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save()

You need to pass the instance to the form.您需要将实例传递给表单。 I've also switched out the alias key in the GET path's form with the instance usage.我还根据实例使用情况在 GET 路径的表单中切换了别名键。

def membership(request):
    profile = Profile.objects.get(user=request.user)
    if request.method != 'POST':
        form = ProfileForm(instance=profile, initial={'user': request.user})
    elif request.POST.get('profile_update', None) == 'profile_update':
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM