Django:提交表单时获取NoReverseMatch,URL出现错误 [英] Django: Getting NoReverseMatch While Submitting the Form, URL has Slug

查看:56
本文介绍了Django:提交表单时获取NoReverseMatch,URL出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过构建一个名为TravelBuddies的应用程序来学习Django.它将允许旅行者计划行程并保留相关的旅行项目(例如预订,机票,护照副本,保险信息等),以及为日常活动创建提醒.该应用程序还将能够向旅行者更新本地信息,例如天气或每日新闻.旅行者还可以与某人共享旅行信息,或者让某人与他们合作以计划行程.

I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip.

我遇到了问题.我有这样的形式:

I am facing a problem. I have a form like this:

当我点击提交按钮时,应该重定向到

When I click on the Submit button, I am supposed to be redirected to http://127.0.0.1:8000/triplist/johor-bahru/. Instead, I get this error:

NoReverseMatch at /addactivity/
Reverse for 'activity' with no arguments not found. 1 pattern(s) tried: ['triplist/(?P<slug>[-a-zA-Z0-9_]+)/$']
Request Method: POST
Request URL:    http://127.0.0.1:8000/addactivity/
Django Version: 3.0
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'activity' with no arguments not found. 1 pattern(s) tried: ['triplist/(?P<slug>[-a-zA-Z0-9_]+)/$']

这是我在 Trips 文件夹中的 models.py 中的代码:

Here are my codes in models.py inside Trips folder:

from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify

# Create your models here.
class Trip(models.Model):
    trip_name = models.CharField(max_length=100)
    date = models.DateField()
    planner_name = models.CharField(max_length=100)
    add_coplanner = models.ManyToManyField(User)
    trip_description = models.CharField(max_length=1000, default='null')
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.trip_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.trip_name)
        super().save(*args, **kwargs)

class Activity(models.Model):
    trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
    activity_name = models.CharField(max_length=100)
    date = models.DateField()
    time = models.TimeField()
    location = models.CharField(max_length=100)
    activity_description = models.CharField(max_length=1000, default='null')
    item_type = models.CharField(max_length=100)
    item_number = models.CharField(max_length=100)
    add_cotraveller = models.ManyToManyField(User)
    slug = models.SlugField(max_length=150, default='null')


    def __str__(self):
        return self.activity_name

    def save(self):
        super(Activity, self).save()
        self.slug = '%i-%s' % (
            self.id, slugify(self.trip.trip_name)
        )
        super(Activity, self).save()

这是我在 Trips 文件夹中的 views.py 中的代码:

Here are my codes in views.py inside Trips folder:

from django.views import generic
from .models import Trip, Activity


class TripListView(generic.ListView):
    template_name = 'trips/triplist.html'
    context_object_name = 'all_trips'

    def get_queryset(self):
        return Trip.objects.all()


class ActivityView(generic.DetailView):
    model = Trip
    template_name = 'trips/activity.html'

这是我在 Trips 文件夹中的 urls.py 中的代码:

Here are my codes in urls.py inside Trips folder:

from . import views
from django.urls import path

app_name = 'trips'

urlpatterns = [
    path('triplist/', views.TripListView.as_view(), name='triplist'),
    path('triplist/<slug:slug>/', views.ActivityView.as_view(), name='activity'),
]

这是我在行程文件夹中的 apps.py 中的代码:

Here are my codes in apps.py inside trips folder:

from django.apps import AppConfig


class TripsConfig(AppConfig):
    name = 'trips'

这是我在 addactivity 文件夹中的 apps.py 中的代码:

Here are my codes in apps.py inside addactivity folder:

from django.apps import AppConfig


class AddactivityConfig(AppConfig):
    name = 'addactivity'

这是我在 addactivity 文件夹中的 forms.py 中的代码:

Here are my codes in forms.py inside addactivity folder:

from django.forms import ModelForm
from trips.models import Activity

class ActivityForm(ModelForm):
    class Meta:
        model = Activity
        fields = ['trip', 'activity_name', 'date', 'time', 'location', 'activity_description', 'item_type', 'item_number', 'add_cotraveller']

这是我在 addactivity 文件夹中的 forms.py 中的代码:

Here are my codes in forms.py inside addactivity folder:

from django.forms import ModelForm
from trips.models import Activity

class ActivityForm(ModelForm):
    class Meta:
        model = Activity
        fields = ['trip', 'activity_name', 'date', 'time', 'location', 'activity_description', 'item_type', 'item_number', 'add_cotraveller']

这是我在 addactivity 文件夹中的 urls.py 中的代码:

Here are my codes in urls.py inside addactivity folder:

from . import views
from django.urls import path

app_name = 'addactivity'

urlpatterns = [
    path('addactivity/', views.AddActivityFormView.as_view(), name='addactivity'),

]

这是我在 addactivity 文件夹内的 views.py 中的代码:

Here are my codes in views.py inside addactivity folder:

from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import ActivityForm
from trips.models import Activity
from django.http import HttpResponseRedirect
from django.urls import reverse

# Create your views here.


class AddActivityFormView(TemplateView):
    template_name = 'addactivity/addactivityform.html'

    def get(self, request):
        form = ActivityForm()
        activities = Activity.objects.all()
        args = {'form': form, 'activities': activities}
        return render(request, self.template_name, args)

    def post(self, request):
        form = ActivityForm(request.POST)
        if form.is_valid():
            form.save()
            trip = form.cleaned_data['trip']
            activity_name = form.cleaned_data['activity_name']
            date = form.cleaned_data['date']
            time = form.cleaned_data['time']
            location = form.cleaned_data['location']
            activity_description = form.cleaned_data['activity_description']
            item_type = form.cleaned_data['item_type']
            item_number = form.cleaned_data['item_number']
            add_cotraveller = form.cleaned_data['add_cotraveller']

            args = {'form': form, 'trip': trip, 'activity_name': activity_name, 'date': date, 'time': time, 'location': location, 'activity_description': activity_description, 'item_type': item_type, 'item_number': item_number, 'add_cotraveller': add_cotraveller}
            return HttpResponseRedirect(reverse('trips:activity'))

这是我在 templates> addactivity 文件夹内的 addactivityform.html 中的代码:

Here are my codes in addactivityform.html inside templates > addactivity folder:

{% extends 'base.html' %}
{% load static %}

{% block title %} Add Activity {% endblock %}

{% block content %}

<div class="container">
    <h2>Add New Activity</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
</div>

{% endblock %}

返回HttpResponseRedirect(reverse('trips:activity'))有什么问题吗?

Trips 文件夹中的 urls.py 中,有一个条.

In urls.py inside Trips folder, there is a slug.

path('triplist/<slug:slug>/', views.ActivityView.as_view(), name='activity'),

我想不通一种方法,可以使用 addactivity 文件夹中的 views.py 中的代码重定向到带有with的网页.作为一个初学者,我无法解决这个问题.所以,我需要帮助.

I can't figure out a way to redirect to a web page with slug with my codes in views.py inside addactivity folder. Being a beginner, I am unable to solve the issue. So, I need help.

更新:我已在问题的 templates> addactivity 文件夹内的 addactivityform.html 中添加了我的代码.

Update: I have added my codes in addactivityform.html inside templates > addactivity folder in the question.

我还在Stackoverflow上找到了类似的问题和答案.但是,我仍然无法解决问题.

I also found similar questions and answers at Stackoverflow. But still, I can't solve the issue.

这是链接到我的项目文件.

推荐答案

更好的方法是在活动模型中定义一个get absolute方法,然后在视图中调用它.

A better way is define a get absolute method in your activity model and call it in your views.

def get_absolute_url(self):
        return reverse("trips:activity", kwargs={"slug": self.slug})

并通过以下方式在您的视图中重定向:

and redirect in your views following way:

if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect(instance.get_absolute_url())

或者,如果您使用通用的创建视图,则可以执行以下操作并提供成功的网址

Or if you use generic create view you can do as follows and give a success url

class TripCreateView(CreateView):
    model = Trip
    form_class = TripCreateForm
    template_name = 'your_remplate.html'

    def form_valid(self, form):
    ---------
    ---------
    return HttpResponseRedirect(self.get_success_url())

这篇关于Django:提交表单时获取NoReverseMatch,URL出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆