该视图未返回HttpResponse对象。它使用Django返回None。

时间:2019-12-13 18:54:07

标签: python django httpresponse modelform

因此,我正在尝试使用Django在HTML中显示表单,它必须是在数据库中创建新页面的表单。 我正在使用ModelForm,因为我读过的书是向用户提供用于在数据库中输入数据的工具的最佳方法。

在views.py中:


       from django.shortcuts import redirect, render
       from django.http import HttpResponse
       from .models import Pages, PagesForm
       from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
       from django.contrib.auth import login, logout, authenticate
       from django.contrib import messages
       from .forms import NewUserForm


def homepage(request):
    return render(request = request,
                  template_name='main/home.html',
                  context = {})
def pages(request):
    if request.method == "POST":
        form = PagesForm(request.POST)
        if form.is_valid():
            pass
            #nada, solo activa la validación
        else:
            form = PagesForm()    
            return render(request,
                        template_name='main/pages.html',
                        context = {"Pages":PagesForm.objects.all})

在models.py中:

from django.db import models
from datetime import datetime
from django.forms import ModelForm
# Create your models here.


#Pages son entradas del diario
class Pages(models.Model):
    title = models.CharField(max_length=300)
    content = models.TextField()
    author = models.CharField(max_length=50)
    published_date = models.DateTimeField("Published: ", default=datetime.now())

    def __str__(self):
        return self.title

class PagesForm(ModelForm):
    class Meta:
        model = Pages
        fields = '__all__'  

在pages.html中:

{% extends "main/header.html" %}


{% block content %}
<div>
  {% for page in Pages %}
  <h2>Display recent pages</h2>
      <div class="col s12 m6 l4">
        <div class="card blue-grey darken-1">
          <div class="card-content white-text">
            <span class="card-title">{{page.title}}</span>
            <p>{{page.published_date}}</p>
            <p>{{page.author}}</p>
            <p>{{page.content|safe}}</p>
            <div class="card-action">
              <a href="#">Leer más</a>
              </div>
          </div>
        </div>
      </div>

  {% endfor %}
</div>

<h2>Create a new page</h2>

<br>
    <form method="POST">
        {% csrf_token %}
        {{form.as_p}}
        <button style="background-color:#F4EB16; color:blue" class="btn btn-outline-info" type="submit">Submit</button>
    </form>


{% endblock %}

感谢您的帮助,非常感谢!

1 个答案:

答案 0 :(得分:0)

像这样更改视图     def页面(请求):

def count_dominators(items): # works but takes a very long time to execute.
    k = 0
    for idx,item in enumerate(items):

        dominator = True
        for ritem in items[idx+1:]:

            if item<=ritem:
                dominator = False
                break
        if dominator:

            k = k+1        
    return k