index.html
<div class="container add_dog_form">
<form method="POST">
{% csrf_token %}
<div class="row" id="namefield">
{{ form.as_table }}
</div>
<div class="row">
<button type="Submit" id="form_submit">Submit</button>
</div>
</form>
</div>
forms.py
class DogForm(forms.ModelForm):
class Meta:
model = Dog
fields = ['name', 'dog_pic']
views.py
class IndexView(generic.ListView):
template_name = "takyi1/index.html"
context_object_name = "dogs_context"
dog_form = DogForm
def get_context_data(self, **kwargs):
self.dogs_context = super().get_context_data(**kwargs)
self.dogs_context['dogs'] = self.dog
self.dogs_context['form'] = self.dog_form
return self.dogs_context
def post(self, request, *args, **kwargs):
form = self.dog_form(request.POST)
if form.is_valid():
form.save()
return HttpResponse('Valid Form')
else:
return HttpResponse('inValid Form')
最简单的方法是创建一个html表单,并通过post方法将数据保存到Model中。
使用ModelForm只会使它变得困难。
如果你使用下面的代码,它工作得很好
class IndexView(generic.ListView):
template_name = "takyi1/index.html"
model = Dog
def post(self, request):
self.model(name=request.POST['name'],
dog_pic=request.POST['dog_pic']).save( )
return HttpResponse('Valid Form')