我是Django的新手。我正在尝试检查字段“组”是否存在于db中。所以,我想在'group'字段中使用带有多个参数的验证器。我正在使用generic.CreateView。这是我的代码:
models.py :
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from .validators import valid_group
class Blood(models.Model):
A_POSITIVE = 'A_positive'
A_NEGATIVE = 'A_negative'
B_POSITIVE = 'B_positive'
B_NEGATIVE = 'B_negative'
AB_POSITIVE = 'AB_positive'
AB_NEGATIVE = 'AB_negative'
O_POSITIVE = 'O_positive'
O_NEGATIVE = 'O_negative'
choices = [
(A_POSITIVE, 'A+'),
(A_NEGATIVE, 'A-'),
(B_POSITIVE, 'B+'),
(B_NEGATIVE, 'B-'),
(AB_POSITIVE, 'AB+'),
(AB_NEGATIVE, 'AB-'),
(O_POSITIVE, 'O+'),
(O_NEGATIVE, 'O-'),
]
bank = models.ForeignKey(Bank, on_delete=models.CASCADE)
group = models.CharField(
choices=choices, max_length=11, db_index=True, validators=[valid_group])
slug = models.SlugField(max_length=100, db_index=True, unique=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=False)
stock = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('group',)
index_together = (('id', 'slug'),)
def clean(self, *args, **kwargs):
return valid_group(self.group, self.bank)
def save(self, *args, **kwargs):
self.slug = slugify(self.bank.name+self.group)
super(Blood, self).save(*args, **kwargs)
validators.py :
def valid_group(group, bank):
print(bank, group)
if group and bank.blood_set.filter(group=group).exists():
return ValidationError('Try to add different group')
views.py :
from django.shortcuts import render
from django.views import generic
from .models import Bank, Blood
from django import forms
class BloodCreateView(generic.CreateView):
model = Blood
template_name = "blood/blood_form.html"
fields = ['group', 'description', 'price', 'stock', 'available']
def form_valid(self, form):
bank_id = self.kwargs.get('pk')
# print(bank_id)
form.instance.bank_id = bank_id
group = form.cleaned_data.get('group')
if group and Bank.objects.get(pk=bank_id).blood_set.filter(group=group).exists():
return forms.ValidationError('Try to add different group')
return super(BloodCreateView, self).form_valid(form)
urls.py:
from django.urls import path, include
from .models import Bank, Blood
from . import views
app_name = 'blood'
urlpatterns = [
path('bank/<int:pk>/create/',
views.BloodCreateView.as_view(), name='blood-create')
]
我可以通过这种方式解决问题,以便在验证器中使用多个参数吗?