Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to add next to manual login redirect?
I have a view: def create_something(request): ... I want to redirect to login if a person isn't logged in. Normally I'd use: @login_required def create_something(request): ... but 🍑.... I want to add a message before the redirect. I wanted to do it like this: def create_something(request): if not request.user.is_authenticated: messages.info(request, 'You must be logged in to create a thing 👀.') return redirect('login') ... However, that doesn't include a ?next in the url to go back to the page I was going to. So my question is: How would you manually redirect back to the login page WITH a manually added ?next query? -
Spanning multi-valued relationships
I read the django documentation and I found something confusing! https://docs.djangoproject.com/en/3.2/topics/db/queries/#spanning-multi-valued-relationships. It is stated that "When you are filtering an object based on a ManyToManyField or a reverse ForeignKey, there are two different sorts of filter you may be interested in" "To select all blogs that contain entries with both “Lennon” in the headline and that were published in 2008 (the same entry satisfying both conditions), we would write:" Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) "To select all blogs that contain an entry with “Lennon” in the headline as well as an entry that was published in 2008, we would write:" Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) "Suppose there is only one blog that had both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog" So, by reading this guide, multiple questions have been created in my mind: 1- What is difference between these two types of filtering? what I know is that both of them must return blogs that contain both 'Lennon' in headline and was published in 2008. I can't find out the point. 2- The Document says this rule is just … -
why i am getting TypeError: create_superuser() missing 1 required positional argument: 'username' in AbstractUser?
I am have written a custom User model and when trying to create superuser got the following error**:-** TypeError: create_superuser() missing 1 required positional argument: 'username' when i run the command for creating superuser, django did't asked me to enter username field. Model Class:- class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False, unique=True) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False) password = models.CharField(max_length=15, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] this is all what i have written, and i am new django unable to figure out what i am doing wrong. Thanks in advance. Hope to here from you soon. -
Django: how apply uuid django.contrib.auth migration
I create a project Django with Postgres. I only apply to User model. But I want to use uuid for field primary key id in all models in app django.contrib.auth such as User, Permission, Group ... Beside, I want to apply uuid for all migrations of my project How can I do that, please help me. -
Django API path restrict
I am pretty new to Django REST framework and have made an app with React/Django REST by following a tutorial. I am including an example on how it's done urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), path('api/register/', RegisterAPI.as_view(), name='register'), ] views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): ... and then let's say index.html contains registration form that generates JSON request and sends it to the register url included above and then it obviously gets processed by the view and response is generated. This is all cool and simple. However, now let's say that some user goes to the url http://127.0.0.1:8000/api/register/. He/she will then access my auto built django rest page with the form that doesn't look very "production-ready". I was wondering if there was a way to allow this page to be accessed by the react, but when we try accessing this url physically, I want the page to redirect us to some other page, or show 404 error. Is there a way to do this? Thanks for the help! -
Django form not rendering widget
I can't figure out, why the django form widget is not rendered in the browser. This is my form: from django import forms from .models import RealEstateTax class CreateRealEstateForm(forms.ModelForm): class Meta: model = RealEstateTax fields = ['invoice_number',] widget = { 'invoice_number': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here'}), } Just for testing purposes, I reattributed the field as a Textarea and gave it a class where the text should appear red. This is the template: {% extends 'main.html' %} {% load static %} {% block title %} Create Realestate Tax {% endblock %} {% block content %} <style> .form-control { color: red; } </style> <form method="post"> <div class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-info">Send</button> </div> </form> {% endblock %} When I inspect the element in the browser, there is no class, it is not a Textarea and the text is not red: This is what I specified in the view: from realestate.models import RealEstate from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.db.models import Sum from realestate.models import RealEstate from .forms import CreateRealEstateForm def create_real_tax(request): form = CreateRealEstateForm if request.method == 'POST': form = CreateRealEstateForm(request.POST) if form.is_valid(): form.save() print(form.base_fields) context = … -
Django: Query database from Channels consumers
I had a Django app which had live chat working. Now I am trying to add a query to the database within the connect method. I am following the Channels documentation, and tried the solution in this other StackOverflow question but nothing is working. Below is my code. The error I'm seeing in the Javascript console is WebSocket connection to 'ws://localhost:9008/ws/chat/334/' failed: WebSocket is closed before the connection is established. I do have redis-server running on localhost and that was working before, so that's not a problem. async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name valid_connection = await database_sync_to_async(self.verify_chat_room_key)() # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def verify_chat_room_key(self): trans = database_sync_to_async(Transaction.objects.get)(id=self.room_name) return True -
Django view filter count
I want to get to know the number 'tasks' (Pendentes) for each 'Customer' (Cliente) I have this models in my models.py: class Cliente(models.Model): id = models.IntegerField(primary_key=True) nome = models.CharField(max_length=200, help_text="Nome") localidade = models.CharField(max_length=100, help_text="Localidade") [...] class Pendente(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID Unico") cliente = models.ForeignKey('Cliente', on_delete=models.RESTRICT, blank=True, null=True) memo = models.TextField(null=True, blank=True, help_text="Memória Descritiva", max_length=200) criado = models.DateField(default=date.today, null=True, blank=True, help_text="Data registo ") concluir = models.DateField(null=True, blank=True, help_text="Data de execução máxima ") tecnico = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) tecnicoatribuido = models.ForeignKey('TecnicoAtribuido', on_delete=models.SET_NULL, blank=True, null=True) Basicly i want to run this sql: "select A.id, A.nome, A.localidade, count(B.id) as tarefas from todolist_pendente B LEFT JOIN todolist_cliente A ON A.id = B.cliente_id GROUP by A.id;" Can't seem to figure out how it would work on a view. I'm able to get the count per cliente with : resultado = Pendente.objects.values('cliente').order_by('cliente').annotate(count=Count('id')) But this doesn't render the name of each customer on the template. On my template I'm using : <ul> {% for obj in resultado %} <li>{{ obj.cliente}} : {{ obj.count}}</li> {% endfor %} </ul> This is rendering: 6 : 2 35 : 1 40 : 1 92 : 1 106 : 1 105 : 1 is there a way to get the … -
django-compressor "Settings has no attribute"
I included django-compressor in version 2.4.1 to my django-project to compile scss-files. I followed the quickstart guide at https://django-compressor.readthedocs.io/en/stable/quickstart/ When I am now open the page where I included the css-file I got an error with regarding to this line {% compress css %} The error: 'Settings' object has no attribute 'COMPRESS_DEBUG_TOGGLE' When I add the value manually it comes to the next attribute which is not set and so on for all attributes. Regarding to the documentation the attributes should have a standard value. Why is my project not recognizing that there are default values set to the variables? -
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