Home > Software design >  set the logged in user to created_by for django CreateView
set the logged in user to created_by for django CreateView

Time:04-28

Apart from form_valid() method what are the other efficient ways i can set the user to created by.

views.py

class CreatEEView(LoginRequiredMixin, CreateView,):
    form_class =  ''
    template_name = ''
    success_url = ''

    def form_valid(self, form):
       instance = form.instance
       instance.created_by = Model.objects.get(user=self.request.user)
       instance.save()
       return super().form_valid(form)

CodePudding user response:

You should use self.request.user itself. Furthermore you should not save the instance, that will be handled by the super().form_valid(form) call, so:

class CreatEEView(LoginRequiredMixin, CreateView):
    form_class = …
    template_name = …
    success_url = …

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

You could wrap this in a mixin, for example:

class SetUserMixin(LoginRequiredMixin):
    user_field = 'created_by'

    def form_valid(self, form):
        setattr(form.instance, self.user_field, self.request.user)
        return super().form_valid(form)

and then use the SetUserMixin with:

class CreatEEView(SetUserMixin, CreateView):
    form_class = …
    template_name = …
    success_url = …

CodePudding user response:

I have come up with something like this but it is not setting in the model.

views.py

   def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['created_by'] = self.request.user
        return context

.html

{% block content %}
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    {{ created_by }}
    <button 
            type="submit">Save
    </button>
   </form>
      </div>{% endblock content %}
  • Related