Home > Mobile >  Error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model

Time:12-13

i'm working on a django project to create football trainings. I'm testing the model and its saving. The problem appears when I try to save it, must be something about redirection, because in the database the training does get saved, but it doesn't redirect me anywhere and the error comes out.

models.py

from django.db import models
from django.utils import timezone
from users.models import User


class Entrenamiento(models.Model):
    autor = models.ForeignKey(User, on_delete=models.CASCADE)
    idEntrenamiento = models.AutoField(primary_key=True)
    idEquipo = models.IntegerField()
    fecha = models.DateTimeField(default=timezone.now)
    idDireccionCampo = models.IntegerField()
    temporadas = [
        ('2022/2023','2022/2023'),
        ('2023/2024','2023/2024'),
        ('2024/2025','2024/2025'),
        ('2025/2026','2025/2026')
    ]
    temporada = models.CharField(max_length=50, choices=temporadas, default='2022/2023')

    def __str__(self):
        return 'Entrenamiento {}'.format(self.idEntrenamiento)

    @property
    def entreno(self):
       return 'Entrenamiento {} de {} para {} con fecha del {}, será en el campo {}'.format(self.idEntrenamiento, self.temporada, self.idEquipo, self.fecha, self.idDireccionCampo)

views.py

from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.models import User
from django.contrib import messages
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.views.generic import (CreateView, DeleteView, DetailView, ListView,UpdateView)
from django import forms
from django.urls import reverse_lazy

from .models import Entrenamiento


def home(request):
    context = {
        'entrenamientos': Entrenamiento.objects.all()
    }
    return render(request, 'entrenamientos/entrenamientos.html', context)

class PostListView(ListView):
    model = Entrenamiento
    template_name = 'entrenamientos/entrenamientos.html'#<app>/<model>_<viewtype>.html
    context_object_name = 'entrenamientos'
    ordering = ['-fecha']

class PostDetailView(DetailView):
    model = Entrenamiento

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Entrenamiento
    fields = ['autor','idEntrenamiento','idEquipo','idDireccionCampo','fecha']
    widgets = {'fecha': forms.DateInput(attrs={'type': 'date'})}


    def form_valid(self,form):
        form.instance.autor = self.request.user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Entrenamiento
    fields = ['autor','idEntrenamiento','idEquipo']

    def form_valid(self,form):
        form.instance.autor = self.request.user
        return super().form_valid(form)

    def test_func(self):
        entrenamiento = self.get_object()
        if self.request.user == entrenamiento.autor:
            return True
        return False

class PostDeleteView(DeleteView):
    model = Entrenamiento
    success_url = '/'

    def test_func(self):
        entrenamiento = self.get_object()
        if self.request.user == entrenamiento.autor:
            return True
        return False

urls.py

    from django.urls import path
    from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
    from django.contrib.auth.decorators import login_required
    
    app_name = 'entrenamientos'
    
    urlpatterns = [
        path('', login_required(PostListView.as_view()), name='entrenamientos'),
        path('entrenamiento/<int:pk>/',login_required( PostDetailView.as_view()), name='entrenamiento-detail'),
        path('entrenamiento/new/',login_required( PostCreateView.as_view()), name='entrenamiento-create'),
        path('entrenamiento/<int:pk>/update/',login_required( PostUpdateView.as_view()), name='entrenamiento-update'),
        path('entrenamiento/<int:pk>/delete/',login_required( PostDeleteView.as_view()), name='entrenamiento-delete'),
        path('entrenamiento', login_required(PostListView.as_view()), name='entrenamientos')
    ]

The error:

ImproperlyConfigured at /entrenamientos/entrenamiento/new/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

I think that something it's wrong with: def form_valid(self,form):

I've tried adding this in the def form_valid but another error appears

    # success_url = reverse_lazy('entrenamiento')
    # success_message = 'Entrenamiento añadido'

I hope the solution

CodePudding user response:

You have to provide success_url inside your class view. You can do it in one of possibilities, but the first one is enough for this problem:

class PostCreateView(LoginRequiredMixin, CreateView):
    ...
    success_url = reverse_lazy('entrenamientos:entrenamientos')

    # OR
    def get_success_url(self):
        return reverse_lazy('entrenamientos:entrenamientos')

Also look at your urls:

urlpatterns = [
    path('', login_required(PostListView.as_view()), name='entrenamientos'),
    ...
    path('entrenamiento', login_required(PostListView.as_view()), name='entrenamientos')
]

You have set two urls with exactly the same name. You should not do that. Always the first one will be rendered with {% url %} tag. Do you even need the second one?

  • Related