Skip to content

Slot Update

In this video, we are going to create the Slot update page. Using this slot update page, the user can update the slot information for a particular vaccination campaign.

Resources

Views

In the views.py file, at first, we will create a view named SlotUpdateView.

# This view will inheirit LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, generic.UpdateView
class SlotUpdateView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, generic.UpdateView):
    # Now, specify the name of model for which you are creating this update view
    model = Slot
    # Then, speicify the form_class
    form_class = SlotForm
    # After that, set the permissions for users.
    permission_required = ("campaign.change_slot",)
    # Then, give the name of the template
    template_name = "campaign/slot-update.html"
    # And, at last, provide the success message.
    success_message = "Slot Updated Successfully"

    # The Slot Form which we are usingh takes campaign_id in the constructor. So, we need to provide that value from our django view
    # For that, we have to override the get_form_kwargs method.
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["campaign_id"] = self.kwargs["campaign_id"]
        return kwargs

    # Also, we have to set the initial value of campaign for this slot
    def get_initial(self):
        initial = super().get_initial()
        initial["campaign"] = Campaign.objects.get(id=self.kwargs["campaign_id"])
        return initial

    # At last, we need to provide the success url on which the user will be redirected once update process is completed.
    def get_success_url(self):
        return reverse_lazy("campaign:slot-list", kwargs={"campaign_id": self.kwargs["campaign_id"]})

Templates

Now, we have to create slot-update.html file in the templates folder under campaign.

I have attached slot-update.html file in the resources section. Please download the file and paste its content in this html file.

{% extends 'mysite/base.html' %}

{% block title %} 
    <title>Update Slot Details</title>
{% endblock title %}

{% block content %}
<div class="card p-3">
    <div class="card-body">
        <h4 class="mb-3">Fill the following details to update slot details</h4>
        {% include "components/form.html" with form_name="Update Slot" %}
    </div>
</div>
{% endblock content %}

URLS

Now, open the urls.py and add a url path to access this view.

path("<int:campaign_id>/slot/update/<int:pk>/", views.SlotUpdateView.as_view(), name="slot-update"),

After that, add this url path in the slot-detail.html file

<a href="{% url 'campaign:slot-update' object.campaign.id object.id %}"><i class="fas fa-pen"></i> Update Slot</a>

[Run the development server and see the changes]