i have function that return some information about user device and i have one class for show my html and form_class how can i use function in class
this is my views.py :
from django.http import request
from django.shortcuts import render, redirect
from .forms import CustomUserCreationForm
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
def a(request):
device= request.META['HTTP_USER_AGENT']
print(device)
return device
class RegisterView(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy("register")
template_name = "man/man.html"
this is my urls.py :
from django.urls import path
from . import views
urlpatterns = [
path('',views.RegisterView.as_view(), name="register"),
]
CodePudding user response:
class RegisterView(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy("register")
template_name = "man/man.html"
def form_valid(self, form):
self.object = form.save()
def a(request):
pass
# remember the import: from django.http import HttpResponseRedirect
return HttpResponseRedirect(self.get_success_url())
CodePudding user response:
You can build the function into your CBV class, as per Muhammad Shezad's answer.
If the function is long enough and general enough to be used in several views, you can just call it from a subclassed CBV method:
from wherever import get_device_info # it needs a much better name than 'a'
class RegisterView( generic.CreateView):
...
def form_valid( self, form):
device_info = get_device_info( self.request)
...
A third approach, if you always want to use it in the same way in a subclassed method, is to turn it into a Mixin class. For example
class GetDeviceMixin( object):
def setup(self, request, *args, **kwargs):
super().setup( request, *args, **kwargs)
# do stuff to get the device information
self.device_info = whatever
# all subsequent method invocations will have self.device_info set
class RegisterView( GetDeviceMixin, generic.CreateView):
...