django 表单提交的几种方式

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

第一种方式:直接建立form构建

新建model

class Contact(models.Model):    subject = models.CharField(max_length=100)    message = models.TextField()    email = models.EmailField(max_length=100)    def __unicode__(self):        return self.subjectclass ContactAdmin(admin.ModelAdmin):    list_display=('subject','message')    search_fields=('subject','message')    list_filter=('subject','message')

新建form

TOPIC_CHOICES = ( ('general', 'General enquiry'), ('bug', 'Bug report'), ('suggestion', 'Suggestion'), )class ContactForm(forms.Form):    subject = forms.CharField(max_length=100)    #topic = forms.ChoiceField(choices=TOPIC_CHOICES)    #message = forms.CharField()    message = forms.CharField(widget=forms.Textarea(),initial="Replace with your feedback")    sender = forms.EmailField(initial='pianzif@126.com')    cc_myself = forms.BooleanField(required=False)# Create your views here.def contact(request):    lit_list=Article.objects.all()    if request.method == 'POST':        form = ContactForm(request.POST)        if form.is_valid():            sender = form.cleaned_data['sender']            message = form.cleaned_data['message']            mess_len=len(message)            if mess_len<4:                raise forms.ValidationError("not enough word")            subject = form.cleaned_data['subject']            Contact.objects.create(email=sender,message=message,subject=subject)            #return HttpResponse('OK')            return HttpResponseRedirect('/news/articles/2014')    else:        form = ContactForm()    return render_to_response('contact.html',{'form':form,'literary' : lit_list},RequestContext(request))

—–add 2015年8月28日 00:16:58

# 获取文章详细信息,包含一个CommentForm表单def detail(req, article_id):    if req.method == 'POST':        form = CommentForm(req.POST)        if form.is_valid():            name = form.cleaned_data['name']            address = form.cleaned_data['address']            email = form.cleaned_data['email']            context = form.cleaned_data['context']            article = Article.objects.get(pk=article_id)            comment = Comment(article=article, name=name, address=address, email=email, context=context)            comment.save()            return HttpResponseRedirect('dlog/detail.html')

–add end

urls.py 中增加

    (r’^contact/$’,contact),

增加模版

{% extends "list_article.html" %}{% block contact %}<form action="/news/contact/" method="post">{% csrf_token %}<h2>-------contact me,pls write your info</h2>{{ form.as_p}}<input type="submit" value="Submit" /></form>{% endblock %}

模版还可以在这样写:

{% extends "list_article.html" %}{% block contact %}<form action="." method="POST">    <div class="fieldWrapper">     {{ form.subject.errors }}     <label for="id_topic">Kind of feedback:</label> {{ form.subject }}    </div>    <div class="fieldWrapper">     {{ form.message.errors }}     <label for="id_message">Your message:</label> {{ form.message }}    </div>    <div class="fieldWrapper">     {{ form.sender.errors }}     <label for="id_sender">Your email (optional):</label> {{ form.sender }}    </div>    <p><input type="submit" value="Submit" /></p>   </form>{% endblock %}

第二种方式:使用模版构建

参考:http://blog.chinaunix.net/uid-21633169-id-4349932.html

新建model

class RemarkForm(models.Model):    subject = models.CharField(max_length=100)    mail = models.EmailField(max_length=100)    message = models.CharField(max_length=100)

新建form

class ContactForm2(forms.ModelForm):    class Meta:        model=RemarkForm                     #表明这个表单继承自叫 RemarkForm的模型        fields=('mail','message',)           #指定表单继承模型的哪些属性def remark(request):    if request.method=='POST':        form=ContactForm2(request.POST)         if form.is_valid():            mail=form.cleaned_data['mail']            topic=form.cleaned_data['topic']             return HttpResponse(mail+topic)  #这里有点问题    else:        form=ContactForm2()    return render_to_response('message.html',{'form':form},RequestContext(request)) 

新建urls

(r’^message/$’,remark),

新建模版

[root@localhost mysite16_5_demo4]# more news/templates/message.html {% extends "list_article.html" %}{% block contact %}  <form action="/message/" method="POST">    {% for field in form %}       <div class="fieldWrapper">     {{ field.label_tag }}:{{ field }} {{ field.errors }}     </div>    {% endfor %}     <div class="fieldWrapper">      <p><input type="submit" value="留言" /></div>   </form>{% endblock %}[root@localhost mysite16_5_demo4]# 

演示效果(比代码多了一个字段)

第三种方式(未测试):《The Django Book—–中文版.pdf》P132

我们的出版商模型拥有一个名字,地址,城市,州(省),国家和网站。在form中重复这个信息无疑违反了DRY原则。我们可以使用一个捷径:form_for_model():

点这里可以跳转到人工智能网站

发表评论