B
B
blazer052015-11-04 09:38:04
Django
blazer05, 2015-11-04 09:38:04

Can't translate links into transliteration?

Hello.
Need help editing the blog code.
There is a blog model in which the slug field has been added

# -*- coding: utf-8 -*-

from django.db import models
from ckeditor.fields import RichTextField


class BlogPost(models.Model):
    class Meta(): # Этот класс прописывается для того, чтоб в базе данных можно было индентифицировать таблицу по ее названию в данном случае это 'blog_post'
        db_table = 'blog_blogpost'
        ordering = ['-timestamp']


    title = models.CharField(max_length=150, verbose_name = 'Заголовок')# По умолчанию это поле обязательное к заполнению blank=False. Если нам нужно оставить какое то поле пустым т.е. не обязятельным к заполнению то пишем параметр blank=True.
    text_redactor = RichTextField(blank=True, verbose_name='Краткое описание')
    text_redactor_full = RichTextField(blank=True, verbose_name='Полное описание')
    likes = models.IntegerField(default=0, verbose_name='Лайки')
    timestamp = models.DateTimeField(verbose_name = 'Дата')# Для числовых полей, если нужно оставить поле пустым - не обязательным к заполнению, то обязательно прописыть параметр blank=True, null=True
    slug = models.SlugField(max_length=150, verbose_name='Транслит', blank=True)
    autor = models.CharField(max_length=100, verbose_name= 'Автор', null=True, blank=True)
    body = models.TextField(verbose_name = 'Описание')# По умолчанию это поле обязательное к заполнению blank=False. Если нам нужно оставить какое то поле пустым т.е. не обязятельным к заполнению то пишем параметр blank=True.


    def __unicode__(self):      # Для python-3 кодировка прописывается так def __str__(self):
      return self.title


# Модель - Комментарии к статьям
class Comments(models.Model):
    class Meta():
        db_table = 'comments'

    comments_text = models.TextField(verbose_name='')
    comments_blogpost = models.ForeignKey(BlogPost)

In admin.py, I connected slug with title In the admin panel, when typing text in the title field in Russian, it automatically translates into Latin in the slug field - everything seems to work. But then it is not possible to change the function that is responsible for displaying the full news, url and template. I did the code from views.py differently here.
prepopulated_fields = {"slug": ("title",)}

def full(reguest, one_id, slug):
    comment_form = CommentForm
    args = {}
    args.update(csrf(reguest))
    args['te'] = BlogPost.objects.get(id=one_id, slug=slug)
    #te = get_object_or_404(BlogPost, slug=slug)
    args['comments'] = Comments.objects.filter(comments_blogpost_id=one_id)
    args['form'] = comment_form
    args['username'] = auth.get_user(reguest).username
    return render_to_response('full.html', args)

In urls.py here I changed one_id to slug
url(r'^full/(?P<one_id>\d+)/$', views.full, name='full'),

In the main urls.py of the project
url(r'^blog/', include('blog.urls', namespace='blog')),

Changed te.pk to te.slug in the template
{% for te in te %}
<div class="panel panel-success">
  <div class="panel-heading">
      <a href="{% url 'blog:full' te.pk %}">{{ te.title }}</a>
  </div>
    <div class="panel-body">
    <p>{{ te.text_redactor|safe }}</p>
     <a href="{% url 'blog:full' te.pk %}"><button type="button" class="btn btn-default btn-xs">Читать далее >>></button></a>
  </div>
<div class="panel-footer">
    <div class="row">
      <div class="col-xs-6 col-md-4"><a href="/blog/addlike/{{ te.pk }}/"><img src="{% static "img/4594371.png" %}" width="30px" height="30px"></a>&nbsp;{{ te.likes }}</div>
         <div class="col-md-4 col-md-pull-1"><!--Соц.кнопки -->
<script type="text/javascript">(function(w,doc) {
if (!w.__utlWdgt ) {
    w.__utlWdgt = true;
    var d = doc, s = d.createElement('script'), g = 'getElementsByTagName';
    s.type = 'text/javascript'; s.charset='UTF-8'; s.async = true;
    s.src = ('https:' == w.location.protocol ? 'https' : 'http')  + '://w.uptolike.com/widgets/v1/uptolike.js';
    var h=d[g]('body')[0];
    h.appendChild(s);
}})(window,document);
</script>
<div data-background-alpha="0.0" data-buttons-color="#FFFFFF" data-counter-background-color="#ffffff" data-share-counter-size="12" data-top-button="false" data-share-counter-type="common" data-share-style="1" data-mode="share" data-like-text-enable="false" data-mobile-view="true" data-icon-color="#ffffff" data-orientation="horizontal" data-text-color="#000000" data-share-shape="round-rectangle" data-sn-ids="fb.vk.tw.ok.gp.mr.lj.ln." data-share-size="30" data-background-color="#ffffff" data-preview-mobile="false" data-mobile-sn-ids="fb.vk.tw.wh.ok.gp.mr.lj.ln." data-pid="1430623" data-counter-background-alpha="1.0" data-following-enable="false" data-exclude-show-more="false" data-selection-enable="true" class="uptolike-buttons" ></div>
  </div>
       <div class="col-xs-6 col-md-4"><h6>Дата публикации: {{ te.timestamp }}</h6></div>
    </div>
    </div>
</div>
{% endfor %}

I can’t figure out how to make links look readable and not like now blog/full/17/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-11-04
@deliro

1) Shit code. Why are you poking around in Meta.db_table? Why is there a BlogPost model in the Blog app? Like duplication. The entire Comments model goes there. By the way, yes. Why is BlogPost singular and Comments plural? Model Comments that, reflects several comments at once? text_editor? What is this field? What does it do? Stores text editor? What about text_editor_full? Stores the full version? autor - what is it? Spanish author? If so - why isn't it a ForeignKey to auth.User? What is args['te']? Something obvious that hasn't reached my village yet? {% for te in te %}? Seriously? How is this to be understood?
2) And now to the point:
The SlugField field should not be blank by definition. Slug - a unique (for the current table) sequence of characters.
Replace in urls:
Add a method to the Post model:

# Где-то в импортах:
from django.core.urlresolvers import reverse

# Внутри модели Post:
def get_absolute_url(self):
    return reverse('full', kwargs={'slug': self.slug})

And all links to the post should be done in this form:
3) Slug is not a transliteration!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question