R
R
RabbitRun92021-07-15 01:35:41
Django
RabbitRun9, 2021-07-15 01:35:41

How to add a user to CreateView?

There is a User model inherited from AbstractUser and supplemented with:

class User(AbstractUser):
    email = models.EmailField(unique=True)
    bio = models.TextField(blank=True, max_length=1000)
    date_of_birth = models.DateField(blank=True, null=True)


And the Post model:
class Post(models.Model):
    theme = models.CharField(max_length=50)
    content = models.TextField()
    photo = models.ImageField(upload_to='media/')
    status = models.BooleanField(default=True)
    create_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)


The form:
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['theme', 'content', 'photo', 'user']
        widgets = {
            'theme': forms.TextInput(attrs={'class': 'form-control'}),
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
        }


View:
class CreatePost(LoginRequiredMixin, CreateView):
    form_class = PostForm
    template_name = '/add_post.html'
    raise_exception = True


Everything works fine, but... When publishing a Post at the bottom, you can always select a User from the list (drop-down list), which is not good.
How to make the user himself pull up the one that publishes the Post?

(If I remove "user" from the fields in the form, fields = ['theme', 'content', 'photo', 'user']then the Post simply does not go, does not find the user, and gives an error.)

I would be grateful for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
s1vemod, 2021-07-16
@RabbitRun9

You can override the form_valid method of CreateView :
Example:

def form_valid(self, form):
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save() 

        return redirect(self.get_success_url())

Taken from:
https://habr.com/ru/post/137960/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question