Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fix the internal error in Django?
I don't have a lot of experience in Django and am a fairly green developer. When I run the localhost I keep getting a Internal Error. I have tried most of the solutions to similar problems here and none works. Can anyone help me? The code is not mine so I don't want to alter it as such either. Here is a picture of the errors I keep getting: Error Page -
How to efficiently add objects to ManyToManyFields of multiple objects Django python?
How to efficiently add objects to ManyToManyFields of multiple objects? def handle(self, *args, **kwargs): shops = MyShop.objects.all() for shop in shops: month_invoice = shop.shop_order.annotate(year=TruncYear('created'), month=TruncMonth('created')).values( 'year', 'month', 'shop_id' ).annotate(total=Sum(ExpressionWrapper( (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())), ).order_by('month') for kv in month_invoice: a = ShopInvoice.objects.create(shop_id=kv['shop_id'], year=kv['year'], month=kv['month'], total=kv['total']) test = shop.shop_order.filter(created__month=kv['month'].month, created__year=kv['year'].year) for t in test: a.items.add(t.id) -
How to calculate total price in django?
I'm building an ecommerce website and trying to calculate the total price of the products in views.py but I'm getting an error. Here is my code: @login_required(login_url='/customer/login') @customer() def addtocart(request): if request.user.is_authenticated: buyer = request.user.is_customer cart = Cart.objects.filter(buyer = buyer) amount = 0.00 cart_products = [p for p in Cart.objects.all() if p.buyer == buyer] if cart_products: for p in cart_products: t_amount = (p.products.discounted_price) total_amount += t_amount return render(request, 'Shop/cart.html', {'cart': cart, 'total_amount': total_amount}) This is what it says in the browser: local variable 'total_amount' referenced before assignment. Thank you -
Django loads HTML but doesn't couple static file
I am having trouble serving the static file (CSS) to my HTML page. The HTML loads but the CSS gets the following error on the console: GET http://myip/static/registration/style.cc net::ERR_ABORTED 404 (Not found) This is how I am telling the server to load the HTML with the css: <doctype !html> <html> <head> {% load static %} <link rel="stylesheet" href="{% static 'registration/style.css' %}"> </head> THis is my file structure : omeusite ├── db.sqlite3 ├── manage.py ├── omeusite │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── quizz │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── nano.save │ ├── __pycache__ │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── templates │ │ └── quizz │ │ ├── detail.html │ │ ├── index.html │ │ └── results.html │ ├── tests.py │ ├── … -
I want to fetch the data using api in flutter just like django
I am trying to build freelancing type app. I am using flutter and for my backend data i created an api using django rest framework. Here is the models.py: class Package(models.Model): management_duration_choices = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ("9", "9"), ("10", "10"), ("11", "11"), ("12", "12"), ("13", "13"), ("14", "14"), ("15", "15") ) title = models.CharField(max_length=120) delivery_time = models.ForeignKey( DeliveryTime, on_delete=models.CASCADE, null=True) package_desc = models.TextField(null=True) revision_basic = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_basic") revision_standard = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_standard") revision_premium = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_premium") num_of_pages_for_basic = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_basic", blank=True) num_of_pages_for_standard = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_standard", blank=True) num_of_pages_for_premium = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_premium", blank=True) is_responsive_basic = models.BooleanField(default=False, null=True, blank=True) is_responsive_standard = models.BooleanField(default=False, null=True, blank=True) is_responsive_premium = models.BooleanField(default=False, null=True, blank=True) setup_payment = models.BooleanField(default=False, null=True, blank=True) will_deploy = models.BooleanField(default=False, null=True, blank=True) is_compitable = models.BooleanField(default=False, null=True, blank=True) supported_formats = models.ManyToManyField(FileFormats, blank=True) # For Logo Design provide_vector = models.BooleanField(default=False, null=True, blank=True) is_3dmockup = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_basic = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_standard = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_premium = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_basic = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_standard = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_premium = models.BooleanField(default=False, null=True, blank=True) # For Digital … -
Razorpay payment integration django
I'm trying to integrate razorpay payment gateway for my ecommerce website . It pops up following message " Invalid amount(should be passed in integer paise . Minimum value is 100 paise i.e Rs 1)" Here are the relevant files views.py checkout def checkout(request): form = CheckoutForm(request.POST or None) cart_id = request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) if form.is_valid(): form.instance.cart = cart_obj form.instance.subtotal = cart_obj.total form.instance.discount = 0 form.instance.total = cart_obj.total form.instance.order_status = "Order Received" del request.session['cart_id'] form.save() form=CheckoutForm() return render(request,"pay.html",{"form":form}) else: cart_obj = None return render(request,"checkout.html",{'cart':cart_obj,'form':form}) pay def pay(request): orders=form o_id=orders.id orderr=Order.objects.get(id=o_id) order_amount=orderr.total order_currency="INR" order=client.order.create(dict(amount=order_amount,currency=order_currency)) context={ 'order_id':order['id'], 'amount':order['amount'], 'key_id':key_id } return render(request,"pay.html",context) pay.html <html> <head> <title>Pay</title> </head> <body> <button id="rzp-button1">Pay</button> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "{{key_id}}", // key_id has been generated "amount":"{{amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{order_id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 2 "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "theme": { "color": "#99cc33" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick … -
How to convert Canvas to SimpleDocTemplate?
I am writing in django. And i have to return pdf using buffer and SimpleDocTemplate. But i can only work with Canvas. Is there any easy way to do it? -
Can't load django project with apache
This is my directory structure pic and this is what i added to the apache httpd.conf file LoadModule wsgi_module modules/mod_wsgi.so <IfModule wsgi_module> WSGIScriptAlias / "C:/Users/Administrator/PycharmProjects/pythonProject/TCL/TCL/wsgi.py" WSGIPythonPath "C:/Users/Administrator/PycharmProjects/pythonProject/TCL" <Directory "C:/Users/Administrator/PycharmProjects/pythonProject/TCL"> <Files wsgi.py> Allow from all Require all granted </Files> </Directory> WSGIPythonHome "C:/Users/Administrator/AppData/Local/Programs/Python/Python37" Alias /media/ C:/Users/Administrator/PycharmProjects/pythonProject/TCL/media/ Alias /static/ C:/Users/Administrator/PycharmProjects/pythonProject/TCL/static/ <Directory C:/Users/Administrator/PycharmProjects/pythonProject/TCL/static> Allow from all Require all granted </Directory> <Directory C:/Users/Administrator/PycharmProjects/pythonProject/TCL/media> Allow from all Require all granted </Directory> </IfModule> i installed port 8080 and 4433 but both can't load -
Django CMS drag and drop problems
when changing the arrangement in the right toolbar, the selected element always slides strongly to the right into the void. In this way, it is not possible to restructure the arrangement sensibly. Does anyone have the same problem or a solution? -
Unable to make django-master-password work
I would like to enable a master password in my DRF (React.js + Django) website using django-master-password. After following the instructions as best as I could understand them, here are the relevant parts of settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', # 3rd party apps 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'corsheaders', 'import_export', 'django_admin_logs', 'master_password', # Local apps 'users', # Responsible for all actions pertaining to user model 'content', 'payments' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", "master_password.auth.ModelBackend" ) MASTER_PASSWORDS = { 'Abc123': None } However, when I try to log into a user account with Abc123 as password, I still get the response {non_field_errors: ["Unable to log in with provided credentials."]}. What am I missing? -
Exclude history fields from django simples history on to_representation method in django rest framework
I'm using Django Rest Framework with django-simple-history and currently I would like to return the history modifications in my rest API, currently it is doing well but I would like to hide some fields. This is the currently output: But, I don't need id, history_id, etc. my implementation is the same of alexander answer in this post. What i've tried: def to_representation(self, data): representation = super().to_representation(data.values()) del representation[0]['history_id'] return representation But it does not seem the best way to do it. If you have some hint about how to do it the correct way I would like to know. Thanks in advance! -
DJANGO DEBTORS LIST
i have two model with the same names, i want to display its value(display repeated names once) and its summation. what i have been achieved so far is to to do only for Invoice table and working perfect, but when i want to add receiptmodel doesn1t not arrange as invoice arranged model.py from django.db import models class invoice(models.Model): customer = models.CharField(max_length=100, null=False) total_amount = models.DecimalField(max_digits=20, decimal_places=2) class Meta: db_table="invoice" class ReceiptModel(models.Model): customer = models.CharField(max_length=100, blank=True, unique=False) to_amount = models.CharField(max_length=100, blank=True, unique=False) class Meta: db_table="receiptmodel" view.py from django.shortcuts import render, redirect, get_object_or_404, reverse from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.forms import modelformset_factory #from django.forms import ModelForm from .models import * from .forms import *#UserRegisterForm, InvoiceForm, LineItemFormset, NewCustomerForm, CustomerReceiptForm from django.urls import * from itertools import chain from operator import attrgetter from django.db.models import Sum, Q def ReceivableReport(request): #still not working receivable_inv = Invoice.objects.values("customer").annotate(totinv= Sum('total_amount')) receivable_rec = ReceiptModel.objects.values("customer").annotate(totrec= Sum('to_amount')) #zipped_data = zip(receivable_inv, receivable_rec) #zipped_data = list(chain(receivable_inv,receivable_rec)) context = { 'receivable_inv':receivable_inv, 'receivable_rec':receivable_rec, # 'zipped_data ':zipped_data, } return render(request, "reports/debtorlist.html", context) debtorlist.html <table style="width: 50%;"> <thead> <tr> <th>Name</th> <th>Inv Amount</th> <th>Rec Amount</th> </tr> </thead> {% for receivable_inv in receivable_inv%} <tbody> <tr> <td>{{ receivable_inv.customer }}</td> <td>{{ receivable_inv.totinv}}</td> <td>{{ receivable_rec.totrec}}</td> </tr> … -
How Django handle multiple requests send at the same time
I have checked most of the comments and the answer always was that Django (on local machine) handles only one request at a time. I have simple django application with view function that waits 5 seconds. When I run two the same GET requests in postman, I can see both requests are handled in the same time, they are not queued or overwritten one by another. My question is how it is possible? My view code: def wait_some_time(request): import time print("Printed immediately.") time.sleep(5) print("Printed after 5 seconds.") return Response({'message': 'nothing'}) Postman request: Postman request (I'm sending 2 requests in the same time) Console output: Printed immediately. Printed immediately. Printed after 5 seconds. [05/Jan/2022 14:55:35] "GET /api/user/test HTTP/1.1" 200 21 Printed after 5 seconds. [05/Jan/2022 14:55:36] "GET /api/user/test HTTP/1.1" 200 21 -
nginx/gunicorn/django 403 forbidden error
I've built a small website using django, gunicorn, and nginx. So far what I have for /etc/nginx/sites-available/blog is upstream django { server 127.0.0.1:8080; } server { listen 172.17.0.1:80; server_name my.broken.blog; index index.html; location = /assets/favicon.ico { access_log off; log_not_found off; } location /assets { autoindex on; alias /var/www/html/mysite/assets; } location / { autoindex on; uwsgi_pass unix:///run/uwsgi/django/socket; include /var/www/html/mysite/mysite/uwsgi_params; proxy_pass http://unix:/run/gunicorn.sock; } } The error.log file shows that 2022/01/05 13:50:55 [error] 194#194: *2 directory index of "/var/www/html/" is forbidden, client: ip-address, server: _, request: "GET / HTTP/1.1", host: "my.broken.blog" -
Whitelisted email in SOCIAL-AUTH-APP-DJANGO
I am figuring how to restrict people to log in to my website. I am using the Python library social-auth-app-django. In the documentation they said to add auth_allowed to the pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) But I am not sure how to configure my code. I even added SOCIAL_AUTH_GOOGLE_WHITELISTED_EMAILS = ['me@foo.com'] But still it doesn't seem to work -
What is ajax gets invalid form, How can i render it?
I am working with Django and Ajax. With the help of jQuery, i successfully sent form data to server and able to validate it. Problem arrive when form is invalid, i want that, if the form is invalid, ajax get the invalid form and render it to same template with errors like all invalid forms do. How Can i do it ? -
Django & Djoser 'NoneType' object has no attribute 'lower' 'NoneType' object has no attribute 'lower'
I keep having an error whenever I try to PATCH in order to update a specific user info. As per Djoser documentation, the endpoint is located in /users/me/ https://djoser.readthedocs.io/en/latest/base_endpoints.html#user Everything is working fine except this part. I have a Custom User model and overrided the default (again, as per documentation) 'current_user': 'accounts.serializers.UserCreateSerializer', serializer.py class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'first_name', 'last_name', 'is_active') models.py class UserAccountManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('Un email est obligatoire') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone = models.CharField(max_length=50) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = UserAccountManager() def get_full_name(self): return self.first_name def get_short_name(self): return self.first_name def __str__(self): return self.email What am I missing? -
Multiple buttons in for loop doesn't work because of the same id
So i want to build a website that has some cointainers for each object in my database and the same 2 buttons on each, "reguli" and "cumpara", everything works fine until i press the buttons. They work only for the first cointainer. My guess is that having the same id for each button of all containers, they work only as one. How could i change the id's of the buttons for each object in the database? &bulletEVENIMENTE&bullet <div class="feturedimage"> <div class="row firstrow"> <div class="col-lg-6 costumcol colborder1"> <div class="row costumrow"> {% for obj in events %} <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 txt1colon "> <div class="featurecontant"> <h1>{{obj.Nume}}</h1> <p>"{{obj.Descriere}}"</p> <h2>Price {{obj.Pret}}</h2> <button id="btnRM" onclick="rmtxt()">REGULI</button> <div id="readmore"> <p>Biletele se cumpara cu cardul nu se poate da refund distractie faina! </p> <button id="btnRL">READ LESS</button> </div> <button id="btncumpara" onclick="rmtxt()">CUMPARA</button> </div> </div> {% endfor %} </div> </div> <div class="col-lg-6 costumcol colborder2"> <div class="row costumrow"> </div> </div> -
How to access the return value from outside the function in Django
I wanted to access the value of the function outside in Django rest framework. I have checked this function which return value but I want to call that return value in another function. I have tried this approach where I'm getting output ticketid as 'None' views.py: def GetUserTaskId(request): userid = request.data.get('UserId') ReportId = request.data.get('ReportId') cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetUserTaskId] @UserId=%s, @Ticket=%s', (userid, ReportId)) result_set =cursor.fetchall() for row in result_set: TaskId=row[0] return Response({"TaskId":TaskId}) def inserttask(request): ticketId = GetUserTaskId(request) print("ticketId--->",ticketId) /***somecode***/ -
'tuple' object has no attribute 'created' when downloading data as a excel format in django?
views.py def download_excel(request): if request.user.admin == True and request.user.admin_approval == True: # content-type of response response = HttpResponse(content_type='application/ms-excel') #decide file name response['Content-Disposition'] = 'attachment; filename=Products' + \ str(datetime.datetime.now()) + '.xls' #creating workbook wb = xlwt.Workbook(encoding='utf-8') #adding sheet ws = wb.add_sheet("Products") # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() date_style = xlwt.XFStyle() date_style.num_format_str = 'DD-MM-YY' # headers are bold font_style.font.bold = True #column header names, you can use your own headers here columns = ['Added Date', 'Modified Date', 'Vendor ID','Product ID','Item No','Color','Stock','Approval Status','Approved Date','Approved By', ] #write column headers in sheet for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = ProductVariants.objects.all().values_list('created','edited','vendoruser','product_id', 'item_num','variant_value','initial_stock','approval_status', 'approved_date','approved_by',) for my_row in rows: row_num = row_num + 1 ws.write(row_num, 0, my_row.created, font_style) ws.write(row_num, 1, my_row.edited, font_style) ws.write(row_num, 2, my_row.vendoruser, font_style) ws.write(row_num, 3, my_row.product_id, font_style) ws.write(row_num, 4, my_row.item_num, font_style) ws.write(row_num, 5, my_row.variant_value, font_style) ws.write(row_num, 6, my_row.initial_stock, font_style) ws.write(row_num, 7, my_row.approval_status, font_style) ws.write(row_num, 8, my_row.approved_date, font_style) ws.write(row_num, 9, my_row.approved_by, font_style) wb.save(response) return response I used this and it works, but I don't get the foreign key values, instead, I get the id of the foreign key field. So, I used the above code, but that gives error … -
how to get choice data from database and style the form fields in django
please i need a solution to this problem: i have a model called transaction, and a form called TransactionForm as below I want to style the form so i can get a select element for the vehicle and checkbox element for the services when i render it in my template. although am able to make that happen for the vehicle but unable to make it possible for services . rendering the form without the styling works very well but with styling i dont get the choice data from database. how do i achieve this pls class Transaction(models.Model): name= models.CharField(max_length=200,null=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, null=True) services = models.ForeignKey(ServiceType, on_delete=models.SET_NULL, null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.get_full_name() TransactionForm class TransactionForm(forms.ModelForm): class Meta: model = Transaction fields = "__all__" exclude = [ 'user'] vehicle = forms.ModelChoiceField( queryset=Vehicle.objects.all(), required=True, label='Select vehicle Type', widget=forms.Select(attrs={ 'placeholder':'Select vehicle Type', 'class':'form-select' })) services = forms.MultipleChoiceField( required=True, label='Select Service Type', widget=forms.CheckboxSelectMultiple( choices=[(service.pk, service.name) for service in ServiceType.objects.all()], attrs={ 'class':'form-select' })) -
How to filter data max marks with attributes from models to view in Django-rest-framework Api?
from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from .models import StudentDetails, Course, Subjects, Teachers, Marks from .serializers import * from django.db.models import Avg, Max, Min @api_view(['GET']) def studentlist(request,*args,**kwargs): max_marks = Marks.objects.filter(student_id=30).aggregate(total_marks=Max('total_marks')) ['total_marks'] serializer = StudentDetailsSerializers(max_marks, many=True) return Response(serializer.data) OUTPUT: HTTP 200 OK HTTP 200 OK Allow: GET, OPTIONS Content-Type: application/json Vary: Accept [] I'm trying to figure out max of total marks from model name Marks using DRF API, After runing server it showing nothing, Is there to add any line above code to find max(total_marks). -
Django - How to add multiple objects one after another
I want to make a Quiz app, u will enter the app and u will have 2 buttons: Create a Quiz Solve a Quiz When you press "Create a quiz" you will need to insert your name and press a button that takes you to add a new question in that quiz.I can only add one question, after i press submit it stops. The problem is that i want to continuously add questions and stop when i added enough. Each question to have a button Add Next Question that automatically saves the question and goes to add the next one and the Finnish Quiz button that stops the proccess of adding questions.I dont know how to add the questions continuously. Views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView, TemplateView, DetailView from quiz.forms import QuestionForm, QuizIdentifierForm from quiz.models import Question, QuizIdentifier # HOMEPAGE class HomeTemplateView(TemplateView): template_name = "quiz/homepage.html" # QUIZ class QuizCreateView(CreateView): template_name = 'quiz/add_quiz.html' model = QuizIdentifier form_class = QuizIdentifierForm def get_success_url(self): return reverse_lazy('add-question', kwargs={'quiz_id': self.object.pk}) class QuizDetailView(DetailView): template_name = 'quiz/detail_quiz.html' model = QuizIdentifier # QUESTION class QuestionCreateView(CreateView): template_name = 'quiz/add_question.html' model = Question success_url = reverse_lazy('home') form_class = QuestionForm def form_valid(self, form): res = … -
Universal password for effective handling of bug reports
When a user of my website submits a bug report, I would like to be able to log into the staging website (so that a non-production copy of the database is used) as him to see exactly what he sees. I could achieve this by changing his user email address to mine and then resetting the password. However, it would simplify things if I could enable a universal password for the staging website, using which I could login as any user. Is there a way to achieve this with Django authentication? -
Validation of reset password link in DJANGO
So I already know that the default Time of Validation for the password reset link is 3 days, . from - https://docs.djangoproject.com/en/4.0/ref/settings/#password-reset-timeout but what happen if i send 3-4 mails for reset password,i use only one of them - what about the another links ? as i say i sent 3-4 mails so i have 3-4 links. If I used one link will the rest of the links no longer be valid? someone know how its work ?