[Answer]-How to render a POST and make it show up on another page

1đź‘Ť

âś…

I assume you have a Sell model/table in your db(where you store the users’ “sells”), otherwise it wouldn’t make any sense. This means you can save yourself some time and use a ModelForm,
instead of a simple Form. A model form takes a database table and produces an html form for it.

forms.py

from django.forms import ModelForm
from yourapp.models import Sell

class SellForm(ModelForm):
    class Meta:
        model = Sell

In your views.py you need one more view that displays the Sells that your users have
posted for others to see. You also need an html template that this view will render with context about each 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 %}

We also need a new url entry for the displaying of a specific 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)

This is enough to get you going I think. There are patterns to make these things more modular and better, but I don’t want to flood you with too much information, since you are a django beginner.

👤rantanplan

Leave a comment