Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Site is Opening when DEBUG=False but When DEBUG=True getting this nginx error
2021/09/19 19:48:19 [error] 15790#15790: *1 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 103.242.189.63, server: api.znas.in, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/zsgunicorn.sock:/admin", host: "api.znas.in" -
Time multiplication per hourly wage
I am writing a code for a flight school management software. Basically, I have to enter the Departure and Arrival flight time, make the difference between the two times and make the multiplication for the hourly flight instructor wage. My code is something like this: time_1 = datetime.strptime('05:00:00',"%H:%M:%S") time_2 = datetime.strptime('10:00:00',"%H:%M:%S") time_interval = time_2 - time_1 print(time_difference) The problem I am facing, basically, is how to make the multiplication between the time_interval variable and the hourly wage of the flight instructor. Does anybody have any suggestion about that? -
Manipulating the output of variables in Django with JavaScript function
I use this piece of code to grab part of the description from video object: <div id="description"> <p>{{video.description | slice:":20" }}</p> <button onclick="showDescription()">Show description</button> </div> There I got showDescription() function, I want it to display the rest of description by changing inner HTML code: function showDescription() { var text = document.getElementById('description') text.innerHTML = "<p style='overflow-wrap: break-word; width: 100%;'>{{video.description}}</p>" }; But it returns {{video.description}} Instead of actual description, any thoughts? -
Bootstrap 5 navbar single items differently aligned
This is actually my first question on Stackoverflow since I am quite new to web-developing, as you will notice by my following question: I've been sitting on this for HOURS, and it just seems so simple, but somehow, I can't get this button on this navbar to be aligned right. I want "Anhänger", "Camping" and "Kontakt" centered and only the button "Anfahrt" on the right. Now, first I got really confused with all the different bootstrap versions and the different commands, and my actual progress is the second toolbar here: https://www.codeply.com/p/DjlnoDXYCt As you can see, I got the "Anfahrt" Button to be aligned right through "ms-auto", but then "justify-content-end" doesn't work! Can someone help me? It seems like such an easy problem, but I cannot get my head around it.. -
check user have liked msg or not from list of messages
suppose class Msg(models.Model): ... likes = models.ManyToManyField(User,...) channelname = models.CharField(...) Now my queryset is queryset = Msg.objects.filter(channelname='home') What should i do after this to get somelike [{id:xyz,liked=true},{id:tuv,liked=true},{id:abc,liked:false}] -
django for loop on html cannot retrieve every data fields for its object_lists
Why for my output.htm file, when I use django template "for loop" tags to retrieve data on {{ post.firstname }} and also {{ post.surname }}, it shows no result? Hope for help. Thanks in advance. Ps: below code is only part of the work. This mean I didn't write out python libraries, full html for below code. #views.py class Student_list(View): def get(self, request): posts = Student.objects.all().values_list("firstname", "surname").union(Teacher.objects.all().values_list("firstname", "surname")) """raw sql => SELECT * FROM l2_OR_queries_student WHERE surname LIKE 'bald%' OR surname LIKE 'aus%' """ return render(request, "l4_UNION_queries/output.htm", context = {"posts": posts}) <!--output.htm --> <table> <tr> <th>First Name</th> <th>Surname</th> </tr> {% for post in posts %} <tr> <td>{{ post.firstname }}</td> <td>{{ post.surname }}</td> </tr> {% endfor %} </table> student.sqlite3 id firstname surname age classroom teacher 4 shaina austin 20 1 trellany 5 raquel avery-parker 21 2 robin 6 lakisha baldwin 20 3 crystal teacher.sqlite3 id firstname surname 9 trellany abraham 10 robin adkins 11 crystal allen 12 shaina young -
i dont why it says that can find the file
https://github.com/Angelheartha/ruciferversion6 as i didnt know where is the problem i post here my github this is my github here, i was trying to work with forms but when i did run https://127.0.0.1:8000/catalog/author/book/<bookinstance_id>/renew it says not pages founded i dont have idea where i am wrong i tried couples things but i didnt found solutions -
django-formtools form wizard in django web app
My requirements in form-wizard: 1.A multi-step form. 2.If a certain form does not contain any options in select fields or dropdowns, provide a plus icon where user create it and select it (latest created), just like django-admin forms. 3.form data should be available in next form. eg:-form0- created an instance. form1- that instance of form0, should be available in a certain dropdown's of form1. What i want: I referred django-formtools to acheive this, but i need more insights/flow or knowledge about which methods should i override, what should be the flow etc. -
Django Rest Framework Swagger API . paginate_queryset takes long time to execute
I designed a REST API with Swagger. When a client tries to fetch response using the API, he gets no response (Response 500). Response Code 500 Response Headers { "connection": "close", "content-length": "131", "content-type": "text/html", "date": "Sun, 19 Sep 2021 10:50:08 GMT" } The issue happens in pagination.py def paginate_queryset(self, queryset, request, view=None): """ Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = self.get_page_number(request, paginator) try: self.page = paginator.page(page_number) except InvalidPage as exc: msg = self.invalid_page_message.format( page_number=page_number, message=str(exc) ) raise NotFound(msg) if paginator.num_pages > 1 and self.template is not None: # The browsable API should display pagination controls. self.display_page_controls = True self.request = request return list(self.page) I put two print statements, before and after list(self.page) . As you can see from the below print statements, return list(self.page) takes a long time. [Sun Sep 19 10:49:44.066406 2021] [pid 108994] File: pagination.py, Class: PageNumberPagination, Function: paginate_queryset. **Before list(self.page)**. self.page= <Page 1 of 223291> [Sun Sep 19 11:08:21.092237 2021] [pid 108994] File: pagination.py, Class: PageNumberPagination, Function: paginate_queryset. **After list(self.page)**. As you can see, list(self.page) took almost 20 … -
Staying login problem about CallbackURL after payment
my view is like : def get_user_pending_order(request): user_profile = get_object_or_404(Profile, user=request.user) order = Order.objects.filter(owner=user_profile, is_ordered=False) if order.exists(): return order[0] return 0 MERCHANT = 'xxx...xxx' ZP_API_REQUEST = "https://api.zarinpal.com/pg/v4/payment/request.json" ZP_API_VERIFY = "https://api.zarinpal.com/pg/v4/payment/verify.json" ZP_API_STARTPAY = "https://www.zarinpal.com/pg/StartPay/{authority}" amount = '' description = "text" # Required email = 'example@email.com' # Optional mobile = '09999999999' # Optional # Important: need to edit for realy server. CallbackURL = 'https://example.com/payment/verify/' def send_request(request): print(get_user_pending_order(request).owner.phone_number) req_data = { "merchant_id": MERCHANT, "amount": int(get_user_pending_order(request).get_total()), "callback_url": CallbackURL, "description": description, "metadata": {"mobile": mobile, "email": email} } req_header = {"accept": "application/json", "content-type": "application/json'"} req = requests.post(url=ZP_API_REQUEST, data=json.dumps( req_data), headers=req_header) authority = req.json()['data']['authority'] if len(req.json()['errors']) == 0: return redirect(ZP_API_STARTPAY.format(authority=authority)) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") def verify(request): t_status = request.GET.get('Status') t_authority = request.GET['Authority'] if request.GET.get('Status') == 'OK': req_header = {"accept": "application/json", "content-type": "application/json'"} req_data = { "merchant_id": MERCHANT, "amount": int(get_user_pending_order(request).get_total()), "authority": t_authority } req = requests.post(url=ZP_API_VERIFY, data=json.dumps(req_data), headers=req_header) if len(req.json()['errors']) == 0: t_status = req.json()['data']['code'] if t_status == 100: user = request.user order_to_purchase = get_user_pending_order(request) order_to_purchase.is_ordered = True order_to_purchase.date_ordered=datetime.datetime.now() order_to_purchase.created_on_time=datetime.datetime.now() order_to_purchase.save() order_items = order_to_purchase.items.all() for order_item in order_items: order_item.product.quantity = order_item.product.quantity - 1 order_item.product.save() order_items.update(is_ordered=True, date_ordered=datetime.datetime.now()) subject = 'successful' c = { "refid":str(req.json()['data']['ref_id']), "ref_code":order_to_purchase.ref_code, "owner":order_to_purchase.owner, } email_template_name = … -
AttributeError: 'Request' object has no attribute 'Get' while making a GET request
I am trying to make a Get request , but am getting this error : AttributeError: 'Request' object has no attribute 'Get' Below is my code : class VerifyEmail(APIView): """Verify user account.""" serializer_class = EmailVerificationSerializer def get(self, request): """Obtain email token.""" token = request.Get.get('token') payload = jwt.decode(token, settings.SECRET_KEY) In the urls.py : path('email-verify/', views.VerifyEmail.as_view(), name='email-verify'), The issue is on this line : token = request.Get.get('token') What could be the issue for this ? -
How to solve this issue in Django 3.2?
While developing an django website i came across an issue. please anyone give a solution how to fix this situation. what iam trying to do is creating two gallery page. if anyone clicked image on first page redirect to another page contain more images of it. Please help, Thanks in advance. -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' (settings.py)
settings.py SECURE_SSL_REDIRECT=bool(int(os.environ.get('SECURE_SSL_REDIRECT'))) I retrieve the following error: line 57, in <module> SECURE_SSL_REDIRECT=bool(int(os.environ.get('SECURE_SSL_REDIRECT'))) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' please solve this -
Setting a password for a model(non User) in django for simple authentication
For my website, i am not planning to make it compulsory for the users to sign up. Instead, they can create a post and set a password for it in order to manage it. I can use the 'set_password' method django provides for the User model: def set_password(self, raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '%s$%s$%s' % (algo, salt, hsh) so that sorts out the storing password part. But this will hash the password (which is good) but now i am stuck on how to authenticate this?? So when someone wants to edit the instance of the model they have created, they first need to be authenticated. How do i go about doing that? Thank you -
how to get str from POST method and save in db nad return a message with str in django?
so, The contents of the POST request Task/name The received object is just a string and a Task object must be created using this string. This string is equal to the same name field in the Task object. This page is located at the following URL: http: // localhost: 8000 / tasks After adding the task, the following message should be displayed to the user: For example, if a task called 'Study for 2 hours' is added, the following message should be displayed to the user: Task Created: 'Study for 2 hours' model : from django.db import models class Task(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name view: from .models import * from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def list_create_tasks(request): if request.method == 'POST': name = request.POST.get('name') all_task = Task(name=name) all_task.save() return HttpResponse(f"Task Created: {name}") It does not work according to the view. How do I fix it? -
ValueError: time data 'Sept. 30, 2021' does not match format '%B %d, %Y'
I have a web app,backend using Django, frontend normal HTML5. when I tried to convert the date sent from frontend, error occurs:ValueError: time data 'Sept. 30, 2021' does not match format '%B %d, %Y' at this line end_date = datetime.strptime(end_date, '%B %d, %Y').strftime('%Y-%m-%d') view.py: @csrf_exempt def assign_to_exec(request): if request.method == 'GET': end_date = request.GET.getlist('end_date')[0] end_date = datetime.strptime(end_date, '%B %d, %Y').strftime('%Y-%m-%d') How could I correct it? -
Using JsonField in django to make a simple post api
I have a task to create a simple post api to send a visitor messages through a contact form. I created a model name Contacts and created api using APIView. But when the code was reviewed, I was suggested to use a jsonfield which is already defined in a Core model. So I am quite stuck how to use it. My Core model is like this: class Core(models.Model): """ Model that saves the corresponding credentials for the slug. """ slug = models.CharField(max_length=255, null=False) example = models.JSONField(null=False, default=dict) def __str__(self) -> str: return self.slug I have searched and found that I can pass a dictionary data inside the example field, but I dont know how to use it. What I have done is like this for now. I have a model just below the core model named Conatcts and created the serializer and view files. class Contacts(models.Model): full_name = models.CharField(max_length=100,blank=True,default="") email = models.EmailField() phone = models.CharField(max_length= 16) address = models.CharField(max_length=255,blank=True,default="") message = RichTextField() def __str__(self): return self.email class Meta: verbose_name_plural = 'Visitor Messages' My view: class ContactsView(APIView): permission_classes = [AllowAny] def post(self,request): data = request.data serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({ 'message': "You message has been sent successfully.", 'data':serializer.data … -
How to get all the data from form submission in django
I am very much new to Django. I am working on an online school system. I am very much new to Django. I have created a student list in my database and from that database, I have retrieved that student data to my template and displayed them on a table. Now I want to confirm they are present to the class and get that data back to the backend. I have added a select option for that to select yes and no. Then I have added a submit button. But after submitting I get only the data of the last student. Please explain to me how to get all the student data to the backend. This is a great help. My model class StudentAttendance(models.Model): grade = models.CharField(max_length=100, null=True, blank=True) subject = models.CharField(max_length=100, null=True, blank=True) admission_number = models.CharField(max_length=100, null=True, blank=True) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) attendance = models.CharField(max_length=100, null=True, blank=True) held_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) submit_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return self.grade My view @login_required(login_url='login') def grade8_dashboard(request): if request.method == "POST": grade = request.POST.get("grade","") subject = request.POST.get("subject","") admission_number = request.POST.get("admission_number","") first_name = request.POST.get("first_name","") last_name = request.POST.get("last_name","") attendance = request.POST.get("attendance","") # held_date = request.POST.get("held_date","") submit_date … -
modify query_params in django in djangofilterbackends
i have a model called product as below, for which i am proving filters using djangofilterbackend with filter_fields = 'all' class Product(models.Model): id name created_at updated_at price and so on.... now when someone sends a query_param related to datetime like "created_at", "updated_at" they are sending epoch timestamps. is there any way to convert epoch timestamps in query_params to datetime ?? things ive tried : ive tried to modify the request_dict in get_queryset identifying the timestamp params and converting them to datetime django. But the request_dict is immutable in DRF. is there any way to modify the query_params in djangofilterbackend ? -
Django: unsupported operand type(s) for +: 'int' and 'str'
I want to sum all the fields of a model by using aggregate(sum()) function but getting this error. Views.py def paymentdailyreport(request): cashsum= Payment.objects.filter(PaymentMethod="Cash").aggregate(sum('Amount')) print(cashsum) context={ } return render(request,'paymentdailyreport.html',context) Models.py class Payment(models.Model): Date=models.CharField(max_length=20) User=models.CharField(max_length=50) PatientName=models.CharField(max_length=50) Dentist=models.CharField(max_length=50) Scheme=models.CharField(max_length=50) PaymentMethod=models.CharField(max_length=50) Amount=models.DecimalField(max_digits=20,decimal_places=3) def __str__(self): return self.Date + " | " + self.User + " | " + self.PatientName -
How to implement Elastic Search with Django rest framework without using viewsets?
I want to design a search system using Django rest framework and Elastic Search. I could not get a proper tutorial on what each of the things mentioned in elasticsearch-dsl and elasticsearch-dsl-drf stand and how to use them with full explanation. Any guides and suggestions would be very highly appreciated. -
How to fix DetailView is missing a QuerySet Error?
When I try to use DetailView to view my posts I keep getting an exception error. ImproperlyConfigured at /musician_details/1/ DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/musician_details/1/ Django Version: 3.2.5 Exception Type: ImproperlyConfigured Exception Value: DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Exception Location: C:\Program Files\Python38\lib\site-packages\django\views\generic\detail.py, line 69, in get_queryset Python Executable: C:\Program Files\Python38\python.exe Python Version: 3.8.2 Python Path: ['F:\Full Stack\Django\Django Project\Test', 'C:\Program Files\Python38\python38.zip', 'C:\Program Files\Python38\DLLs', 'C:\Program Files\Python38\lib', 'C:\Program Files\Python38', 'C:\Users\Tanim\AppData\Roaming\Python\Python38\site-packages', 'C:\Program Files\Python38\lib\site-packages', 'C:\Program Files\Python38\lib\site-packages\win32', 'C:\Program Files\Python38\lib\site-packages\win32\lib', 'C:\Program Files\Python38\lib\site-packages\Pythonwin'] Server time: Sun, 19 Sep 2021 07:44:37 +0000 views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import View, TemplateView, ListView, DetailView from home import models class IndexView(ListView): context_object_name = 'musician_list' model = models.Musician template_name = 'first_app/index.html' class MusicianDetail(DetailView): context_object_name = 'musician' model = models.Musician template_name = 'first_app/musician_details.html' models.py from django.db import models # Create your models here. class Musician(models.Model): first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) instrument=models.CharField(max_length=50) def __str__(self): return self.first_name + " " + self.last_name class Album(models.Model): artist=models.ForeignKey(Musician, on_delete=models.CASCADE) name=models.CharField(max_length=100) release_date=models.DateField() rating=( (1,"Worst"), (2,"Bad"), (3,"Not Bad"), (4,"Good"), (5,"Excellent!"), ) num_Stars=models.IntegerField(choices=rating) def __str__(self): return self.name +", Rating: " +str(self.num_Stars) models.py from django.contrib import admin from django.urls import path from home … -
Django: How to create a separate endpoint login link for admin/staff users
Currently I've been using the generic login/register links (.../account/login, .../account/register etc) which lets all users (staff and non-staff) to login. I'm creating a separate app for only staff members and I'd like to have a separate endpoint link (.../acccount/staff-login) that would only allow staff members to get tokens. This seems pretty basic but I haven't been able to find anything for this. -
Reorder django form fields
I try to reorder a form fields but I do not find a proper way. This is my form class UserSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(UserSignupForm, self).__init__(*args, **kwargs) self.fields["first_name"] = CharField(label="Prénom") self.fields.keyOrder = ['first_name', 'email', 'password1', 'password2'] and the render into the template <form class="signup" id="user_signup_form" method="post" action="{% url 'user_signup' %}"> {% csrf_token %} {{ form|bulma }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/> {% endif %} <button type="submit" class="button is-primary">{% trans "Sign Up" %}</button> </form> as you can see, I override the SignupForm from django-allauth with a field addition. Then, I would like to reorder fields to set the first_name as 1st fields. Unfortunately, I do not find a solution and don't want to edit the html render. Any solution ? -
Django forms for quiz app ( how to disable a form after submission )
I am creating a classroom app. Which has a exam section where students can give test. If a student wants to give a exam he/she has to select subject and then has to go in exam section. I want student to have access to exam form for one time.