Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I combine the data of two querysets?
I have a Model Poller and a Model Vote which stores the votes made by a user for a specific poller. Additionally I use this Model of a third party package to handle comments made to a Poller. Now I would like to attach the information which vote the creator of a comment selected to each comment (comments can only be done if the user already voted). So in my view I got this: def single_poller(request, poller_id): """ renders a specific poller with prepopulated meta according to previous user interaction, e.g. votes and likes """ # Retrieve the item via get poller = Poller.objects.get(poller_id=poller_id) # Get votes and users for rendering comments with vote 1 or vote 2 votes = Vote.objects.filter( poller=poller, user__in=poller.poller_comments.all().values('user') ) Votes Model class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) How can I now link the votes queryset's information to the comments queryset so I can determine for each comment whether the commentor voted for poller_choice_one_vote or poller_choice_two_vote? Cause I think the votes queryset isn't aware of the comment's queryset yet somehow when rendering the template since the comments queryset is rendered by the … -
Filter Data between two number Django
How can I filter my model obj in range of numbers some thing like Item.objects.filter(4500< price < 7500) I try for loop but its too slow and take lots of sources -
How to stop adding delete button to first form in djagno formset?
I am creating a dynamic form using formsets. So basically when user click on "Add Field" button a new form will be created and when user click on trash icon the form should be removed ! Now the problem is that, delete icon is displaying on first default form also so if the click on the icon the default form also gets removed ! How to add delete icon on the cloned forms ? <script> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function addForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); var row = $('.dynamic-form:first').clone(true).get(0); $(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden'); $(row).children().not(':last').children().each(function() { updateElementIndex(this, prefix, formCount); $(this).val(''); }); $(row).find('.delete-row').click(function() { deleteForm(this, prefix); }); $('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1); return false; } function deleteForm(btn, prefix) { $(btn).parents('.dynamic-form').remove(); var forms = $('.dynamic-form'); $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); for (var i=0, formCount=forms.length; i<formCount; i++) { $(forms.get(i)).children().not(':last').children().each(function() { updateElementIndex(this, prefix, i); }); } return false; } </script> <script> $(function () { $('.add-row').click(function() { return addForm(this, 'form'); }); $('.delete-row').click(function() { return deleteForm(this, … -
Django can't connect mysql 8.0.how can fix?
Because I upgraded MySQL 5.7 to MySQL 8.0.26, the dajango project cannot connect to MySQL; python version:3.6 django version:3.2.7 mysqlclient version:1.4.6 pymysql version:0.9.3 mysql-connector-python version:8.0.19 django setting.py database: enter image description here error: enter image description here -
using django regroup tag equivalent in python
I have a project built with django whereby I use django's template engine. I want to switch the frontend from django template engine to reactjs. Everything works quite well using django template engine. I have googled and stackoverflowed everywhere but no solution to my problem. Here is what I did using django template engine (everything works well): # models.py class Post(models.Model): ... publish = models.DateTimeField( default=timezone.now, verbose_name=("Publication date"), ) ... My templatetag looks like this: # blog_tags.py @register.inclusion_tag('blog/month_links_snippet.html') def render_month_links(): all_posts = Post.published.dates('publish', 'month', order='DESC') return {'all_posts': all_posts,} My template file looks like this: # blog/month_links_snippet.html {% regroup all_posts by year as dates_by_year %} <div class="sidebar"> <ul class="active list-unstyled"> {% for month in dates_by_year %} <li id="year{{ month.grouper }}"{% if forloop.first %} class="active"{% endif %}> <h2 style="font-size: 18px"><a href="{% url 'blog:archive-year' month.grouper %}">{{ month.grouper }}</a> <i class="collapsing-icon fa fa-plus"></i></h2> <div class="collapsing-content"> <ul class="list-unstyled"> {% for d in month.list %} <li><a href="{% url 'blog:archive_month_numeric' d|date:"Y" d|date:"n" %}">{{ d|date:"F Y" }}</a></li> {% endfor %} </ul> </div> </li> {% endfor %} </ul> </div> Everything works as expected. Take a look: Blog post archive How can I achieve this using django rest framework? Please remember that this data will later be consumed by reactjs. … -
Nginx giving out a 413 Request entity too large
I have a Django app serving React static files powered by Nginx running in Docker containers. As I'm trying to upload some larger files via my web app I keep receiving 413 Request entity too large from Nginx directly Here is my Nginx config / # nginx -T nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful # configuration file /etc/nginx/nginx.conf: user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } # configuration file /etc/nginx/mime.types: types { text/html html htm shtml; text/css css; text/xml xml; image/gif gif; image/jpeg jpeg jpg; application/javascript js; application/atom+xml atom; application/rss+xml rss; text/mathml mml; text/plain txt; text/vnd.sun.j2me.app-descriptor jad; text/vnd.wap.wml wml; text/x-component htc; image/png png; image/svg+xml svg svgz; image/tiff tif tiff; image/vnd.wap.wbmp wbmp; image/webp webp; image/x-icon ico; image/x-jng jng; image/x-ms-bmp bmp; font/woff woff; font/woff2 woff2; application/java-archive jar war ear; application/json json; application/mac-binhex40 hqx; application/msword doc; application/pdf pdf; application/postscript ps eps ai; application/rtf rtf; application/vnd.apple.mpegurl m3u8; application/vnd.google-earth.kml+xml kml; application/vnd.google-earth.kmz kmz; application/vnd.ms-excel xls; application/vnd.ms-fontobject eot; … -
Django querying data out of models and get sum of field
I'm just beginning with Django and have the following question: I have set up a model looking like class Automation_Apps(models.Model): app_name = models.CharField(max_length=50) app_description = models.TextField(blank=True) view_function_name = models.CharField(max_length=50) time_saver_min = models.IntegerField() implementation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.app_name class Automation_Usage(models.Model): used_app = models.ForeignKey(Automation_Apps, on_delete=models.CASCADE) used_by_user = models.ForeignKey(User, on_delete=models.CASCADE) used_on_date = models.DateTimeField(auto_now_add=True) I would like to query it like: Select Sum(time_saver_min) from Automation_Apps, Automation_Usage where Automation_Usage.used_app = Automation_Apps.app_name I would like to do this in my view. Any help is much appreciated. -
How can I solve the ImproperlyConfigured error in Django
I just started learning django and I'm getting the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. when running the command from myApp.models import Dragons. This is ``models.py`: from django.db import models # Create your models here. class Dragons(models.Model): rider = models.CharField(max_length=200) dragon = models.CharField(max_length=60) This is INSTALLED_APPS inside settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myApp.apps.MyappConfig', ] This is àpps.py: from django.apps import AppConfig class MyappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myApp.apps' And this is the folder structure: Solutions that didn't work: Restarting the server. -
Can we print name in the image using django?
(https://footballshirtmaker.com/) this website prints desired name in the jersey and I want that feature in my e-commerce project and I don't have any idea? -
Problem detecting a language outside views.py in Django
I have a Django app that loads a list of countries and states from a json file and translate them using a custom translaction dictonary little tool I created for this purpose. I don't use gettext for this specific task because gettext doesn't work with data coming from databases or files. First the file that handles the json file from django.utils.translation import gettext_lazy as _, get_language import importlib current_lng = get_language() # importing the appropriate translation file based on current_lng imp = importlib.import_module("countries.translations.countries_%s" % current_lng) import json def readJson(filename): with open(filename, 'r', encoding="utf8") as fp: return json.load(fp) def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], imp.t_countries(x['name'])) all_countries.append(y) return all_countries # the files continues with other function but they are not relevant arr_country = get_country() I use countries_hangler.py in forms.py from django import forms from .models import Address from django.conf import settings from .countries_handler import arr_country from django.utils.translation import gettext_lazy as _ class AddressForm(forms.ModelForm): # data = [] #def __init__(self, data): # self.data = data country = forms.ChoiceField( choices = arr_country, required = False, label=_('Company Country Location'), widget=forms.Select(attrs={'class':'form-control', 'id': 'id_country'}), ) def get_state_by_country(self, country): return return_state_by_country(country) … -
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?