Home > Enterprise >  Django Classbased views with condition
Django Classbased views with condition

Time:02-27

I created script in function based view in django and I want to convert it into classbased views with if/else condition. I done searching but I didn't found the solutions. Sorry for a basic question, Im new in django and start learning.

This is my function script that I want to convert in Classbased views.

def vm_create(request):
    if request.method == 'POST':
        Number = request.POST.get('number')
        Date = request.POST.get('date')

        if Date == '':
            Date = None
        else:
            Date = datetime.datetime.strptime(or_date,'%Y-%m-%d')

        month = ''
        endnum = ''
        if Number != '':
            endnum = int(Number[-1])
            if endnum == 1:
                month = 'January'
            elif endnum == 2:
                month = 'Febuary'
     save = Models(CS_Number=Number, CS_Date=Date, CS_Month=month)

I tried to convert to classbased but return is not working.

class vm_create(CreateView):
    model = models
    form_class = forms
    template_name = 'cs_form.html'
    def create_new(self, request, *args, **kwargs):
        endnum = ''
        if request.GET.get('Number') != '':
            endnum = int(Number[-1])
            if endnum == 1:
                return 'January'
            elif endnum == 2:
                return 'Febuary'
        return super().create_new(request, *args, **kwargs)

CodePudding user response:

For starters, your model has to be YourObjectModel, you should not pass there models. Same thing with form_class. It has to be YourForm that you should store in forms.py. But only if you use some django's form. Otherwise use fields attribute.

Another thing is that you should not get values from GET, when you actually use POST. You didn't do that in your function based view, there is no reason to do it here. Last thing, you should work with post method or in this case, definitely with form_valid as you want only change one value of Model.

views.py:

from your_app.models import YourObjectModel

class vm_create(CreateView):
    model = YourObjectModel
    fields = '__all__'
    template_name = 'cs_form.html'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.

        if form.instance.CS_Number != '':
            endnum = int(form.instance.CS_Number[-1])
            if endnum == 1:
                form.instance.CS_Month = 'January'
            elif endnum == 2:
                form.instance.CS_Month = 'February'

        return super().form_valid(form)

It's important that to use real field names (as I believe you have i.e. CS_Number in your model) with form.instance because it actually changes the values from form POSTing and sending to database.

And your template cs_form.html you can simply render such form with:

{{ form }}
  • Related