我的帖子有DetaiView,我想在此视图中使用表格,所以我决定将DetailView
与FormMixin
一起使用。我需要为此表格设置一些缩写,但我不知道该怎么做。这是我的代码:
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField("Nick", max_length=80)
email = models.EmailField()
body = models.TextField("Treść")
created = models.DateTimeField("Utworzono", auto_now_add=True)
updated = models.DateTimeField("Zaktualizowano", auto_now=True)
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = (
"name",
"email",
"body"
)
views.py
class PostDetailView(FormMixin, DetailView):
model = Post
form_class = CommentForm
template_name = "newspaper/post-detail.html"
def get_success_url(self):
return reverse("post-detail", kwargs={"slug": self.object.slug})
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context["form"] = self.get_form()
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
return super().form_valid(form)
因此,我想在CommentForm
中发布此DetailView
。希望你能理解:D。
预先感谢您的帮助!
答案 0 :(得分:1)
通过FormMixin
,您可以使用initial
属性指定表单的缩写:
class PostDetailView(FormMixin, DetailView):
model = Post
form_class = CommentForm
template_name = "newspaper/post-detail.html"
initial={'name': 'John'}
或get_initial方法:
def get_initial(self):
return {"post": self.get_object() }