简体   繁体   中英

Can't get forms to render in Django

I'm working on a project and I don't get the django forms to render on any of my pages. I've compared it to django girls code, as that is what I usually consult but it looks virtually identical to it. It's not just this page, my other pages have issues with rendering the forms as well. Here's the code:

Views.py

from django.shortcuts import render
from .models import *
from .forms import *
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.db.models import Sum
from django.utils import timezone
from django.views.decorators.http import require_POST
from .cart import Cart
from django.db import transaction
from django.contrib import messages


@login_required
def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=Post)
    return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})

Forms.py

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text',)

post_edit.html

{% extends 'rentadevapp/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<head>
    <link rel="stylesheet" href="{% static 'css/post_edit.css' %}">
</head>
<body>
    <div class="container"><br>
        <h2>New Post</h2><br>
        <form method="POST" class="post-form">{% csrf_token %}
            {{ form.as_p }}
            <button type="submit" class="save btn btn-default">Save</button>
        </form>
    </div>
</body>
{% endblock %}

Models.py

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now)
    updated_date = models.DateTimeField(auto_now_add=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, default='0')

    class Meta:
        ordering = ('title',)

    def created(self):
        self.created_date = timezone.now()
        self.save()

    def updated(self):
        self.updated_date = timezone.now()
        self.save()

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

I'm pretty stuck and have spent a couple hours trying to figure this out. Any help is really appreciated. Thanks!

Your form isn't returned to the template in the context.

In Django 1.11 or 2.2 the render function call in your view should return a dictionary of context variables as the third argument, but you've got two dictionaries. The 4th argument where you've got a dictionary containing the form is being passed as content_type which is then used in the HttpResponse so I'm quite surprised there isn't something strange happening or an error seen.

So you're doing;

return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})

What you need to do is;

context = {'form': form, 'rentadevapp': post_edit}

return render(request, 'rentadevapp/post_edit.html', context)

Prior to 1.10 render had a different signature, but the first three arguments of request, template_name, context have been that way since <1.8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM