0
ManyToMany 관계, 범주 및 Post가있는 두 모델이 있습니다. 두 개의 modelform, post_form 및 category_form을 하나의 제출 단추와 동일한 양식으로 통합하려고합니다. 관계를 저장할 때 관계를 어떻게 표시합니까?ManyToMany 관계를 하나의 양식으로 단일 양식과 연관시키는 방법
현재 두 개의 다른 게시물에 같은 category_name을 추가하면 이미 존재한다는 경고가 나타납니다. 드롭 다운 또는 비슷한 항목에서 동일한 category_name을 선택할 수 있기를 바랍니다. 도와주세요. 이것이 가능하지 않으면 내 대안은 무엇입니까?
Models.py
class Category(models.Model):
category_name = models.CharField(max_length=250, unique=True)
category_slug = models.SlugField(max_length=250, unique=True)
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
categories = models.ManyToManyField(Category)
def get_absolute_url(self):
return reverse('posts:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
Views.py
def post_list(request):
queryset = Post.objects.all()
return render(request, 'posts/post_list.html', {'post_list': queryset})
def post_detail(request, year, month, day, post):
instance = get_object_or_404(Post, slug = post,
status = 'published',
publish__year = year,
publish__month = month,
publish__day = day)
return render(request, 'posts/post_detail.html', {'post':instance})
def post_create(request):
post_form = PostForm(request.POST or None)
category_form = CategoryForm(request.POST or None)
if post_form.is_valid() and category_form.is_valid():
post_form_instance = post_form.save()
category_form_instance = category_form.save()
print (request.POST)
print (post_form.is_valid)
context = {'post_form':post_form, 'category_form':category_form}
return render(request, 'posts/post_form.html', context)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'title',
'slug',
'body',
'publish',
'status',
]
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = [
'category_name',
'category_slug',
]
post_form.html
<!--DOCTYPE html -->
<html>
<head>
</head>
<body>
<form method='POST'>{% csrf_token %}
<h1>Form</h1>
{{ post_form.as_p }}
{{ category_form.as_p }}
<input type="submit" value="Create Post" />
</form>
</body>
</html>
덕분에 많이. 나는 네가 나에게 요구 한 것을 정확히 찾고 있었다. 같은 양식으로 NEW 카테고리를 추가하는 방법을 어떻게 도울 수 있습니까? – user3052646