[Django]-Howto use django regular inheritance in models and forms

-1πŸ‘

βœ…

The easiest solution I could find was without proper inheritance. But it is possible to make two different requests in views

models.py

class Event(models.Model):
   event_date = models.DateTimeField(auto_now=False, null=True, blank=True)

forms.py

class EventForm(forms.ModelForm):
    number = forms.IntegerField(initial = 1)

    class Meta:
        model = Event
        fields = ('event_date',)

views.py

def event_new(request):
    if request.method == "POST":
        form = EventForm(request.POST)
        if form.is_valid():
            number = int(request.POST['number'])
            event = form.save(commit=False)
            print(number)
            print(event)  
            ... generate events ...
            event.save()
πŸ‘€schasoli

-1πŸ‘

You can use class property that way you can use it in forms, views, templates but it does not go into the database.

    class Event(models.Model):
        event_date = models.DateTimeField(auto_now=False, null=True, blank=True)

        @property
        def number(self):
            return `some value that you calculated`

    class EventForm(ModelForm):
        number = forms.IntegerField()

        class Meta:
            model = Event 
            fields = ('event_date',)

        def __init__(self, *args, **kwargs):
            instance = kwargs.get("instance", None)
            if instance:
                kwargs["initial"] = {"number": `some initial value you want`, }
            super().__init__(*args, **kwargs)
    def event_new(request):
        if request.method == "POST":
            form = EventForm(request.POST)
            if form.is_valid():
                event = form.save(commit=False)
                ... generate events ...
                ... use event.number in the way you want...
                event.save()

πŸ‘€cgl

Leave a comment