我的目标是为Post模型添加类别。我希望以后能够通过不同的,有时是多个类别查询所有帖子。
models.py
class Category(models.Model):
categories = (
('1', 'red'),
('2', 'blue'),
('3', 'black')
)
title = models.CharField(max_length=50, blank=True, choices=categories)
class Post(models.Model):
text = models.CharField(max_length=500)
category = models.ManyToManyField(Category)
forms.py
class Post_form(forms.ModelForm):
categories = (
('1', 'red'),
('2', 'blue'),
('3', 'black')
)
category = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple,
choices=categories)
class Meta:
model = Post
fields = (
'text',
'category'
)
我对保存一个obj的逻辑感到困惑,然后才能保存另一个obj。
views.py
def post(request):
if request.method == 'POST':
form = Post_form(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
p1 = Category(form.cleaned_data['category'])
post.category.add(p1)
return redirect('home:home')
else:
form = Post_form()
args = {'form': form }
return render(request, 'home/new_post.html', args)
错误:
"<Post: Post object>" needs to have a value for field "id" before this many-to-many relationship can be used.
编辑:
form.cleaned_data ['category']返回导致主要问题的列表。现在我的问题是我的选择是没有保存到Category类的标题中,而是保存选择号。这就是我得到的。
def post(request):
if request.method == 'POST':
form = Post_form(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
for k in form.cleaned_data['category']:
p1 = Category(title=k)
p1.save()
post.category.add(p1)
解决
views.py
def post(request):
if request.method == 'POST':
form = Post_form(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
for k in form.cleaned_data['category']:
selection = Category.objects.get(pk=k)
post.category.add(selection)
return redirect('home:home')
答案 0 :(得分:1)
主要问题是在分配类别之前没有将post对象保存到数据库。所以将视图稍微更改为此
def post(request):
if request.method == 'POST':
form = Post_form(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
for k in form.cleaned_data['category']:
p1 = Category.objects.create(title=k)
p1.save()
post.category.add(p1)
答案 1 :(得分:0)
像这样编辑您的视图,
if form.is_valid():
title = form.cleaned_data['category']
post = form.save(commit=False)
post.user = request.user
post.save()
category = Category.objects.create(title=title)
post.category.add(category)
post.save_m2m()
return redirect('home:home')