Django modeltranslation slug problem. When i change language dont go right url











up vote
0
down vote

favorite












modeltranslation...



i change title, content and slug sections on my translation.py. Everything work is fine but i have a problem.



let me try to explain;



i have one post in my website and this post "slug" like this;



slug_en = some_en_slug



slug_fr = some_fr_slug



And i have one language changer on my navbar.



     {% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

<form action="{% url "set_language" %}" method="post" class="navbar-form navbar-right">
{% csrf_token %}
<div class="form-group">
<select name="language" class="form-control" onchange="this.form.submit()">
{% for language in languages %}
<option value="{{ language.code }}"
{% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}>
{{ language.name_local }}
</option>
{% endfor %}
</select>
</div>
</form>


Actually this lang. changer working fine. This is change all slug href url's on outside post... But this didnt change slug url in post page.



when i go this url;



https://example.com/en/en_slug



and after try change language, my browser is going this url;



https://example.com/fr/en_slug and i see 404 page..



i need to go to https://example.com/fr/fr_slug this url after change language ...



I dont have any idea for this. I would like your help.



urls.py
from django.urls import path
from . import views
from django.utils.translation import gettext_lazy as _

app_name = "article"


urlpatterns = [
path(_('dashboard/'),views.dashboard,name="dashboard"),
path(_('addarticle/'),views.addarticle,name="addarticle"),
path('<slug>',views.detail,name="detail"),
path('edit/<int:id>',views.editArticle,name="edit"),
path('delete/<int:id>',views.deleteArticle,name="delete"),
path(_('article/'),views.articles,name="article"),
path('comment/<int:id>',views.addcomment,name="comment"),
path('category/<slug>', views.category_detail,name="category_detail" )
]


models.py



from django.db import models
from ckeditor.fields import RichTextField
from django.utils.text import slugify

class Article(models.Model):

author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
title = models.CharField(max_length = 120, verbose_name="Title")
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
content = RichTextField(verbose_name="Content")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
image = models.ImageField(blank=True, null=True, verbose_name="Add Image (.jpg .png)")
slug = models.SlugField(unique=True, max_length = 130)

def __str__(self):
return self.title

def get_unique_slug(self):
slug = slugify(self.title.replace("ı","i"))
unique_slug = slug
counter = 1
while Article.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, counter)
counter += 1
return unique_slug

def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.get_unique_slug()
return super(Article, self).save(*args, **kwargs)


translation.py



from modeltranslation.translator import translator, TranslationOptions
from .models import Article

class ArticleTranslationOptions(TranslationOptions):
fields = ('title', 'content','slug')

translator.register(Article, ArticleTranslationOptions)


I think i need some changes in urls.py but i dont know :/



Thanks for help...










share|improve this question




















  • 1




    Are you sure you want the slug to be translated? I would think very carefully about this, because if someone with the fr setting finds a link somewhere (via Google) with the english slug, it will give a 404. If you really want slugs translated, I would change the detail view to handle all the possible languages by overriding get_object() (and either redirect to the url with the translated slug or just leave it in whatever language it was first).
    – dirkgroten
    8 hours ago












  • hey @dirkgroten thanks for answer. i think actually good for google for seo url. Why would you get a 404 page? And you have a solution for this ? can you show me sample codes please... Thanks
    – Aytek
    36 mins ago

















up vote
0
down vote

favorite












modeltranslation...



i change title, content and slug sections on my translation.py. Everything work is fine but i have a problem.



let me try to explain;



i have one post in my website and this post "slug" like this;



slug_en = some_en_slug



slug_fr = some_fr_slug



And i have one language changer on my navbar.



     {% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

<form action="{% url "set_language" %}" method="post" class="navbar-form navbar-right">
{% csrf_token %}
<div class="form-group">
<select name="language" class="form-control" onchange="this.form.submit()">
{% for language in languages %}
<option value="{{ language.code }}"
{% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}>
{{ language.name_local }}
</option>
{% endfor %}
</select>
</div>
</form>


Actually this lang. changer working fine. This is change all slug href url's on outside post... But this didnt change slug url in post page.



when i go this url;



https://example.com/en/en_slug



and after try change language, my browser is going this url;



https://example.com/fr/en_slug and i see 404 page..



i need to go to https://example.com/fr/fr_slug this url after change language ...



I dont have any idea for this. I would like your help.



urls.py
from django.urls import path
from . import views
from django.utils.translation import gettext_lazy as _

app_name = "article"


urlpatterns = [
path(_('dashboard/'),views.dashboard,name="dashboard"),
path(_('addarticle/'),views.addarticle,name="addarticle"),
path('<slug>',views.detail,name="detail"),
path('edit/<int:id>',views.editArticle,name="edit"),
path('delete/<int:id>',views.deleteArticle,name="delete"),
path(_('article/'),views.articles,name="article"),
path('comment/<int:id>',views.addcomment,name="comment"),
path('category/<slug>', views.category_detail,name="category_detail" )
]


models.py



from django.db import models
from ckeditor.fields import RichTextField
from django.utils.text import slugify

class Article(models.Model):

author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
title = models.CharField(max_length = 120, verbose_name="Title")
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
content = RichTextField(verbose_name="Content")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
image = models.ImageField(blank=True, null=True, verbose_name="Add Image (.jpg .png)")
slug = models.SlugField(unique=True, max_length = 130)

def __str__(self):
return self.title

def get_unique_slug(self):
slug = slugify(self.title.replace("ı","i"))
unique_slug = slug
counter = 1
while Article.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, counter)
counter += 1
return unique_slug

def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.get_unique_slug()
return super(Article, self).save(*args, **kwargs)


translation.py



from modeltranslation.translator import translator, TranslationOptions
from .models import Article

class ArticleTranslationOptions(TranslationOptions):
fields = ('title', 'content','slug')

translator.register(Article, ArticleTranslationOptions)


I think i need some changes in urls.py but i dont know :/



Thanks for help...










share|improve this question




















  • 1




    Are you sure you want the slug to be translated? I would think very carefully about this, because if someone with the fr setting finds a link somewhere (via Google) with the english slug, it will give a 404. If you really want slugs translated, I would change the detail view to handle all the possible languages by overriding get_object() (and either redirect to the url with the translated slug or just leave it in whatever language it was first).
    – dirkgroten
    8 hours ago












  • hey @dirkgroten thanks for answer. i think actually good for google for seo url. Why would you get a 404 page? And you have a solution for this ? can you show me sample codes please... Thanks
    – Aytek
    36 mins ago















up vote
0
down vote

favorite









up vote
0
down vote

favorite











modeltranslation...



i change title, content and slug sections on my translation.py. Everything work is fine but i have a problem.



let me try to explain;



i have one post in my website and this post "slug" like this;



slug_en = some_en_slug



slug_fr = some_fr_slug



And i have one language changer on my navbar.



     {% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

<form action="{% url "set_language" %}" method="post" class="navbar-form navbar-right">
{% csrf_token %}
<div class="form-group">
<select name="language" class="form-control" onchange="this.form.submit()">
{% for language in languages %}
<option value="{{ language.code }}"
{% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}>
{{ language.name_local }}
</option>
{% endfor %}
</select>
</div>
</form>


Actually this lang. changer working fine. This is change all slug href url's on outside post... But this didnt change slug url in post page.



when i go this url;



https://example.com/en/en_slug



and after try change language, my browser is going this url;



https://example.com/fr/en_slug and i see 404 page..



i need to go to https://example.com/fr/fr_slug this url after change language ...



I dont have any idea for this. I would like your help.



urls.py
from django.urls import path
from . import views
from django.utils.translation import gettext_lazy as _

app_name = "article"


urlpatterns = [
path(_('dashboard/'),views.dashboard,name="dashboard"),
path(_('addarticle/'),views.addarticle,name="addarticle"),
path('<slug>',views.detail,name="detail"),
path('edit/<int:id>',views.editArticle,name="edit"),
path('delete/<int:id>',views.deleteArticle,name="delete"),
path(_('article/'),views.articles,name="article"),
path('comment/<int:id>',views.addcomment,name="comment"),
path('category/<slug>', views.category_detail,name="category_detail" )
]


models.py



from django.db import models
from ckeditor.fields import RichTextField
from django.utils.text import slugify

class Article(models.Model):

author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
title = models.CharField(max_length = 120, verbose_name="Title")
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
content = RichTextField(verbose_name="Content")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
image = models.ImageField(blank=True, null=True, verbose_name="Add Image (.jpg .png)")
slug = models.SlugField(unique=True, max_length = 130)

def __str__(self):
return self.title

def get_unique_slug(self):
slug = slugify(self.title.replace("ı","i"))
unique_slug = slug
counter = 1
while Article.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, counter)
counter += 1
return unique_slug

def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.get_unique_slug()
return super(Article, self).save(*args, **kwargs)


translation.py



from modeltranslation.translator import translator, TranslationOptions
from .models import Article

class ArticleTranslationOptions(TranslationOptions):
fields = ('title', 'content','slug')

translator.register(Article, ArticleTranslationOptions)


I think i need some changes in urls.py but i dont know :/



Thanks for help...










share|improve this question















modeltranslation...



i change title, content and slug sections on my translation.py. Everything work is fine but i have a problem.



let me try to explain;



i have one post in my website and this post "slug" like this;



slug_en = some_en_slug



slug_fr = some_fr_slug



And i have one language changer on my navbar.



     {% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

<form action="{% url "set_language" %}" method="post" class="navbar-form navbar-right">
{% csrf_token %}
<div class="form-group">
<select name="language" class="form-control" onchange="this.form.submit()">
{% for language in languages %}
<option value="{{ language.code }}"
{% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}>
{{ language.name_local }}
</option>
{% endfor %}
</select>
</div>
</form>


Actually this lang. changer working fine. This is change all slug href url's on outside post... But this didnt change slug url in post page.



when i go this url;



https://example.com/en/en_slug



and after try change language, my browser is going this url;



https://example.com/fr/en_slug and i see 404 page..



i need to go to https://example.com/fr/fr_slug this url after change language ...



I dont have any idea for this. I would like your help.



urls.py
from django.urls import path
from . import views
from django.utils.translation import gettext_lazy as _

app_name = "article"


urlpatterns = [
path(_('dashboard/'),views.dashboard,name="dashboard"),
path(_('addarticle/'),views.addarticle,name="addarticle"),
path('<slug>',views.detail,name="detail"),
path('edit/<int:id>',views.editArticle,name="edit"),
path('delete/<int:id>',views.deleteArticle,name="delete"),
path(_('article/'),views.articles,name="article"),
path('comment/<int:id>',views.addcomment,name="comment"),
path('category/<slug>', views.category_detail,name="category_detail" )
]


models.py



from django.db import models
from ckeditor.fields import RichTextField
from django.utils.text import slugify

class Article(models.Model):

author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
title = models.CharField(max_length = 120, verbose_name="Title")
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
content = RichTextField(verbose_name="Content")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
image = models.ImageField(blank=True, null=True, verbose_name="Add Image (.jpg .png)")
slug = models.SlugField(unique=True, max_length = 130)

def __str__(self):
return self.title

def get_unique_slug(self):
slug = slugify(self.title.replace("ı","i"))
unique_slug = slug
counter = 1
while Article.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, counter)
counter += 1
return unique_slug

def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.get_unique_slug()
return super(Article, self).save(*args, **kwargs)


translation.py



from modeltranslation.translator import translator, TranslationOptions
from .models import Article

class ArticleTranslationOptions(TranslationOptions):
fields = ('title', 'content','slug')

translator.register(Article, ArticleTranslationOptions)


I think i need some changes in urls.py but i dont know :/



Thanks for help...







python django django-modeltranslation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 8 hours ago

























asked 8 hours ago









Aytek

165




165








  • 1




    Are you sure you want the slug to be translated? I would think very carefully about this, because if someone with the fr setting finds a link somewhere (via Google) with the english slug, it will give a 404. If you really want slugs translated, I would change the detail view to handle all the possible languages by overriding get_object() (and either redirect to the url with the translated slug or just leave it in whatever language it was first).
    – dirkgroten
    8 hours ago












  • hey @dirkgroten thanks for answer. i think actually good for google for seo url. Why would you get a 404 page? And you have a solution for this ? can you show me sample codes please... Thanks
    – Aytek
    36 mins ago
















  • 1




    Are you sure you want the slug to be translated? I would think very carefully about this, because if someone with the fr setting finds a link somewhere (via Google) with the english slug, it will give a 404. If you really want slugs translated, I would change the detail view to handle all the possible languages by overriding get_object() (and either redirect to the url with the translated slug or just leave it in whatever language it was first).
    – dirkgroten
    8 hours ago












  • hey @dirkgroten thanks for answer. i think actually good for google for seo url. Why would you get a 404 page? And you have a solution for this ? can you show me sample codes please... Thanks
    – Aytek
    36 mins ago










1




1




Are you sure you want the slug to be translated? I would think very carefully about this, because if someone with the fr setting finds a link somewhere (via Google) with the english slug, it will give a 404. If you really want slugs translated, I would change the detail view to handle all the possible languages by overriding get_object() (and either redirect to the url with the translated slug or just leave it in whatever language it was first).
– dirkgroten
8 hours ago






Are you sure you want the slug to be translated? I would think very carefully about this, because if someone with the fr setting finds a link somewhere (via Google) with the english slug, it will give a 404. If you really want slugs translated, I would change the detail view to handle all the possible languages by overriding get_object() (and either redirect to the url with the translated slug or just leave it in whatever language it was first).
– dirkgroten
8 hours ago














hey @dirkgroten thanks for answer. i think actually good for google for seo url. Why would you get a 404 page? And you have a solution for this ? can you show me sample codes please... Thanks
– Aytek
36 mins ago






hey @dirkgroten thanks for answer. i think actually good for google for seo url. Why would you get a 404 page? And you have a solution for this ? can you show me sample codes please... Thanks
– Aytek
36 mins ago



















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265833%2fdjango-modeltranslation-slug-problem-when-i-change-language-dont-go-right-url%23new-answer', 'question_page');
}
);

Post as a guest





































active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265833%2fdjango-modeltranslation-slug-problem-when-i-change-language-dont-go-right-url%23new-answer', 'question_page');
}
);

Post as a guest




















































































Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents