Django 通过TemplateView保存表单
我试图通过PostByTemplateView保存表单,但当def Post调用时,表单不会保存。 使用内联表单集。书名由作者保存,一个作者可以有多本书 以下代码是我正在使用的代码: 这是视图,Inlineformset的发布内容,如果是get,则显示表单,如果是post,则必须保存数据。 #view.py #模型 这是models.pyDjango 通过TemplateView保存表单,django,Django,我试图通过PostByTemplateView保存表单,但当def Post调用时,表单不会保存。 使用内联表单集。书名由作者保存,一个作者可以有多本书 以下代码是我正在使用的代码: 这是视图,Inlineformset的发布内容,如果是get,则显示表单,如果是post,则必须保存数据。 #view.py #模型 这是models.py # Create your models here. from django.db import models class Author(models.Mo
# Create your models here.
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
def __str__(self):
return self.title
index.html
<form action="" method="post" >
<div class="html">
{% csrf_token %}
{% for form in formset %}
{{form }}
{%endfor %}
<button type="submit">save</button>
</form>
</div>
<form method="post">
{{ csrf_token }}
{{ author_form}}
<input type="submit" value="submit">
</form>
{%csrf_令牌%}
{formset%中表单的%s}
{{form}}
{%endfor%}
拯救
不久前,我遇到了同样的问题,我解决这个问题的方式与使用表单集(我不太熟悉)有点不同,希望它能帮助您:
Models.py
from django.db import models
class Author(models.Model)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
def __str__(self):
return self.title
Forms.py
from django import forms
from Appname.models import Author, Book
class Author(forms.ModelForm):
class Meta:
model = Author
fields = ['name']
class Book(forms.ModelForm):
class Meta:
model = Book
fields = ['author', 'title']
Views.py
class BookView(TemplateView):
template_name ="index.html"
author_form_class = Author
def get_context_data(self, **kwargs):
context = super(BookView, self).get_context_data(**kwargs)
context['author_form'] = self.author_form_class
context['book_form'] = self.book_form_class
return context
def post(self, request):
author_form_class = Author(request.POST or None)
book_form_class = Book(request.POST or None)
if author_form_class.is_valid():
author_form_class.save()
return redirect('/')
if book_form_class.is_valid():
book_form_class.save()
return redirect('/')
index.html
<form action="" method="post" >
<div class="html">
{% csrf_token %}
{% for form in formset %}
{{form }}
{%endfor %}
<button type="submit">save</button>
</form>
</div>
<form method="post">
{{ csrf_token }}
{{ author_form}}
<input type="submit" value="submit">
</form>
{{csrf_token}}
{{author_form}}