我目前在我的开发网站上有一个用于创建新帖子的表单。我最近在Post模型中添加了一个Tags模型和一个tags字段。然后我将标签字段添加到我的表单中。但是当我创建一个帖子并选择一个标签并保存它。除了我选择的标签外,一切都被保存。继承我的代码
我的模特
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=200, unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
tags = models.ManyToManyField(Tag)
objects = PostManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-timestamp", "-updated"]
class Tag(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=200, unique=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:tag_index", kwargs={"slug": self.slug})
class Meta:
ordering = ["-timestamp"]
my forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title",
"content",
"image",
"draft",
"publish",
"tags"
]
我的观点
def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Created !!")
return HttpResponseRedirect(instance.get_absolute_url())
template = "posts/post_form.html"
context = {
"form": form
}
return render(request, template, context)
我的帖子form.html
{% extends 'posts/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="col-sm-6 col-sm-offset-3">
<h1>
Form
</h1>
<form method="POST" action="" enctype="multipart/form-data">{% csrf_token%}
{{ form|crispy}}
<input type="submit" value="Create Post" class="btn btn-default">
</form>
</div>
{% endblock content %}
欢迎任何和所有指导
答案 0 :(得分:3)
您必须使用save_m2m()
基本上是这样的:
instance = form.save(commit=False)
instance.save()
instance.save_m2m()
Excerpt from the documentation:
要解决此问题,请每次使用时保存表单 commit = False,Django向您的ModelForm添加了save_m2m()方法 子类。手动保存后生成的实例后 在表单中,您可以调用save_m2m()来保存多对多表单数据。
请注意,执行save_m2m()
时,commit=False
仅需 。如果您只是form.save()
,则所有数据(包括多对数)都将成功保存