Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
web socket in django showing error 10048
Listen failure: Couldn't listen on 127.0.0.1:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. -
Difference between urls.py and Response(routes)
In django, what is the difference between putting your urls in urls.py and using this: def getRoutes(requests): routes = [ # urls ] return Response(routes) -
Why does MQTT not connect to the server?
My purpose is to achieve MQTT message publish upon postsave signal sent my DJango models. I have registered on_connect, on disconnect, on_publish callbacks to check when the relevant process is executed. However, none of callbacks I registered works. Here is my post_save signal code. Can someone please give me a hint where I do mistake? import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("connecting") print("client:"+str(client)) print("userdata:"+str(userdata)) print("flags:"+str(flags)) print("result:"+str(rc)) global flag_connected flag_connected=1 def on_publish(client, userdata, mid): print("message published") def on_connect_fail(client, userdata, flags, rc): print("failed to connect") print("client:"+str(client)) print("userdata:"+str(userdata)) print("flags:"+str(flags)) print("result:"+str(rc)) global flag_connected flag_connected=0 def on_disconnect(client, userdata, rc): global flag_connected flag_connected = 0 def notify_windowsApp(sender,instance, **kwargs): new_truck_registered={ "identity":str(instance.truck_identity), "doorName":str(instance.registered_door.door_name), "doorNumber":str(instance.registered_door.door_number), "entryTag":str(instance.entry_tag), #"depatureTag":str(instance.departure_tag), "entrytime":instance.entry_time.strftime('%Y-%m-%d::%H-%M'), } sendToClient(new_truck_registered) def sendToClient(payloadTobeSent): client=mqtt.Client(client_id="django_post_save_signal", clean_session=True, ) mqttBroker="broker.hivemq.com" client.on_connect=on_connect client.on_publish=on_publish client.on_connect_fail=on_connect_fail client.on_disconnect=on_disconnect client.connect(mqttBroker) client.publish('baydoor/truckentrance',payload=str(payloadTobeSent),qos=1, retain=True) -
Django routing/pathing to multiply apps
Hi i know there is many of these asking about routing from a veiw to a new app in django. I have looked at a lot of them. And figured out to use app_name = 'name' and to use named routes for my html templates makes everything easier for sure. When i try to use a app_name:named-route i get this : ValueError at /recipedashboard The view recipeApp.views.dashboard didn't return an HttpResponse object. It returned None instead. I have gotten the name_app:named-route to send me to the second app, but how do i pass the session to the new app? userApp veiws: from django.shortcuts import render, redirect from django.contrib import messages from .models import User as LoggedUser # Create your views here. def index(request): return render(request, 'index.html') def register(request): if request.method == "GET": return redirect('/') errors = LoggedUser.objects.validate(request.POST) if len(errors) > 0: for er in errors.values(): messages.error(request, er) return redirect('/') else: new_user = LoggedUser.objects.register(request.POST) request.session['user_id'] = new_user.id messages.success(request, "You have successfully registered") return redirect('/success') def login(request): if request.method == "GET": return redirect('/') if not LoggedUser.objects.authenticate(request.POST['email'], request.POST['password']): messages.error(request, "Invalid Email/Password") return redirect('/') user = LoggedUser.objects.get(email=request.POST['email']) request.session['user_id'] = user.id messages.success(request, "You have successfully logged in!") return redirect('/success') def logout(request): request.session.clear() return redirect('/') def … -
DictQuery + Django + AJAX
My problem is simple, I had developed an application in DJANGO. I turn a CSV into JSON files but I have a format problem. <QueryDict: {'data': ['[{data }]']}> On the left, the ]} is not correct. The AJAX script is correct. The data send to JavaScript is properly. The format in JSON is ok on the JavaScript side but the Django side, there are this error in the format. How shoud I do to remove that ? Thanks a lot! -
'ManyToManyDescriptor' object has no attribute 'all' while accessing related_name
models.py 'ManyToManyDescriptor' object has no attribute 'all' when accessing related_name class Category(BaseModel): name = models.CharField(max_length=255, unique=True) class Record(BaseModel): categories = models.ManyToManyField(Category, related_name='records') query used Category.records.all() -
how to find top performing category in django without foreign key
models.py class Line_items(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey('Products' , on_delete=models.DO_NOTHING ) class Products(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=400 , blank=True) class Categories(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100 , blank=True) slug = models.CharField(max_length=200 , blank=True) class Product_Categories(models.Model): id = models.AutoField(primary_key=True) product_id = models.ForeignKey(Products, on_delete=models.DO_NOTHING) category_id = models.ForeignKey(Categories, on_delete=models.DO_NOTHING) here are my models. where line_items contains number of orders done till now. in line_items we have connect product id with product table. but we don't have any connetion from product table to category table. ( category table contains every category and their id ). to connect product table with category table we have created new table 'product_categories' which connects each category with their respective product. here what we want is top performing category. category which have highest number of products. thanks -
How to auto print in django
Hi I'm currently trying to build resturent pos app. So I want to know how can I print from printer when new order in placed from waiter site. There will be 3 user admin, kitchen, waiters Waiter can place order and kitchen will get the order and have the order print automatically. They both will be different devices. If so how can I set to auto print in kitchen site when waiter site place an order. Thank you in advance -
Django Query duplicated 2 times
I have a Project model class Project(models.Model) name = models.CharField(max_length=255) members = models.ManyToManyField(User, related_name="members") and I am using a classbased Update view to restrict only those users who are members of the project. class ProjectUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Project fields = ["name"] def test_func(self): members = self.get_object().members.all() if members.contains(self.request.user): return True return False After looking at the SQL queries through Djang Debug Toolbar, I see the query is duplicated 2 times. the 1st instance is from this test_func and the other instance is from django generic views, how can I resolve the duplicated query issue -
Store html in database in django
Hello I'm trying to store HTML code in the database with Django but facing a problem with escape characters. here's an object that I'm trying to store but { "data": "<div class=\"read\" id=\"search\">Google</div>" } here's what I'm getting in database. <div class="read" id="search">Google</div> I tried to store with Model.objects.create() this becomes a problem to parse too much HTML in javascript then. JSON object gets confused with the double-quotes. the solution is I want to store data in database with backslashes \ as well so it can be parsed correctly as a JSON object. -
Conditional rendering in radio button saves both vales in the state
I'm new to react, I have conditional rendering in radio button, lets say a ratio button has 2 options option1 and option2 on selection option1 the page shows up 2 text fields ( say first and last name ) on selection option2 the page shows up 2 buttons(saybtn1andbtn2`) if i select option1 and fill up first & last name and hit save, it saved and if i come back to this page, it shows last filled first & last name But later if I comeback and select option2, click on btn1 and hit save the state will hold first name, last name and option2 with btn1 pressed. after saving option2 if i click option1, i can still see the first & last name filled I have attached the sample code, all the fields are picked up from Django application - the issue is, every ratio button options has its on number of components nested. how do toggle all the nested values of non selected options to null or default when the alternative option of the radio button is selected. // Radio_button_field.js import React from "react"; import {Col, FormGroup, Input, Label, Row} from "reactstrap"; export default class RadioButtonField extends React.Component { … -
How can I get top 5 inventory items from a django model which has lowest quantity?
#This is my inventory model. I want to get the inventory items that have the lowest quantity in the model. class Inventory(models.Model): name = models.CharField(max_length=100) purchase_date = models.DateTimeField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.CharField(max_length=50) purchase_price = models.FloatField(max_length=50) selling_price = models.FloatField(max_length=50) description = models.CharField(max_length=100) location = models.ForeignKey(Locations, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) -
how django render function handles for loop ,how parse a "if" or "for"
{% for name, age in data.items %} Name: {{name}}, Age: {{age}} <br> {% endfor %} for loop in template,when render it,how does django know it is a for loop and show datas on html page. I know how to use "for loop" in template, and render template&content in view function,but I dont understand how django interprets it. How does the render function handle the for loop in html?I meand how implement it detailedly? I just read souce code from render function jump to this point:\python3.8\Lib\string.py for the self.pattern.sufunction just: @overload def sub(self, repl: AnyStr, string: AnyStr, count: int = ...) -> AnyStr: ... so how does django implement it ? -
Django, when trying to associate items to inventory as inline it raises migration error
Purpose: I want to make it possible to have inlines in inventory, so you can look up one specific user in the inventory model and modify their items. In "Items", I want to be able to make items. They have a name and a price. Simple. In "Inventory", I want to be able to make inventories, select a user (who owns it), and give them multiple items, using inlines. For the items, I want them to be independent: so if I make "Item 1", I want to be able to give "Item 1" to any inventory and I want them (the items) to be listed in the inventory, not in the items themselves. For example: Inventory | user | items | | -------- | -------------- | | user1 | item1,item2,item3 | | user2 | item2,item6,item78 | instead of: Item | belongs_to | item | | ------ | ------- | | user1 | item1 | | user1 | item2 | | user1 | item3 | | user2 | item2 | | user2 | item6 | | user2 | item78 | The error code: <class 'core.admin.ItemInline'>: (admin.E202) 'core.Item' has no ForeignKey to 'core.Inventory'. My code: models.py class Item(models.Model): name = models.CharField(max_length=32, blank=False, … -
How to display information from db on the one template along with forms in django using class view?
I would like to have information from db on the right side of the page. How to display it on template? What I could add in class based view in order to see it on the template? template {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm"> <form action="" method="POST"> <table> {{ form }} {% csrf_token %} </table> <input type="submit" class="btn btn-primary" value="Submit"> </form> </div> <div class="col-sm"> <div class="col-sm"> <h5>Problem:</h5> </div> </div> </div> </div> {% endblock content %} view class SolutionCreate(CreateView): model = Solution template_name = 'analysis/create_solution.html' fields = [ 'problem', 'research', 'solutions', 'resources', 'plan', 'test' ] def post(self, request, *args, **kwargs): form = SolutionForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/saved/') return render(request, self.template_name, {'form': form}) -
How to do unit testing and how it is different from integration testing in frameworks like Django and fastapi?
Let's say I have a Fastapi application like this (This code is taken from documentations): app = FastAPI() @app.get("/foo") async def read_main(): return {"msg": "Hello World"} I believe there are two ways of testing this view. The first one is by the use of a client object. For instance: client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"} However, I think this is not a unit test. It is more like an integration test. Because we are actually running fastapi codes as well. The second option which in my opinion is closer to unit test definition is to run the function directly: def test_read_main(): response = read_main() assert response == {"msg": "Hello World"} Similarly, in Django, we can directly call the view function, or by using a client object. My first question is which one is better? Let's say we chose one of them and now in order to prevent calling the database I have mocked the database. Now I want to test a view that just checks if something exists in the database. My second question is what is the point of testing such view? Becuase after mocking the database, … -
What is if 'admin' in request.path
I followed YouTube Django E-commerce video, I did exactly the same as the tutorial. But I found some difficulty in certain code. CONTEXT_PROCESSORS.PY from .models import cart,cartitem from .views import getcartid def counter(request): cart_counter=0 **if 'admin' in request.path:** return {} else: try: cart1=cart.objects.filter(cartid=getcartid(request)) cart_items=cartitem.objects.all().filter(basket=cart1[:1]) from 1 for cart_item in cart_items: cart_counter += cart_item.quantity except cart.DoesNotExist: cart_counter=0 return dict(cart_counter=cart_counter) Can someone explain for me what is if 'admin' in request.path, then return {}? -
How to serialize multiples objects from a Django model and add dynamically computed data in outputed JSON for each object?
I'm porting a Laravel PHP code to Python Django/Django Rest Framework. My endpoint will output JSON. I need to output many objects, but I need to add extra computed values for each object. How can I achieve this ? For example, my model is : from django.db import models from rest_framework.serializers import ModelSerializer class MyObject(models.Model): name = models.CharField(max_length=255) score = models.IntegerField() class MyObjectSerializer(ModelSerializer): class Meta: model = MyObject fields = ( 'name', 'score' ) I retrieve a queryset with MyObject.objects.all() (or with filter). For each MyObject in my queryset, I compute an extra value, called 'stats', that I want to output in my JSON output. For example, if I have 2 objects MyObject(name='foo',score='1') and MyObject(name='bar',score='2'), I will compute a stats value for each object. And my JSON output should be like : { { 'name': 'foo', 'score': 1, 'stats': 1.2 }, { 'name': 'bar', 'score': 2, 'stats': 1.3 }, } What is the cleanest way , if any to achieve this ? I can have a loop for each MyObject, serialize each MyObject, one by one with a serializer, and create and update dictionary for this object adding 'stats' key. I'm afaid about performance. What if I compute stats value … -
how to get bulk object values through foreign key in django
i have models class Orders(models.Model): id = models.AutoField(primary_key=True) date_created = models.DateField(blank=True) date_modified_gmt = models.DateField(blank=True) class Line_items(models.Model): id = models.AutoField(primary_key=True) order = models.ForeignKey('Orders' , on_delete=models.DO_NOTHING , blank = True , null = True ) so here what i am trying to do is that i am getting list of orders between two dates - startdate , enddate. views.py orders = orders_model.objects.filter(date_created__gte=f'{startdate}', date_created__lte=f'{enddate}' ) now i want line_items which have same order id which is i am fetching between two dates. example i am fetching data between two dates lets suppose 20-04-2022 , 21-04-2022 now i get two entries of order data which are placed between these two dates. lets say order-id: ( 234 , 235 ) now i want list of line items who have these order id in order column in line_items table ( Note please django orm ) thanks -
How can I populate a Django ChoiceField with attributes of an object?
I have a Election and Candidate object model like so: class Election(models.Model): id = models.IntegerField(primary_key=True, unique=True) name = models.CharField(max_length=80) region = models.CharField(max_length=80) candidates_count = models.IntegerField() total_votes_cast = models.IntegerField() def __str__(self): return self.name class Candidate(models.Model): id = models.IntegerField(primary_key=True, unique=True) name = models.CharField(max_length=80) party = models.CharField(max_length=80) election_id = models.IntegerField() vote_count = models.IntegerField() def __str__(self): return self.name I have a form to create a new candidate, like so: class AddNewCandidateForm(forms.Form): PARTY_CHOICES = [ (1, "Party 1"), (2, "Party 2"), (3, "Party 3"), (4, "Party 4"), (5, "Party 5"), (6, "Other") ] candidate_name = forms.CharField( max_length=80, required=True, label='Candidate Name' ) candidate_party = forms.ChoiceField( label='This candidates party', required=True, widget=forms.Select(), choices=PARTY_CHOICES ) candidate_election = forms.ChoiceField( label="The election that this candidate is participating in", required=True, widget=forms.Select() ) I want to populate the candidate_election ChoiceField with the name attribute of all of existing Election objects in the database. What is the best way to do this? I'm struggling with ways to figure out how to make a 2-tuple for the ChoiceField to accept. Thanks! -
How can I use for loop in HTML to display data in a table with format
So I'm a beginner and I'm using django and python. I created a table here and I want to display all data in a queryset. Plus I want to have 4 columns. So I want something like, for each four items in the queryset, create a and display the 4 items, but it seems like I can only do one item in each loop. My code looks like this, and it's dipslaying one each row right now. Code for the table Is it possible to do this in html? -
How to solve this error "django.db.migrations.exceptions.InconsistentMigrationHistory" when running python manage.py migrate
I have implemented a CustomUser model on users app in django. class CustomUser(AbstractUser): username = None email = models.EmailField('email address', unique=True) first_name = models.CharField('First Name', max_length=255, blank=True, null=False) last_name = models.CharField('Last Name', max_length=255, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return f"{self.first_name} {self.last_name}" And then when running "python manage.py migrate", I got this error "django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'." -
coding SerializerFactory Django
I have a Django App using Django RFM. And I Have 10 Serializers, 10 Models, 10 Views and 10 Urls. All Everything works well, but I want optim this because on my Views nothing changes, except the name of the Serializer. So, how can I generalize the views so that depending on the URL, Django fetches the right Serializer and uses it in the views. Eventually, I'd like to have just one view that fetches the Serializer automatically ? I Hope it's possible.. Namely, I use Django with React implemented -
Occasional "could not translate host error" in Postgres, Django and Docker Swarm set up
I have a stack with two nodes, only one manager in Docker Swarm, one replica of db on the manager and 3 replicas of the web (Django backend). Occasionally I get this error in the logs of my web container psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known /usr/local/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Name or service not known When I was building this locally, i got this error for example after rebooting my machine, but then i just docker-compose down and up again and it disappeared. (I never got another solution for this). However now in my swarm stack I do not have a workaround. I don't know what exactly is causing this, I've tried everything I could find, changing the SQL_HOST to localhost, putting the stack name in front of the service: stack_db, adding POSTGRES_HOST_AUTH_METHOD=trust to the db environment, adding the web and the db in the same network, changing the postgres image to postgres:13.4-alpine, adding a depends_on rule for which I use a script with my deploy command (I also parse it with docker-compose … -
Passenger error in Django cPanel web application
Getting error when trying to deploy website. Setup: CloudLinux Cpanel Application Manager (Phusion Passenger) - Development = True Python 3.8 venv Django + Django Rest Framework - Debug = True The Phusion Passenger(R) application server tried to start the web application. But the application itself (and not Passenger) encountered an internal error. I have included the seetings.py & wsgi.py files for reference. Error received: error: cannot open Packages database in /var/lib/rpm Traceback (most recent call last): File "/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home2/fpicsnp/fpic_resources/passenger_wsgi.py", line 1, in <module> from fpic_resources.wsgi import application File "/home2/fpicsnp/fpic_resources/fpic_resources/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi Settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'b=+eif_^duy#xz6c1%*g%)7r4dl*$)o&3yo0$th_u+ntbz)vui' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['fpic.snpolytechnic.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', …