【问题标题】:NoReverseMatch at /tinku/update/tinku/update 中的 NoReverseMatch
【发布时间】:2020-03-31 12:13:33
【问题描述】:

没有找到参数的“update_student”反向。尝试了 1 种模式:['(?P[-a-zA-Z0-9_]+)/update$']

上面显示错误,请告诉是否有人知道如何解决这个问题

urls.py

path('',views.index,name="home"),
path('<slug:name>/update',views.student_update,name="update_student"),
path('delete/<slug:name>',views.student_delete,name="delete_student")

student_update.html

<div class=" row d-flex justify-content-center">
<div class="col-md-6 box-shadow">
    <form action="{% url 'update_student' %}" method="POST" class="form">
        {% csrf_token %}
        {{updateform|crispy}}

    <button class="btn btn-primary form-control">update</button>
    </form>
</div>

views.py:-

def student_update(request,name):
instance=get_object_or_404(Student,name=name) 
print(instance) 
form=StudentForm(request.POST,instance=instance)
print(form)
if form.is_valid():
    form.save()
    return redirect('home')

return render(request,'webapp/student_update.html',{'updateform':form})

models.py

from django.db import models

从 django.core.validators 导入 MaxValueValidator,MinValueValidator from django.contrib.auth.models 导入用户

类学生(models.Model): 性别=( ('M','男'), ('F','女') )

name=models.CharField(max_length=50)
age=models.PositiveIntegerField(validators=[MinValueValidator(18),MaxValueValidator(50)])
sex=models.CharField(max_length=1,choices=gender)

def __str__(self):
    return self.name

forms.py

from django import forms

从 django.core.validators 导入 MaxValueValidator,MinValueValidator 从 webapp.models 导入学生

类StudentForm(forms.ModelForm):

class Meta:
    model = Student
    fields=['name','age','sex']

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的模板中有{% url 'update_student' %}(表单操作),这会导致错误,因为update_student 模式需要name 参数。

    因此,您要么需要将其更改为 {% url 'update_student' name=form.instance.name %},但由于您的表单发布到与呈现表单相同的 url,因此完全删除 action 属性会更容易。

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      相关资源
      最近更新 更多