如何在一个视图中同时保存多个模型形式(lAWYER和类别((1:1((Django(
class Lawyer(models.Model):
category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE)
name = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Category(models.Model):
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES)
slug = models.SlugField(max_length=150, unique=True, db_index=True)
city = models.CharField(max_length=20)
在视图中。.PY
def lawyer_list(request, category_slug=None):
if request.method == 'POST':
cat_form = CategoryForm(request.POST)
if cat_form.is_valid():
cat_obj = cat_form.save(commit=False)
cat_obj.profile = request.user.profile
cat_obj.save()
lawyer_form = LawyerForm(request.POST)
if lawyer_form.is_valid():
lawyer_form = lawyer_form.save(commit=False)
lawyer_form.profile = request.user.profile
lawyer_form.category = cat_obj
lawyer_form.save()
也有两种形式 1(类律师表格(表格。模型形式( 2(类类别(表格。模型形式(
在视图中,我不想制作两个对象
Forms.py
enter code here
CATEGORY_CHOICES = (('CRIMINAL', 'Criminal'),('EMPLOYMENT', 'Employment'),
('CORPORATE', 'Corporate'),)
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=3,
widget=forms.Select(choices=CATEGORY_CHOICES),)
class Meta:
model = Category
fields = ('category_name','city',)
class LawyerForm(forms.ModelForm):
class Meta:
model = Lawyer
fields = ('name','description','charge','available',)
class Lawyer(models.Model):
category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE)
name = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Category(models.Model):
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES)
slug = models.SlugField(max_length=150, unique=True, db_index=True)
city = models.CharField(max_length=20)
def save(self, *args, **kwargs):
lawyer=Lawyer(*args,**kwargs)
lawyer.category=self
lawyer.save()
super(Category, self).save(*args, **kwargs)
在视图中
def lawyer_list(request, category_slug=None):
if request.method == 'POST':
cat_form = CategoryForm(request.POST)
if cat_form.is_valid():
cat_obj = cat_form.save(commit=False)
cat_obj.profile = request.user.profile
cat_obj.save()