I'm trying to make an automatic slug using the slugify in django.utils.text
. The following are my code:
# models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(allow_unicode=True)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
thumb = models.ImageField(default='default.png', blank=True)
author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
def save(self, *args, **kwargs):
self.slug = slugify(self.title, allow_unicode=True)
super().save(*args, **kwargs)
def __str__(self):
return self.title
# article_create.html
{% extends 'base.html' %}
{% block content %}
<div class="create-article">
<h2>Awesome New Article </h2>
<form class='site-form' action="{% url 'articles:article_create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="create">
</form>
</div>
{% endblock %}
# html template - article_lists.html
...
<a href="{% url 'articles:article_details' article.slug %}"></a>
...
I used the allowed_unicode=True in order to allow different languages to be used, but the following error comes up when I type in Korean in the title in the form:
The first underlined is the title of the article that I'm trying to post, and the second underline is the Django backend checking the slug, but I see that it doesn't recognize the Korean letters... I did what all the other similar StackOverflow, including putting the allow_unicode=True
, but it's not working. What must be wrong here???
*edit: This is the urls.py
code:
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name="article_list"),
path('create/', views.article_create, name="article_create"),
path('<slug:slug>/', views.article_details, name='article_details'),
]
Found out the reason to this! it wasn't working it was because of the urls.py
Before:
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
...
path('<slug:slug>/', views.article_details, name='article_details'),
]
After:
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
...
path('<slug>/', views.article_details, name='article_details'),
]
I had to change the <slug:slug>
to <slug>
... I really don't know the reason why and maybe it's just for in Korean, but this was the right way for me.