【发布时间】:2014-04-26 10:30:12
【问题描述】:
Django 中的新功能,我在将表单数据添加到模型时遇到问题。我无法读取表单值并添加到模型中。我想将用户添加到具有名称和一个主题的模型中。
#models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=80)
subject = models.CharField(max_length=120)
#views.py
from django.shortcuts import render,render_to_response
from models import User
from django.http import HttpResponseRedirect
def add_user(request):
if request.method == 'POST':
f = User(request.POST)
if f.is_valid():
name = f.cleaned_data['name']
subject = f.cleaned_data['subject']
f.save()
return HttpResponseRedirect('index.html')
else:
f = User()
return render_to_response('index.html')
return render(request, 'index.html')
#index.html
<!DOCTYPE html>
<html>
<head>
<title>Sistemas Web</title>
</head>
<body>
<div>
<h1>Add User</h1>
<form action="add_user" method="POST">{% csrf_token %}
<label>Name</label><br>
<input id="name" type="text"><br>
<input type="radio" id="subject">A<br>
<input type="radio" id="subject">B<br>
<input type="submit" value="Enviar">
</form>
</div>
</body>
</html>
我们将不胜感激。
【问题讨论】: