Django:提交表单时获取NoReverseMatch,URL会Sl弹

时间:2019-12-07 05:41:12

标签: python django

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

我遇到了问题。我有这样的形式: enter image description here

当我点击提交按钮时,应该重定向到http://127.0.0.1:8000/triplist/johor-bahru/。相反,我收到此错误:

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中的代码:

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中的代码:

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中的代码:

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中的代码:

from django.apps import AppConfig


class TripsConfig(AppConfig):
    name = 'trips'

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

from django.apps import AppConfig


class AddactivityConfig(AppConfig):
    name = 'addactivity'

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

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中的代码:

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中的代码:

from . import views
from django.urls import path

app_name = 'addactivity'

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

]

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

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中的代码:

{% 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 %}

return HttpResponseRedirect(reverse('trips:activity'))中有问题吗?

Trips 文件夹内的urls.py中,有一个子弹。

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

我找不到在 addactivity 文件夹中的views.py中用我的代码重定向到笨拙的网页的方法。作为一个初学者,我无法解决这个问题。所以,我需要帮助。

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

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

这里是link to my project files

1 个答案:

答案 0 :(得分:0)

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

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

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

if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect(instance.get_absolute_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())