简体   繁体   English

Django:OneToOne 自引用字段表单验证错误(具有此字段的模型已存在)

[英]Django: OneToOne self-referencing field form validation error (Model with this field already exists)

Guys, could you please give a hint..各位大佬能指点一下吗。。

I just made a onetoone field in model that refers to itself.我刚刚在 model 中创建了一个指向自身的 onetoone 字段。 I have a collision problem in form validation when Im trying to edit already created model with already filled onetoone field with the SAME instance as it was assigned from scratch.当我尝试编辑已经创建的 model 时,我在表单验证中遇到了冲突问题,该字段已经填充了与从头开始分配的相同实例的 onetoone 字段。 In case I remain same relation (instance that was assigned before) in field it will return error: " Model (name of my model) with this field (name of my field) already exists " but If I change field value in form to another instance it will eventually validate this form without any problems.如果我在字段中保持相同的关系(之前分配的实例),它将返回错误:“ Model (我的模型名称)与此字段(我的字段名称)已经存在”但是如果我将表单中的字段值更改为另一个例如,它最终会毫无问题地验证此表单。 So, my solution that came to my mind is to override validate/clean methods in form.因此,我想到的解决方案是覆盖表单中的验证/清理方法。 Is it a proper way to manage this problem?这是处理这个问题的正确方法吗? And if it's true so how to write a proper code to handle this case?如果这是真的那么如何编写适当的代码来处理这种情况?

For clarity I attach my code below:为了清楚起见,我在下面附上了我的代码:

Models.py模型.py

db_dr = models.OneToOneField('self', on_delete=models.CASCADE, blank=True, null=True)

Part of code in views.py views.py中的部分代码

form = DatabaseInfoForm(initial=data)
if request.method == 'POST':
   form = DatabaseInfoForm(request.POST)
   if form.is_valid():

you are not putting in your full code for help, so here is an example, if let's say you have two models employee and company:你没有输入完整的代码来寻求帮助,所以这里有一个例子,假设你有两个模型员工和公司:

class Employee(models.Model):
    name = models.CharField(max_length=25)
    created_name = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class Company(models.Model):
    employee = models.OneToOneField(Employee, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    direction = models.CharField(max_length=80)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Assuming you already have the employee form created, we'll just create the company form:假设您已经创建了员工表单,我们将只创建公司表单:

class CompanyForm(ModelForm):
    class Meta:
        model = Company
        fields = (
            'employee', 'name', 'direction',
        )

already having the company models and forms, it is only a matter of creating the views, first we start with the creation one:已经有了公司模型和forms,只需要创建视图,首先我们从创建开始:

def company_creation(request):
    template_name = 'your template'
    form = CompanyForm(request.POST)

    if request.method == 'POST' and form.is_valid():
        form.save()
        return redirect('your url')

    return render(request, template_name, {
        'form': form,
    })

then we create the modification view:然后我们创建修改视图:

def company_edit(request, pk):
    template_name = 'your template'

    # here we get the data we want to modify
    company = Company.objects.get(pk=pk)
    form = CompanyForm(request.POST, instance=company)

    if request.method == 'POST' and form.is_valid():
        form.save()
        return redirect('your url')

    return render(request, template_name, {
        'form': form,
    })

finally we just create the url:最后我们只创建 url:

app_name = 'company'
urlpatterns = [
    path('create/', views.company_creation, name='create'),
    path('edit/<pk>/', views.company_edit, name='edit'),
]

and that way create and edit, without any problem这样创建和编辑,没有任何问题

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

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