简体   繁体   中英

Fill The ForeignKey Field in Django CreateView Automatically

Here is my scenario. I want one of my model fields to be auto-fill based on whether the user is authenticated or not. Like when the user submits the form, I need to check if the user is authenticated and then fill the created_by field up with <User Object> otherwise, leave it Null if possible.

Here is my model:

class Snippet(models.Model):
    # ---
    create_by = models.ForeignKey(
        User,
        on_delete = models.CASCADE,
        null=True,
    )
    # ---

Here is my view:

class SnippetCreateView(CreateView):
    # ---
        def save(self, request, *args, **kwargs):
            if request.user.is_authenticated:
                user = User.objects.get(username=request.user.username)
                request.POST['create_by'] = user       # --->> TraceBack: due to immutability..
            return super().post(request, *args, **kwargs)
    # ---

Since the request.POST QueryDict is immutable, how can I implement it?? I have tried multiple ways like creating a copy of that but nothing happens and it doesn't change anything.

But..

I can implement it like this and it works with no problem. I think this solution is dirty enough to find a better way. What do you think about this solution??

class Snippet.CreateView(CreateView):
    # ---
        def save(self, request, *args, **kwargs):
            if request.user.is_authenticated:
                user = User.objects.get(username=request.user.username)
            data = {
                'title': request.POST['title'],
                # ---
                'create_by': user if user else None,
            }
            
            snippet = Snippet.objects.create(**data).save()
            # redirecting to Snippet.get_absolute_url()
    # ---

This solution is applied only if you are using django ModelForm.

class CreateArticle(CreateView):
    model = Snippet

    ......... 
    def form_valid(self, form):
        user = self.request.user
        form.instance.created_by = user if user else None
        return super(CreateArticle, self).form_valid(form)
    ......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM