C
C
ColdSpirit2016-03-02 18:22:53
Django
ColdSpirit, 2016-03-02 18:22:53

How to pass object id to its field in django in django?

Actually there is a news model, installed ckeditor (this is not very important, you can imagine a regular field, but with a handler), put it as a field in the model. When opening in the admin panel, the id of this news should be passed in the ckeditor field.

from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField

# вот примерно как сейчас
class Page( models.Model ):
  title = models.CharField( verbose_name="Заголовок")
  content = RichTextUploadingField( verbose_name="Текст" )

# вот как хотелось бы, но так не выйдет, т.к. объекта еще нет, всего лишь описывается класс
class Page( models.Model ):
  title = models.CharField( verbose_name="Заголовок")
  content = RichTextUploadingField( verbose_name="Текст", page_id=self.id )

I’m completely confused already in the classes, I don’t understand where to start from, because all object management takes place in the admin view, but it would be nice not to touch it, I want to write the model/field code so that their objects can be sorted out by themselves.
# addition
I can get the id only after creating the model object (not to be confused with writing to the database). Django parses my Page description, creates variables, and only then can I access the key. The question is how to get and pass the key to the field before django starts parsing my class description.
class Page( models.Model ):
    title = models.CharField( verbose_name="Заголовок")
    content = RichTextUploadingField( verbose_name="Текст" )

    def __init__(self, *args, **kwargs):
        #print(self.id) # AttributeError: 'Page' object has no attribute 'id'
        super(Page, self).__init__(*args, **kwargs)
        print(self.id) # выведет ид

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2016-03-02
@ColdSpirit

Try passing the id through the form widget when initializing
admin.py

from forms import PageForm

@admin.register(Page)
class PageAdmin(admin.ModelAdmin)
     form = PageForm
     model = Page

forms.py
class PageForm(forms.ModelForm)
     def __init__(self, *args, **kwargs):
          super(PageForm, self).__init__(*args, **kwargs)
          if self.instance:
                self.fields['content'].widget=RichTextUploadingField( verbose_name="Текст", page_id=self.instance.id )
...

S
sim3x, 2016-03-03
@sim3x

It’s hard to say whether it will work or not Add the
uuid field to the model
In the ModelForm, we immediately initialize the field
But I don’t know how to connect everything with the editor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question