Alter Django Form

Aug 19 2020

Come posso modificare il mio codice in modo che un utente non possa scegliere un altro utente per un nuovo post. Voglio fare in modo che l'utente connesso venga automaticamente aggiunto come autore.

I have tried setting the fields part in the views.py to just the content field, however it doesn't work

models.py

class post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.CharField(max_length=140)

views.py

class CreatePostView(CreateView):

    model = post
    fields = '__all__'
    template_name = 'users/create.html'

Myform.html

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Login">
</form>

Risposte

1 bkrop Aug 18 2020 at 23:50
class CreatePostView(CreateView):
    model = post
    template_name = 'users/create.html'
    fields = ['content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)
MukheemMohammed Aug 18 2020 at 23:51

You can manually insert the user value using request.user.username (or) Have a look at this. The questioner's answer is located at the bottom.

AbhishekBera Aug 19 2020 at 00:37

There are 3 things you need to do:

  1. Protect the page, so that anonymous users cannot access it, Using LoginRequiredMixin
  2. Remove the user from the fields
  3. Enter the current user in the submitted form after the form is posted, using form_valid method
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
class CreatePostView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ["content"]
    template_name = "create.html"
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)