justdjango / getting-started-with-django

A beginners course for Django
MIT License
352 stars 249 forks source link

The form of the LeadCreateView provides access to all the agents #21

Open paulrogov opened 2 years ago

paulrogov commented 2 years ago

The form of the LeadCreateView is bugged.

It provides access to all the agents, including those from other organizations (created by other organizer users).

fullscreen

paulrogov commented 2 years ago

The fix is the same as for the AssignAgentForm. You need to update a queryset of a form field "agent" inside a form's __init__


Add a new form to forms.py

class LeadCreationModelForm(forms.ModelForm):
    class Meta:
        model = Lead
        fields = (
            "first_name",
            "last_name",
            "age",
            "agent",
            "description",
            "phone_number",
            "email",
            "profile_picture",
        )

    def __init__(self, *args, **kwargs):
        request = kwargs.pop("request")
        agents = Agent.objects.filter(organization=request.user.userprofile)
        super().__init__(*args, **kwargs)
        self.fields["agent"].queryset = agents

views.py

from .forms import LeadCreationModelForm

class LeadCreateView(OrganizerLoginRequiredMixin, CreateView):
    template_name = "leads/lead_create.html"
    form_class = LeadCreationModelForm

    def get_form_kwargs(self, **kwargs):
        kwargs = super().get_form_kwargs(**kwargs)
        kwargs.update({
            "request": self.request
        })
        return kwargs

    def get_success_url(self) -> str:
        return reverse("leads:lead-list")

    def form_valid(self, form):
        lead = form.save(commit=False)
        lead.organization = self.request.user.userprofile
        lead.save()
        # TODO send email
        send_mail(
            subject="A lead has been created",
            message="Go to the site to see the new lead",
            from_email="test@test.com",
            recipient_list=["test2@test.com"]
        )
        messages.success(self.request, "You have successfully created a lead")
        return super(LeadCreateView, self).form_valid(form)