Django不采用get_absolute_url方法

时间:2019-04-06 03:03:10

标签: python django

我正在尝试制作一个类似于博客文章显示Spikeball游戏统计信息的应用程序。 Django并没有选择我的models.py中的get absolute url方法。

在models.py中,我尝试反转到详细游戏形式的绝对URL,但django没有选择它,这意味着我定义了函数,但仍然收到错误提示,但没有。

这是我的模型。py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Game(models.Model):
    game = models.CharField(max_length=100, blank=True,null=True)
    score = models.CharField(max_length=10, blank=True,null=True)
    winner = models.CharField(max_length=20, default=None, blank=True,null=True)
    date_played = models.DateField(default=timezone.now)
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    player1 = models.CharField(max_length=20, blank=True,null=True)
    player2 = models.CharField(max_length=20, blank=True,null=True)
    player3 = models.CharField(max_length=20, blank=True,null=True)
    player4 = models.CharField(max_length=20, blank=True,null=True)

    def __str__(self):
        return self.game

    def get_absolute_url(self):
            return reverse('spike_stats-detail', kwargs={'pk': self.pk})

这是我的views.py:

from django.shortcuts import render
from django.views.generic import (
    ListView, 
    DetailView, 
    CreateView
)
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Game


def home(request):

    context = {
        'games': Game.objects.all()
    }
    return render(request, 'spike_stats/home.html', context)


class GameListView(ListView):
    model = Game
    template_name = 'spike_stats/home.html' # <app>/<model>_<viewtype>.html
    context_object_name = 'games'
    ordering = ['-date_played'] # minus sign orders from newest to oldest


class GameDetailView(DetailView):
    model = Game


class GameCreateView(LoginRequiredMixin, CreateView):
    model = Game
    fields = ['game', 'score', 'winner', 
    'player1', 'player2', 'player3', 'player4']

    def form_valid(self, form):
        game = form.save(commit=False)
        game.creator = self.request.user
        game.save()
        return super().form_valid(game)


def about(request):
    return render(request, 'spike_stats/about.html',
                  {'game': 'Game 1 about'})

urls.py:

from django.urls import path
from .views import (
    GameListView, 
    GameDetailView, 
    GameCreateView
)
from . import views

urlpatterns = [
    path('', GameListView.as_view(), name='spike_stats-home'),
    path('game/<int:pk>/', GameDetailView.as_view(), name='spike_stats-detail'),
    path('game/new/', GameCreateView.as_view(), name='spike_stats-create'),
    path('about/', views.about, name='spike_stats-about'),
]

game_detail.html表单:

{% extends "spike_stats/base.html" %}
{% block content %}
<article class="media content-section">
    <img class="rounded-circle article-img" src="{{ game.creator.profile.image.url }}" >
    <div class="media-body">
        <div class="article-metadata">
            <a class="mr-2" href="#">{{ object.author }}</a>
            <small class="text-muted">{{ object.date_played|date:"F d, Y" }}</small>
        </div>
        <h2 class="article-title">{{ object.game }}</h2>
        <p class="article-content">{{ object.score }}</p>
        <p class="article-content">{{ object.winner }}</p>
    </div>
</article>
{% endblock content %}

和我得到的追溯:

Environment:


Request Method: POST
Request URL: http://localhost:8000/game/new/

Django Version: 2.1.5
Python Version: 3.6.5
Installed Applications:
['spike_stats.apps.SpikeStatsConfig',
 'users.apps.UsersConfig',
 'crispy_forms',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in get_success_url
  116.                 url = self.object.get_absolute_url()

During handling of the above exception ('NoneType' object has no attribute 'get_absolute_url'), another exception occurred:

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/contrib/auth/mixins.py" in dispatch
  52.         return super().dispatch(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in post
  142.             return self.form_valid(form)

File "/Users/z_goodman/Spike_Board/spike_stats/views.py" in form_valid
  41.         return super().form_valid(game)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in form_valid
  126.         return super().form_valid(form)

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in form_valid
  57.         return HttpResponseRedirect(self.get_success_url())

File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in get_success_url
  119.                     "No URL to redirect to.  Either provide a url or define"

Exception Type: ImproperlyConfigured at /game/new/
Exception Value: No URL to redirect to.  Either provide a url or define a get_absolute_url method on the Model.

它应该仅重定向到详细的游戏表单。抱歉,我是Python和Stack Overflow的新手。

1 个答案:

答案 0 :(得分:1)

您的问题在以下一行:return super().form_valid(game)-您正在将game传递到您的超类中,而不是最初打算的form

您需要将视图更改为如下形式:

class GameCreateView(LoginRequiredMixin, CreateView):
    model = Game
    fields = ['game', 'score', 'winner', 
    'player1', 'player2', 'player3', 'player4']

    def form_valid(self, form):
        game = form.save(commit=False)
        game.creator = self.request.user
        game.save()
        return super().form_valid(form)