Home > OS >  Set default value Django Models
Set default value Django Models

Time:06-09

I need to set a date to Enddate if the user didn't enter it by taking the value from Starting input, Let's say I have this Model:

class DataSet(models.Model):
Event     = models.CharField(max_length=50,blank=True ,null=True)
Starting   = models.DateField()
Enddate   = models.DateField(blank=True ,null=True)
Times     = models.PositiveIntegerField(max_length=4,blank=True ,null=True)
postdate    = models.DateTimeField(auto_now_add=True)
author      = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
    return self.Stating
class Meta:
    ordering = ('-Enddate',)

and the form is;

class DataSet_F(forms.ModelForm):
Event    = forms.CharField(label='Event')
Starting = forms.DateField(label='Start date',widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'}))
Enddate  = forms.DateField(label='End date',required =False,widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'}))
Times    = forms.IntegerField(label='Time',required =False)
class Meta:
    model= DataSet
    fields=['Event','Starting','Enddate','Times']

How I set Enddate equal to Starting when the user didn't enter the value, then set Times equal to 1. Many thanks

CodePudding user response:

I found the solution and it was so easy :)

class PostCreateEVENT(LoginRequiredMixin, CreateView):
model = DataSet
template_name = 'Home/EVENTS/Add_event.html'
form_class = DataSet_F
def form_valid(self, form):
    form.instance.author = self.request.user
    if form.instance.Enddate:
        pass
    else:
        form.instance.Enddate=form.instance.Starting
        form.instance.Times  =1
    return super().form_valid(form)

THANK YOU ALL FOR MOTIVATION

CodePudding user response:

I also Found another way directly in the form

class DataSet_F(forms.ModelForm):
     Event    = forms.CharField(label='Event')
     Starting = forms.DateField(label='Start date',widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'}))
     Enddate  = forms.DateField(label='End date',required =False,widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'}))
     Times    = forms.IntegerField(label='Time',required =False)

     def __init__(self, *args, **kwargs):
        super(DataSet_F, self).__init__(*args, **kwargs)
        if self.fields['Enddate']:
           pass
        else:
           self.fields['Enddate']=self.fields['Starting']
           self.fields['Times']  =1
    class Meta:
       model= DataSet
       fields=['Event','Starting','Enddate','Times']
  • Related