在 Django 中:为什么当我尝试在 notes.html 页面中使用 html 表单创建新笔记时没有任何反应

in Django : Why nothing happens when I try to Create new note with the html form in the notes.html page

我刚刚通过关注 YouTube 上的视频开始了我的第一个 Django 应用程序。 该应用程序是一个学生仪表板,具有 8 种工具和功能,可帮助学生做笔记、搜索帮助、保存书籍等

当我按照这些步骤进行操作时,我陷入了创建新笔记的过程中,但笔记来自管理员端,而是来自具有 脆皮形式 和创建的实际笔记模板按钮。 该程序应该用于编写标题和描述(笔记的内容),然后按下创建按钮。当我尝试点击时,没有任何反应。


#这是仪表板应用程序中的 view.py 页面:

    from django.shortcuts import render
    from . forms import *
    from django.contrib import messages
    # Create your views here.
    
    
    def home(request):
        return render(request, 'dashboard/home.html')
    
    def notes(request):
        if request.method == "POST":
            form = NotesForm(request.POST)
            if form.is_valid():
                notes = Notes(user=request.user,title=request.POST['title'],description=request.POST['description'])
                notes.save()
            messages.success(request,f"Notes Added from {request.user.username} Successfully")
        else:
         form = NotesForm()
        notes = Notes.objects.filter(user=request.user)
        context = {'notes':notes,'form':form}
        return render(request,'dashboard/notes.html',context)

这是仪表板应用 > 模板文件夹 > 仪表板文件夹中的 notes.html 页面:

{% extends 'dashboard/base.html' %}
<!-- Load the static files here -->
{% load static %} {% load crispy_forms_tags %}
<!-- loading the crispy files must be here so now i write anything to
     create some space and lines here we go baby lets add more -->
{% block content %}
<div class="container">
  <div class="row">
    {% for note in notes %}
    <div class="col-md-3">
      <a href="#">
        <div class="card">
          <div class="card-header">{{note.title}}</div>
          <div class="card-body">{{note.description|slice:"0:100"}}</div>
          <div class="card-footer mt-auto">
            <a href="#"> <i class="fa fa-trash fa-2x"></i></a>
          </div>
        </div>
      </a>
    </div>
    {% endfor %}
    <br /><br />
  </div>
</div>
<br /><br />
<div class="container">
  <form method="POST">
   {% csrf_token %}
    <fieldset class="form-group">
      <legend class="border-bottom mb-4">Create Notes</legend>
    </fieldset>
    {% crispy form %}
    <div class="form-group">
      <button href="" class="btn btn-outline-info" type="submit">Create</button>
    </div>
  </form>
</div>
{% endblock content %}

所以,这也是 models.py 文件

from django.db import models
from django.contrib.auth.models import User
# Create your models here.


class Notes(models.Model):
 user = models.ForeignKey(User, on_delete=models.CASCADE)
 title = models.CharField(max_length=200) 
 description = models.TextField() 
 def __str__(self):
   return self.title 
 class Meta:
   verbose_name = "notes" 
   verbose_name_plural = "notes"

如果不是这里的问题,请看里面这个forms.py

from dataclasses import fields
from django import forms
from . models import *

class NotesForm(forms.ModelForm):
  class Meta:
    model = Notes 
    fields = ['title', 'description']

和.. urls.py

from django.urls import path 
from . import views 


urlpatterns = [
    path('',views.home, name='home'), 
  path('notes',views.notes, name="notes")
]

代码中有很多小错误:

  1. 显示格式是{{form|crispy}}不是{% crispy form %}

  2. POST 数据保存表单后,您也没有使用 HttpResponseRedirect[django-doc] 进行重定向,您应该始终 return 和 HttpResponse,这是一个很好的做法。

试试下面的代码:

Notes.html

{% block content %}
{% load crispy_forms_tags %}

<div class="container">
<div class="row">
    {% for note in notes %}
    <div class="col-md-3">
    <a href="#">
        <div class="card">
        <div class="card-header">{{note.title}}</div>
        <div class="card-body">{{note.description|slice:"0:100"}}</div>
        <div class="card-footer mt-auto">
            <a href="#"> <i class="fa fa-trash fa-2x"></i></a>
        </div>
        </div>
    </a>
    </div>
    {% endfor %}
    <br /><br />
</div>
</div>
<br /><br />
<div class="container">
<form method="POST" action="{% url 'notes' %}" novalidate>
    {% csrf_token %}
    <fieldset class="form-group">
    <legend class="border-bottom mb-4">Create Notes</legend>
    </fieldset>
    {{form|crispy}}
    <input type="submit" value="Create">
</form>
</div>

{% endblock content %}

views.py


from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.shortcuts import render
from . forms import *
from django.contrib import messages
from django.urls import reverse


def home(request):
    return render(request, 'dashboard/home.html')


def notes(request):
    if request.method == "POST":
        form = NotesForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            descrip = form.cleaned_data['description']
            notes = Notes(
                user=request.user, title=title, description=descrip)
            notes.save()
            messages.success(
                request, f"Notes Added from {request.user.username} Successfully")
            return HttpResponseRedirect(reverse('thanks'))
    else:
        form = NotesForm()
    notes = Notes.objects.filter(user=request.user)
    context = {'notes': notes, 'form': form}
    return render(request, 'dashboard/notes.html', context)


def thanks(request):
    return render(request, 'dashboard/thanks.html')

urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.home, name='home'),
    path('notes/', views.notes, name="notes"),
    path('thanks/', views.thanks, name='thanks')
]

thanks.html

<body>
    <h2>The form successfully submitted</h2>
</body>

你的forms.py可以保持原样。