Home > Enterprise >  Django URLs not updating after slug change
Django URLs not updating after slug change

Time:01-03

I use Slugify. After making a change in slug for all objects in Entry, slug still shows as old slug. If I refresh obj page, I get a page not found, unless I click "back" and then reopen the obj page, and that is when the obj page will load and new slug will update.

Any idea how to fix this?

I tried an empty migration and applied obj.save() and obj.refresh_from_db() but no luck.

Below is my model, this is what generates my slug field: (My change was removed self.4 and replaced with self.5)

class Entry(models.Model)
    1 = ...
    2 = ...
    3 = ...
    4 = ...
    5 = ...
    slug = models.SlugField(null=True, unique=True, max_length=300)



    def save(self, *args, **kwargs):
        self.slug = slugify(f"{self.1}-{self.2}-{self.3}-{self.5}")
        return super().save(*args, **kwargs)

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

View:

def post_page(request, slug):
    form = PostForm()
    entry = Entry.objects.get(slug=slug)
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.cleaned_data['post']
            post = form.save(commit=False)
            post.entry = entry
            post.save()

            return redirect('post_page', slug=entry.slug)
        else:
            msg_error = 'Please correct errors and resubmit'
            return render(request, 'post_page.html', {'entry': entry, 'form':form, 'msg_error':msg_error})

    return render(request, 'post_page.html', {'entry': entry, 'form':form})

Url:

path('post-page/<slug>/', views.post_page, name='post_page'),

CodePudding user response:

try

path('post-page/<slug:slugname>/', views.post_page, name='post_page'),

def post_page(request, slugname):
    form = PostForm()

    entry = get_object_or_404(Entry, slug=slugname)

    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.cleaned_data['post']
            post = form.save(commit=False)
            post.entry = entry
            post.save()

            return redirect('post_page', slug=entry.slug)
        else:
            msg_error = 'Please correct errors and resubmit'
            return render(request, 'post_page.html', {'entry': entry, 'form':form, 'msg_error':msg_error})

    return render(request, 'post_page.html', {'entry': entry, 'form':form})

CodePudding user response:

You need to change URL pattern like this

path('post-page/<slug:slug>/', views.post_page, name='post_page'),

CodePudding user response:

Found a solution

In shell:

for obj in Entry.objects.all():
        obj.save()
  • Related