0

I'm looking for using Multiple Django functions in the same Class and display these functions on the same template.

Both functions are in my Django Template, but none work and I don't know why.

First function :

This function lets to search a person in my Database based on 3 criteria : firstname, lastname and birthcity. Then I display the query result in my array.

Second function :

This function is a simple Django form.

This is my first Django Class :

class SocieteFormulaire(TemplateView) :

    template_name= "Societe.html"
    model = Societe


    def get_context_data(self, **kwargs):

        request = self.request

        if 'recherche' in request.GET:

            query_Lastname_ID = request.GET.get('q1LastnameID')
            query_Firstname_ID = request.GET.get('q1FirstnameID')
            query_BirthCity_ID = request.GET.get('q1BirthCityID')

            sort_params = {}

            set_if_not_none(sort_params, 'Lastname__icontains', query_Lastname_ID)
            set_if_not_none(sort_params, 'Firstname__icontains', query_Firstname_ID)
            set_if_not_none(sort_params, 'BirthCity__icontains', query_BirthCity_ID)

            query_list = Societe_Recherche.Recherche_Filter(Societe, sort_params)

            context = {
                "query_Lastname_ID" : query_Lastname_ID,
                "query_Firstname_ID" : query_Firstname_ID,
                "query_BirthCityID" : query_Birthcity_ID,
                "query_list" : query_list,
            }

            return context


    def get_context_data(self, **kwarg) :

        success = False
        request = self.request

        if request.method == 'POST':

            form = IndividuFormulaire(request.POST or None, request.FILES or None)

            if form.is_valid() :
                post = form.save(commit=False)
                for element in settings.BDD :
                    post.save(using=element, force_insert=True)

                messages.success(request, 'Le formulaire a été enregistré !')
                return HttpResponseRedirect(reverse('IndividuResume', kwargs={'id': post.id}))

            else:
                messages.error(request, "Le formulaire est invalide !")

        else:
            form = IndividuFormulaire()
            form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name

        context = {
            "form" : form,
            "Individu" : Individu
        }

        return context

I named both functions with the same name, because if I don't do that, first function or my form is not displayed on my template.

So my question is : How I can set multiple functions in the same Django Class and in the same Django template ?

2
  • @DanielRoseman I'm trying to improve my code and get object-oriented code. Up to now, I defined my view as a succession of functions. Each function pointed to a Django template. But sometimes I have to get multiple functions i the same template as in my question : search people and create people thanks to Django form. I'm trying to handle my script because it's ugly and I want to set something better. Commented Sep 12, 2017 at 8:20
  • There is no such thing as "Multiple Django functions". What you want is to use multiple views. If you want to use the same template for multiple views, nothing stops you from doing that Commented Sep 12, 2017 at 8:22

1 Answer 1

2

You have several misconceptions and misunderstandings here.

You simply can't have two methods with the same name in a Python class. The first one will just be overridden when the class is loaded. The normal solution is to put all the code in one method, or have two with different names and call one from the other.

However, you should also consider that none of this logic belongs in get_context_data anyway. That's for preparing context data for the template, not for processing form submissions.

The fundamental problem is that you are picking the wrong class to inherit and then overriding the wrong methods. TemplateView is a very basic class and is certainly not meant to be used like this. The real action of your view is to display and process a form that creates an element; so, you should use CreateView. Then you can get rid of almost all the code in your second method; the view will do all the processing for you, the only thing you will need to do is to define form_valid to do your custom save logic.

The search logic could remain in get_context_data if you like. But you do need to remember to call the superclass method, and also return context even if 'recherche' in request.GET is false.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok thank you to your answer. It's the first time I'm using Django class like this and I made lot of mistakes in my script. So I have to replace class SocieteFormulaire(TemplateView) : by class SocieteFormulaire(CreateView) : and see how this class works ?
Yes; then delete all of the second get_context_data method except for the bit inside if form.is_valid() and move that into a separate form_valid method.
Thank you I will try your answer !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.