【问题标题】:How to render a POST and make it show up on another page如何呈现 POST 并使其显示在另一个页面上
【发布时间】:2012-10-20 10:06:22
【问题描述】:

我正在尝试创建一个类似于 craigslist 的市场网站。 我根据 Django 教程“使用表单”创建了一个表单,但我不知道如何呈现从 POST 表单中获得的信息。 我想让我从 POST 获得的信息(主题、价格...等)显示在这样的另一个页面上。 http://bakersfield.craigslist.org/atq/3375938126.html 并且,我希望这个产品(例如 1960 法国椅)的“主题”(请查看 form.py)显示在这样的另一个页面上。 http://bakersfield.craigslist.org/ata/}

我可以就处理提交的信息获得一些建议吗? 这是目前的代码。感谢您的所有回答和帮助。

◆forms.py

from django import forms

class SellForm(forms.Form):
    subject = forms.CharField(max_length=100)
    price = forms.CharField(max_length=100)
    condition = forms.CharField(max_length=100)
    email = forms.EmailField()
    body = forms.TextField()

◆views.py

from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect
from site1.forms import SellForm

def sell(request):

    if request.method =="POST":
        form =SellForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            price = form.cleaned_data['price']
            condition = form.cleaned_data['condition']
            email = form.cleaned_data['email']
            body = form.cleaned_data['body']

            return HttpResponseRedirect('/books/')

    else:
        form=SellForm()

    render(request, 'sell.html',{'form':form,})

◆urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^sechand/$','site1.views.sell'),
    url(r'^admin/', include(admin.site.urls)),

)

◆sell.html

<form action = "/sell/" method = "post">{% csrf_token%} 
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>             

【问题讨论】:

    标签: django django-forms django-views render


    【解决方案1】:

    我假设您的数据库中有一个Sell 模型/表(您存储用户的“销售”),否则它没有任何意义。这意味着您可以节省一些时间并使用ModelForm, 而不是简单的Form。模型表单接受一个数据库表并为其生成一个 html 表单。

    forms.py

    from django.forms import ModelForm
    from yourapp.models import Sell
    
    class SellForm(ModelForm):
        class Meta:
            model = Sell
    

    在您的views.py 中,您需要一个显示用户拥有的Sells 的视图 贴出来给别人看。您还需要一个 html 模板,该视图将呈现每个 Sell 的上下文。

    sell_display.html

    {% extends 'some_base_template_of_your_site.html' %}
    {% block content %}
    <div id="sell">
      <h3> {{ sell.subject }}</h3>
      <p> {{ sell.condition }}</p>
      <p> {{ sell.body }}</p>
      <!-- the rest of the fields.. -->
    </div>
    {% endblock %}
    

    我们还需要一个新的 url 条目来显示特定的Sell

    urls.py

    from django.conf.urls import patterns, include, url
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
        # Changed `sell` view to `sell_create`
        url(r'^sechand/$','site1.views.sell_create'),
        # We also add the detail displaying view of a Sell here
        url(r'^sechand/(\d+)/$','site1.views.sell_detail'),
        url(r'^admin/', include(admin.site.urls)),
    )
    

    views.py

    from django.http import HttpResponseRedirect
    from django.shortcuts import render_to_response, get_object_or_404
    from yourapp.models import Sell
    from yourapp.forms import SellForm
    
    def sell_detail(request, pk):
        sell = get_object_or_404(Sell, pk=int(pk))
        return render_to_response('sell_display.html', {'sell':sell})
    
    def sell_create(request):
        context = {}
        if request.method == 'POST':
            form = SellForm(request.POST)
            if form.is_valid():
                # The benefit of the ModelForm is that it knows how to create an instance of its underlying Model on your database.
                new_sell = form.save()   # ModelForm.save() return the newly created Sell.
                # We immediately redirect the user to the new Sell's display page
                return HttpResponseRedict('/sechand/%d/' % new_sell.pk)
        else:
            form = SellForm()   # On GET request, instantiate an empty form to fill in.
        context['form'] = form
        return render_to_response('sell.html', context)
    

    我认为这足以让你继续前进。有一些模式可以使这些东西更加模块化和更好,但我不想给你太多信息,因为你是一个 django 初学者。

    【讨论】:

    • 非常感谢!现在我被重定向到“找不到页面(404)(我被重定向的URL是“Http~~/sell/”,因为我有“
      ”里面当我单击 POST 表单上的“提交”按钮时,该页面的内容。根据您的解释,我应该被重定向到新的 Sell 显示页面。我应该更改 sell.html 中的某些内容吗?
    • 使用上面的 urlspattenrs,表单操作应该是“/sechand/”。根据您的喜好进行相应调整。
    • 非常感谢,我已经成功创建了 Registration/Login/Logout/Profile/ 页面,并且感谢您的信息,“销售”页面(这些已发布产品的信息存储为“/ sechand/1/, /sechand/2/...")!另外,我创建了“产品”页面,其中包含一些类别(书籍、家具等,但现在我只关注“电子产品”)来显示我们通过“SellForm(ModelForm)”创建的产品信息页面。但是,我不知道如何将已发布的数据链接到“electronics.html”页面。如果您有空闲时间,请检查此问题。 (bit.ly/TA7Vl2)
    • @stack5914 如果您觉得我的回答对您有所帮助,那么习惯上将accept它作为正确答案。我可能会在明天看看你的其他答案,因为我不在城里。欢呼
    • 我接受了 :) 我让我的问题更加具体和简洁。 (stackoverflow.com/questions/13224213/…) 所以如果可能的话,请看看这个问题而不是前一个问题。
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2022-07-05
    • 2010-10-13
    • 2011-09-20
    • 2018-04-22
    相关资源
    最近更新 更多