我正在尝试从模型表单中获取数据,然后将其放入数据库中。我已经弄清楚如何制作表单,但是当点击提交按钮时,它似乎不会放在我的数据库中的任何位置。我做错了什么,或者我没有找到数据库中的正确位置。
forms.py
from django import forms
from sxsw.models import Account
class AccountForm(forms.ModelForm):
class Meta:
model = Account
fields = ['firstName', 'lastName', 'email']
views.py
from django.shortcuts import render
from django.shortcuts import redirect
from .forms import AccountForm
from .models import Account
def sxsw(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
form.save()
else:
print form.errors
else:
form = AccountForm()
return render(request, 'sxsw/sxsw.html', {'form': form})
def formSubmitted(request):
return render(request, 'sxsw/formSubmitted.html',{})
models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Account(models.Model):
firstName = models.CharField(max_length = 50)
lastName = models.CharField(max_length = 50)
email = models.EmailField()
def __unicode__(self):
return self.firstName
class Module(models.Model):
author = models.ForeignKey(Account, on_delete = models.CASCADE)
nameOfModule = models.CharField(max_length = 150) #arbitrary number
moduleFile = models.FileField(upload_to = 'uploads/')#Not exactly sure about the upload_to thing
public = models.BooleanField()
def __unicode__(self):
return self.nameOfModule
sxsw.html
{% extends "base.html" %}
{% block content %}
<div class="container-fluid">
<div class="jumbotron text-center">
<h3>SXSW Form</h3>
</div>
</div>
<div align="center">
<h1>New Form</h1>
<form role='form' action="/sxsw/formSubmitted/" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
</div>
{% endblock %}
formSubmitted.html
{% extends "base.html" %}
{% block content %}
<div class="container-fluid">
<div class="jumbotron text-center">
<h3>Form Successfully submitted</h3>
</div>
</div>
<div align="center">
<a href="{% url 'sxsw' %}" class="btn">Submit Another Response</a>
</div>
</div>
{% endblock %}
答案 0 :(得分:2)
您的表单发布到我认为错误的网址
<form role='form' action="/sxsw/formSubmitted/" method="post">
应该使用sxsw视图的URL
<form role='form' action="/sxsw/" method="post">
提交后,您可能希望重定向到提交的视图
return redirect('/sxsw/formSubmitted/') # Preferably use the url pattern name here
答案 1 :(得分:0)
您的表单action
似乎设置为/sxsw/formSubmitted/
,它始终只返回提交的页面,而不是调用sxsw
视图的网址,其中调用表单的save方法