CreateView with fixed Tag

Format: Python
 ( View Raw)
Date: Mon, 17 Jul 2023 at 21:05:40

from django.urls import reverse_lazy
from django.views.generic import CreateView

from dnsmasq.models import DhcpOption, DhcpTag

from website.views.generic import GenericMixin
from website.views.require_login import RequireLoginMixin

class DhcpOptionsCreateView(RequireLoginMixin,
    model = DhcpOption
    fields = ['tag', 'option', 'description',
              'character_value', 'numeric_value', 'forced', 'is_active']
    success_url = reverse_lazy('website.dhcp_options.list')
    template_name = 'website/dhcp_options/detail.html'
    page_title = 'Create new DHCP option'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # If the tag is passed set it as disabled/fixed
        if 'tag' in self.kwargs:
            context['form'].fields['tag'].disabled = True
        return context

    def get_initial(self):
        results = super().get_initial()
        # If the tag is passed set its value
        if tag_id := self.kwargs.get('tag', None):
            results['tag'] = DhcpTag.objects.get(pk=tag_id)
        return results