Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX not reading json CORS allow-origin headers returned from django
I'm calling a Django view with AJAX cross-domains. I'm returning the proper CORS allow-origin headers properly (works in other ajax calls to my api), however, my AJAX response is still fail with browser console error: "Access to XMLHttpRequest at 'foo' from origin 'bar' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." In my python console, the response is as expected: {"successMessage": "Sent referral email", "Access-Control-Allow-Origin": "", "Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Headers": "", "Access-Control-Max-Age": "1000"} but for some reason this is not translating to AJAX and it's failing. If I remove the json conversion, and simply return HttpResponse(), I get a status 200 from AJAX and no CORS warning, but it still fails. I assume because it's expecting JSON and that's not what it's getting. Help! My ajax: $.ajax({ url: "http://192.168.0.23:8000/api/SendEmail?email=" + $("#refereeEmail").val() + "&refereeName=" + $("#refereeName").val() + "&referrerName=" + $("#referrerName").val(), dataType: "json" }).fail(function (xhr, status, error) { console.log("fail"); $('#email-alert').text("There was an error communicating with the server. Please try again."); $('#email-alert').show(); // handle a non-successful response console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }).success(function (response) { if (response.status == "ok") { console.log("worked"); // sent email, … -
Django View, get all list items in template
In Veiw, to get the selected item from an existing list in a template, I use request.POST.getlist('my_list'). In View, how to get all items from an existing list in a template? -
Django Custom Tag Problems
Hello Stack Overflow ! I am making a news site in Django as a part of my "internship", I have just started learning web development. I was given a task to make a custom template ( it HAS to be a custom template ) which will render out 3 latest news from a category, and I have to include it as a sidebar on my "article" page. I tried to write the custom tag, but it's not going to well unfortunately. This is my "last" task for the website, and I'm stuck (like many times before :P ) Here's the thing..everything is working if I include the custom tag on my "list all articles" page, it renders correctly depending on which category I click on. The thing is, once I try to include my tag into my "single article" page I hit a brick wall. The tag is still working, but is now displaying all of my articles, instead of filtering the articles related to that article's category. To simplyfiy, If i click on a "health" article to open it, I want the sidebar just to include the articles for the "health" category, I hope that makes sense. Anyone with … -
How to use `construct_change_message` to create a `change_message` in my own view to log my actions in the built-in `LogEntry` model?in django
I've added a code in my view to log every add action in my add_new_staff page. Here's the code: message = f'New user added. Added staff profile for {user.first_name} {user.last_name}' log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=repr(user.id), # or any field you wish to represent here object_repr=repr(user.username), action_flag=ADDITION, # assuming it's a new object change_message=message,) # a new user has been added log.save() In here, I only made a custom get message thru message string. And I think, for this add_staff_view it is ok to do this. But now, I'm working on my update_staff_profile_view and also, I need to log this action. I saw how the change/update form in django admin page inserts the change_message in LogEntry model(it shows which fields are changed/updated), and I can't think of ways to do it inside my own update_staff_profile_view. Here's my update_staff_profile_view: @login_required def ProfileUpdateView(request): if request.method == 'POST': user_form = accounts_forms.UserUpdateForm(request.POST, instance=request.user) if request.user.is_staff == True: profile_form = accounts_forms.StaffProfileUpdateForm( request.POST, instance=request.user.staffprofile) else: profile_form = accounts_forms.StudentProfileUpdateForm( request.POST, instance=request.user.studentprofile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=repr(user.id), object_repr=str(user.username), action_flag=CHANGE, change_message = 'IM STUCK HERE',) log.save() messages.success(request, 'Your profile has been updated.') return redirect('update-profile') else: user_form = accounts_forms.UserUpdateForm(instance=request.user) if request.user.is_staff == True: … -
MultiValueDictKeyError at /login/
I'm trying to create a customized signup and login form with sessions. The data is successfully saved in the db but when I'm trying to login into the system using email and password credentials. It is throwing an error. I'm unable to figure out the reason. def user_login(request): context = {} if request.method == "POST": user_email = request.POST['user_email'] password = request.POST['password'] member = authenticate(email=user_email, password=password) request.session['user_email'] = member if member: login(request, member) if request.GET.get('HomePage', None): return HttpResponseRedirect(request.GET['HomePage']) return HttpResponseRedirect(reverse('success')) else: context["error"] = "Provide valid credentials !!" return render(request, "login.html", context) else: return render(request, "login.html", context) def form_view(request): if request.session.in_key('user'): user = request.session['user'] return render(request, 'HomePage.html', {"user": user}) else: return render(request, 'login.html', {}) def logout(request): try: del request.session['user'] except: pass return HttpResponseRedirect(reverse('user_login')) my signup form and login form class UserSignupForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Users fields = "__all__" class LoginForm(forms.ModelForm): class Meta: model = Users fields = ['user_email', 'password'] urls urlpatterns = [ path('admin/', admin.site.urls), path('signup/', views.signup), path('login/', views.user_login, name="user_login"), path('success/', views.success, name="success"), path('logout/', views.user_logout), path('logout/', views.logout, name="logout"), login.html file <form method="POST" > {% csrf_token %} <table> <tr> <td><label for="user_email">Email</label></td> <td><input type="text" name="Email" id="user_email" required></td> </tr> <tr> <td><label for="password">Password</label> </td> <td><input type="password" name="password" id="password" required></td> </tr> <p style="color: … -
Django templating + Vue templating for the same content for SEO reasons
I'm in the process of building a Django app with limited Javascript interactivity, and am looking at how to incorporate Vue templating along with Django templating for the same content. Imagine an infinite scroll page, where SEO is very important. Django is great at solving this problem since it is per definition a server side framework. However, how would you enrich a page rendered by Django with Vue, provided that both of these technologies need to render the same content? Django would in this case render for the SEO crawlers, right before Vue takes over, Vue "hydrates" these components and make them interactive. After this happens, subsequent content that is fetched asynchronously with AJAX will also be templated using Vue. I have done some research without finding sufficient information on how to solve this: https://vsupalov.com/vue-js-in-django-template/ which is where some parts of the code sample below is based off of https://medium.com/quick-code/crud-app-using-vue-js-and-django-516edf4e4217 which outlines that combining django and vue seems to work pretty well together https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a I don't get the sense that these sources are talking about SEO, or rather if they are, they utilize Vue templating only where the content is not SEO heavy(like opening a modal). Below is an initial … -
Django, keras segmentation : Tensor is not an element of this graph
I have an object to load the model. class BillOCR: def __init__(self,image_address='',retrain=False,checkpoint='unet_model/'): self.image_address = image_address self.checkpoint = checkpoint latest_weights = checkpoint+'resnet_unet_1.4' assert ( not latest_weights is None ) , "Checkpoint not found." self.model = keras_segmentation.models.unet.resnet50_unet(n_classes=3, input_height=32*24, input_width=32*18,) self.model.load_weights(latest_weights) I have declared the necessary objects and graph as global global ocr ocr = BillOCR() global model model = ocr.model global graph graph = tf.get_default_graph() and I have a django method: def classify(request): data = {"success": False} if request.method == "POST": tmp_f = NamedTemporaryFile() if request.POST.get("image64", None) is not None: base64_data = request.POST.get("image64", None).split(',', 1)[1] plain_data = b64decode(base64_data) image = np.array(Image.open(io.BytesIO(plain_data))) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) tmp_f.write(plain_data) tmp_f.close() with graph.as_default(): k_number = ocr.model.predict_segmentation(image) K.clear_session() data["success"] = True data["result"] = k_number return JsonResponse(data) But this is leading to Tensor Tensor("activation_50/truediv:0", shape=(?, 110592, ?), dtype=float32) is not an element of this graph. How do I tackle this? K.clear_session() also didn't work. Im using Keras==2.2.4 tensorflow==1.13.1 and latest version of keras_segmentation. Loading the model everytime there's a request is way too time consuming. -
Django: Ignores readonly=True for multiple select of a ManytoManyField despite grayed out area
Bit puzzled, it seems Django Crispy forms ignores readonly=True for a multiple select field linking to a ManytoManyfield. Area is grayed-out but I am still able to change and save the selection into the database. readonly=True should supposedly gray out the area and not allowing to save any changes. readonly=True works on a CharField as intended in the same form. Why is this? is it a bug or a known problem, in such case, what fixes are suggested. class Product(models.Model): product_type = models.CharField(max_length=22, blank=True) class Package(models.Model): product_code = models.CharField(max_length=3) products = models.ManyToManyField('product.Product', blank=True) class ProductModelForm(ModelForm): class Meta: model = Package fields = '__all__' class ProductFieldsForm(ProductModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-4' self.helper.field_class = 'col-sm-7' self.helper.form_tag = False prd_code = 'product_code' prds = 'products' self.helper.layout = Layout ( Field(prd_code, readonly=True), # WORKS FINE, as intended Field(prds, readonly=True), # **CAN CHANGE and SAVE (gray area)** ) -
How to generate a pdf form prepopulated from a Django formwizard values and send an email
I am trying to generate a pdf form with values filled in from a Django form wizard and send an email with the pdf. But am stuck trying to get the values and generating pdf. This is my forms.py class FormStepOne(forms.Form): qualifying_criteria = forms.MultipleChoiceField(label='Applicant company must qualify against at least one', required=True, widget=forms.CheckboxSelectMultiple, choices=CRITERIA_CHOICES) details = forms.CharField(label="Provide more details and give reasons for wanting to join the Chamber and what you are expecting from your membership", widget=forms.Textarea(attrs={"rows": 10, "cols": 20})) class FormStepTwo(forms.Form): company_name = forms.CharField( label="Company Name (in full):", max_length=100) other_name = forms.CharField( label="Other Trading Name(s) if applicable:", max_length=100, required=False) physical_address = forms.CharField( label='Physical Address:', widget=forms.Textarea(attrs={"rows": 5, "cols": 20})) email = forms.EmailField(label="Email:") website = forms.URLField(label="Website:", required=False) contact_name = forms.CharField(label="Name:", max_length=100) job_title = forms.CharField(label="Job Title:", max_length=150) contact_mobile = forms.CharField(label="Mobile", max_length=30) contact_telephone = forms.CharField( label="Telephone No", max_length=30, required=False) contact_email = forms.EmailField(label="Email Address:") views.py class FormWizardView(SessionWizardView): template_name = "join.html" form_list = [FormStepOne, FormStepTwo] file_storage = FileSystemStorage( location=os.path.join(settings.MEDIA_ROOT)) def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] criteria = form_data[0]['qualifying_criteria'] self.request.session['criteria'] = criteria self.request.session['details'] = form_data[0]['details'] return redirect('complete') class Process_Data(TemplateView): template_name = 'corporate-form.html' def get_context_data(self,**kwargs): context = super(Process_Data, self).get_context_data( **kwargs) context['criteria'] = self.request.session['criteria'] context['details'] = self.request.session['details'] return context In my views, I … -
What's the proper way to use different pipenv environments for a Django project on different computer systems?
Hopefully this isn't too stupid of a question, concerning the use of pipenv for the same Django project on different computer systems. The scenario is that I'm using pipenv with a test Django project on one laptop, everything works fine, using VS Code and it's using the proper pipenv environment for the Python environment within VS Code. The project however is within Dropbox so when I'm using a different laptop, which I do sometimes, one is my work laptop the other is my personal one at home, I can work on the same project wherever I left off. So you can probably deduce the issue I'm having. I'm using pipenv environment A on my work laptop for the Django project. But when I open the project in VS Code on my personal laptop at home I have to keep specifying the proper pipenv environment to use, which obviously is different than the one on my work laptop. Maybe I shouldn't be working this way and should just work on one laptop for the project, but I imagine others have done the same with similar setups before. Is there a "proper" way to do this, using different pipenv environments on different … -
Selected value not passed in Django
I want to pass the selected values to have dependent dropdown with data connection. I am using <select> in HTML to pass value to Django but selected values can't be passed in Python for processing. I am new to Django and prefer not to use models.py or forms.py at the moment. <select class="Lv0" name="lv0"> <option value="US">US</option> <option value="UK">UK</option> </select> views.py def search_index(request): results = [] lv0="" search_term = "" if request.GET.get('lv0'): lv0 = request.GET['lv0'] print(lv0) //this can't be printed if request.GET.get('query'): search_term = request.GET['query'] print("####test#####\n", search_term) //this is printed results = esearch(query=search_term) print(results) //this is printed context = {'results': results, 'count': len(results), 'search_term': search_term} return render(request, 'esearch/base.html', context) Below is for query that gets passed. <form class="form-inline"> <input class="form-control mr-sm-2" type="query" placeholder="Search Here" aria-label="query" name = 'query' value = ""> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> -
How to restrict users without permissions when using remote auth backend?
I am relatively new to Django. I am user a remote auth backend, but I am wondering if there is a way that I can restrict users that do not have permissions, gotten from REMOTE_USER. Is it similar to the way you do it with a Django Auth system? Right now everyone who is logged in on my auth backend can access my site. I want to grant certain users permissions before they login, and deny all other users. Is there a way in which I can do this? -
Django unitTest response.content doesnt show proper user info
I am facing the following problem. When I am running a unit test to verify whether user logged in properly, returned HTTP response doesn't contain variables from the template. class WorkflowViewTest(TestCase): def test_response_authorized(self): User = get_user_model() user = User.objects.get(username='JohnDoe') self.client.force_login(user) response = self.client.get('/workflow/') print(response.content.decode()) # response content is not right self.assertEqual(response.status_code, 200) # assertions are passing just fine self.assertTemplateUsed(response, 'workflow.html') Simplified content of used template 'workflow.html' is: {% extends "base_generic.html" %} {% load static %} {% block content %} {% if user %} {{user}} {{user.username}} {{user.first_name}} {{user.last_name}} {{user.email}} {% else %} User variable not provided {% endif %} {% endblock %} Where encoded response.context.content is following: <body> AnonymousUser </body> </html> I have tried to create a user within setUp of the test, I also created user manually, I tried both self.client.force_login() and self.client.login(). None of the proposed solutions I found were working. I really appreciate any insight. Thanks -
Django How can I trace back where this call is done Not Found: /graphql
Since I created a new project (Django 2.2 and Python 3.7) I am having this error been printed every time I load a new page or some times it does it periodically. Not Found: /graphql [24/Sep/2019 13:23:50] "GET /graphql HTTP/1.1" 404 4216 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 53701) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/robertofernandez/KMH/flowlemon_backen/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/robertofernandez/KMH/flowlemon_backen/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I think this error is caused by some dependency that I have installed (I don't have any view or URL call graphql and I am not using graphql at all in my project), but I am unable to detect which package is the one causing the problems. requirements.txt attrs==19.1.0 certifi==2019.6.16 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 defusedxml==0.6.0 Django==2.2.4 django-braces==1.13.0 django-cors-headers==3.1.0 django-extensions==2.2.1 django-filter==2.2.0 django-oauth-toolkit==1.2.0 django-rest-framework-social-oauth2==1.1.0 djangorestframework==3.10.2 drf-yasg==1.16.1 idna==2.8 inflection==0.3.1 itypes==1.1.0 Jinja2==2.10.1 loguru==0.3.2 MarkupSafe==1.1.1 oauthlib==3.1.0 packaging==19.1 PyJWT==1.7.1 pyparsing==2.4.2 python-decouple==3.1 python3-openid==3.1.0 pytz==2019.2 requests==2.22.0 requests-oauthlib==1.2.0 ruamel.yaml==0.16.5 ruamel.yaml.clib==0.1.2 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 sqlparse==0.3.0 uritemplate==3.0.0 urllib3==1.25.3 Any idea … -
Django Place Lock on a URL
Not 100% sure how to phrase the question but here is the problem: I have a website serving documents which each have their own URL, for example: www.app/doc/1 www.app/doc/2 The website allows users to edit the documents and save the changes. I want to put a lock in place so that only one user can edit a document at a time. So, if one client has www.app/doc/1 open then noone else should be able to open the same URL. The web app is developed in Django. Any pointers on how to do this? I know some websites are able to pick up if you have a page open in another tab and force you to pick an active tab. What is the method that they use? -
Django built in server keep disconnecting when loading a template
I'm using Django built in server for developing a web application. Upon rendering a template for a specific web page, the server stop working without any log or warning on the console. It's just suddenly disconnected everytime i try to access that page. After a while, i found out that if i remove a block of code which has the function of creating a dropdown list, the problem disappeared. But it's just a very simple code in order to get a list of departments, iterate it and make a dropdown list. I have seen other people do the same on the internet, so i have no idea why this is happening. Here is the code of the view: def edit(request): departments = Department.objects.filter() # I can iterate the QuerySet normally for d in departments: print(d.id, d.name, d.department_code) return render(request, 'edit/edit.html', {'departments': departments}) and the block of code which creates a dropdown list: <select name="department1" class="department"> <option value=""></option> {% for d in departments %} <option value="{{ d.id }}"> {{ d.name }} - {{ d.department_code }} </option> {% endfor %} </select> Any help would be appreciated. Thank you. -
failed to change language manually in django
For some reason I don't want to use this method. Right now I want to change language via a GET request. But it's not working as expected. Here is my settings: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'English'), ('bn', 'Bengali') ) LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = False urls.py urls = [ path('language/', base.change_lan, name='change_language'), ] urls += i18n_patterns( path('login/', base.login, name='login'), prefix_default_language=False, ) html: <div class="header-menu"> <ul> <li><a href="{% url 'change_language' %}?lan=en"><img src="{% static 'image/flag/en.png' %}" alt="USA Flag">ENGLISH</a></li> <li><a href="{% url 'change_language' %}?lan=bn"><img src="{% static 'image/flag/bn.png' %}" alt="Bangladesh Flag">বাংলা</a></li> </ul> </div><!-- End .header-menu --> and views: def change_lan(request): allowed_lan = ('en', 'bn') get_lan = request.GET.get('lan', 'en') if get_lan in allowed_lan: translation.activate(get_lan) request.session[translation.LANGUAGE_SESSION_KEY] = get_lan request_url = request.META.get('HTTP_REFERER', '/') // ex: http://localhost:8000/login/ redirect_url = urls.translate_url(request_url, get_lan) //ex: http://localhost:8000/bn/login/ return redirect(redirect_url) else: return redirect(request.META.get('HTTP_REFERER', '/')) -
How to create a user specific homepage in django 2.2?
I'm a newbie to Django framework, I wanted to create a homepage(initial page), which shows a specific set of content made for that particular user if that user is already logged in. -
Handling Custom Error Pages(404, 500) In Django
Why when I click on the page does not exist imposed error page appears in the project folder but I see the emergence of the page django with all the code is true in view from django.shortcuts import ( render_to_response ) from django.template import RequestContext def page_not_found(request,exception): response = render_to_response('404.html',context_instance=RequestContext(request)) response.status_code = 404 return response in url from django.conf.urls import ( handler400, handler403, handler404, handler500 ) handler404 = 'listings.views.page_not_found' -
How to update multiple queries in postgresql stored procedure?
I want to update table in postgresql using array data as per code. I am using stored procedures in postgresql. update table_name set number = '123' where type in ('ab','cd') I want to use same above query in stored procedures also but when placing same code in stored procedures getting errors. Please let me know if anyone has solution for it. -
Google API file permissions using python
I need to do some functionality for different users of my site to automatically upload html files to google disk and open them for viewing and editing in google docs. To do this I create a document, pass it to google disk and use the id of the created document to open it in google docs. To access api, I use a json file taken from the service Google account. I tried to execute my code with owner and view rights, but the result is the same. class CvView(AuthorizedMixin, View): """Here I check if the file format is html, I temporarily save it on disk and pass it to the file_to_drive function (to save it to google disk and open it in google docs) and delete it from disk""" def get(self, request, employee_id, format_): """Returns employee's CV in format which is equal to `format_` parameter.""" employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) if content_type == 'text/html': try: name = uuid.uuid4().hex + '.html' with open(name, 'w+') as output: output.write(str(data)) return HttpResponseRedirect(file_to_drive(import_file=name)) finally: os.remove(os.path.join(settings.BASE_DIR, name)) return HttpResponse(data, content_type=content_type) file_to_drive from google.oauth2 import service_account from django.conf import settings … -
127.0.0.1:8000 was blocked after securing the site to host
to host my site I went to https the problem is that for the creation of another site I can not connect myself to the http how do I delete the security script but I still have the same error This site can not provide a secure connection -
Access Contrib.Auth User Model Email In My Django Model
So basically, my users already input their email on registration, but I have a separate model with some custom fields that are filled in after registration which show up in the admin section, and I want the email to show there too, but I don't want to ask them for their email twice. What I want to do is a add a field to my model, which just takes their email address from the django auth user model, i.e. class Model(models.Model): field1 = models.CharField email = request.user.email How would I achieve this? -
how to do migrations dynamically in django?
Is there any way that we can create an create an input field dynamically in the form without doing manually work, like first create the particular field in model and then run makemigartions command and then run migrate command. I have tried using formset but that is not what i am looking for. reffer this link -https://demo.vtiger.com/vtigercrm/index.php?module=LayoutEditor&parent=Settings&view=Index&sourceModule=Assets&mode=showFieldLayout when you open this link there is a option "ADD CUSTOM FIELD". i want to do same with my django. Hope i am able to explain you what i wants to do. I am searching for this since 3 days and cannot able to implement that. -
If We disable the admin module of Django , how does user authentication and authorization works
If We disable the admin module of Django , how does user authentication and authorization works. I tried searching but could not get any reference.I am new to Django please help .