как я могу предварительно установить автора пользователем с помощью помощника crispy inlineformset_factory django?

#python #django

#питон #джанго

Вопрос:

ребята. Прежде всего, спасибо за любых помощников. Я начал изучать Django несколько месяцев.

Итак, я пытаюсь установить автора с зарегистрированным пользователем. Я потратил долгие часы на поиск… Но до сих пор у меня не было успеха.

models.py

 class Painel(models.Model):
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    hashtag = models.CharField(max_length=255, unique=True, blank=False, null=True)
    painel_date_posted = models.DateTimeField(auto_now_add= True, null=True)
    painel_date_updated = models.DateTimeField(auto_now= True, null=True)

    def __str__(self):
        return self.hashtag

    def get_absolute_url(self):
        return reverse('painel-detail', kwargs={'hashtag': self.hashtag})

class Post(models.Model):
    #===============================================================================
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    painel = models.ForeignKey(Painel, on_delete=models.CASCADE, blank=True, null=True)
    title = models.CharField(max_length=100, blank=False)
    slug = models.SlugField(max_length=100 ,null=True)
    #===============================================================================
    content = models.TextField(null=True, help_text='Write your Post', blank=False)
    url = models.URLField(help_text='Paste here the link, witch you saw that news?', blank=False)
    contact_number = models.CharField(max_length=20,blank=True, help_text='If you have another way to comunicate.')
    
    def __str__(self):
        return self.title
     
    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})
 

form.py

 class PainelForm(ModelForm):
    class Meta:
        model = Painel
        fields = ('hashtag', 'created_by', )

    @property
    def helper(self, *args, **kwargs):
        helper = FormHelper()
        helper.form_tag = False # This is crucial.
        helper.layout = Layout(
            Fieldset('Create new Painel - {{ user|capfirst }}',
                    PrependedText('hashtag','#', placeholder="hashtag"),
                    ),
            
        )
        return helper
        
class PostFormHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(PostFormHelper, self).__init__(*args, **kwargs)
        self.form_tag = False # This is crucial.
        self.render_required_fields = True
        self.layout = Layout(
            Fieldset("Add Post {{ forloop.counter }}",
                    PrependedText('title','', placeholder="My Post"),
                    PrependedText('content','',placeholder="Descritions"),
                    PrependedText('url','', placeholder="www.example.com"),
                    
                    ),
            Field('author', name='author', value='{{request.user.id}}'),
        )
 

форма html

 <div class="content-section">
<form method="POST">
    {% csrf_token %}
    <fieldset class="form-group">
        {% crispy form %}
        {{ post_form.management_form|crispy}}
        {{ post_form.non_form_errors|crispy }}
        {% crispy post_form post_formhelper %}
    </fieldset>
    <input type="submit" name="submit" value="Save" class="btn btn-outline-primary" id="submit-save">
</form>
 

views.py

 CombinedFormSet = inlineformset_factory(
Painel,
Post,
fields=('title','content', 'url', 'contact_number', 'author', ), 
extra=1,
can_delete=False,
max_num=1,
validate_max= 1,
 

)

 class PainelCreate(LoginRequiredMixin,CreateView):
model = Painel
form_class = PainelForm
template_name = 'painel/painel_form.html'

def post(self, request, *args, **kwargs):
    self.object = None
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    post_form = CombinedFormSet(self.request.POST, prefix='posts') 

    if (form.is_valid() and post_form.is_valid()):
        return self.form_valid(form, post_form)

    return self.form_invalid(form, post_form)

def form_valid(self, form, post_form):

    form.instance.created_by = self.request.user
    self.object = form.save(commit=False)
    post_form.instance = self.object
    post_form.instance.author = self.request.user >>>> It didnt work <<<<<
    form.save()
    post_form.save()

    return HttpResponseRedirect(self.get_success_url())

def get_context_data(self, **kwargs):
    """ Add formset and formhelper to the context_data. """

    ctx = super(PainelCreate, self).get_context_data(**kwargs)

    if self.request.POST:
        ctx['form'] = PainelForm(self.request.POST)
        ctx['post_form'] = CombinedFormSet(self.request.POST, prefix='posts')
        ctx['post_formhelper'] = PostFormHelper()
    else:
        ctx['form'] = PainelForm()
        ctx['post_form'] = CombinedFormSet(prefix='posts') 
        ctx['post_formhelper'] = PostFormHelper()

    return ctx

def get_success_url(self):
    return reverse('painel-detail', kwargs={'hashtag': self.object.hashtag})
 

Администратор Painel
Я бы хотел, чтобы это поле заполнялось пользователем автоматически

Ответ №1:

Вероятно, это не очень хороший способ решить эту проблему, но до сих пор это то, что есть.

views.py

 def form_valid(self, form, post_form):

    form.instance.created_by = self.request.user
    self.object = form.save()
    post_form.instance = self.object
    post_form.save()

    paineis = Painel.objects.all()
    painel = paineis.get(hashtag=form.instance.hashtag)
    posts_by_hashtag = painel.post_set.all()
    for post in posts_by_hashtag:
        if post.author is None:
            post.author_id = self.request.user.id
            post.save()