0

I have the following code:

class MyView(View):
    var2 = Choices.objects.get(id=1)
    my_strings = ['0','1','2','3']

    @login_required
    def myfunction(self,request):

        return render(request,
              'app/submit.html',{'my_strings':my_strings, 'var2':var2})

I want to access "var2" and "my_string" variables and display them in the template submit.html. If I use only the function without putting it in a class, everything works fine. But inside the class it shows errors.

Can anybody tell me how to access "var2" and "my_string" class variables in "myfunction" ?

2

2 Answers 2

1

You have to use self. In front of class variables.

Your function names in class based views should correspond to what http method you try to use(get, post etc...)

@login_required
def get(self,request):

    return render(request,
          'app/submit.html',{'my_strings':self.my_strings, 'var2':self.var2})

Please also read: https://docs.djangoproject.com/en/1.9/topics/class-based-views/intro/

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

2 Comments

I did this but it shows an error: __init__() takes 1 positional argument but 2 were given
stacktrace? need some more info.
0

You don't have to write custom function to dispatch request...Django internally have the GET and POST method to do that... And also preferred way to handle login required is method_decorator

from django.utils.decorators import method_decorator 

@method_decorator(login_required, name='dispatch')
class MyView(View):

    string = "your string"

    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

    def get(self, request):
        return render(request, 'template', {'string': self.string})

Comments

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.