Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', … -
Queue in django/python
I have developed a django REST API. I send request/data to it to perfrom a task and it does it nicely. Though, In a way, I can send it multiple request/data to perfrom the task on each of them. The issue is that server where the task gets performed has limited memory and I need to perform these task one by one. So, I am thinking to have a queue system at django pipeline which can maintain the reqeust on hold till the task in front of the queue is done. I am not sure if I am on right path, but not sure if celery is the option to solve my issue? It seems a simple task and I didnt understand if celery is what i need. Can you point me what should be looking at? -
How to send scheduled email with Crontab in Django
I like to send scheduled emails in Django with Crontab. I made a very simple app to test how can I send an email in every minutes (just for testing purposes). I think I am doing something wrong, because I can't get the mails. users/cron.py from django.core.mail import send_mail def my_scheduled_job(): send_mail( 'subject', 'Here is the message.', 'something@example.com', ['me@gmail.com'], fail_silently=False, ) print('Successfully sent') settings.py CRONJOBS = [ ('*/1 * * * *', 'users.cron.my_scheduled_job') ] I added the job like this: python3 manage.py crontab add then python3 manage.py runserver My mailing server configured fine, every other emails are sent, but I can't get these emails, nothing happens. I don't like to use Celery or Django Q. -
how update MQTT data in django template
I'm using paho-MQTT and I can receive messages and I can display the data in a template(html), but I can't update the message in realtime in the template(html). I want to update the value in the template when I get a new message from the mosquitto/topic. from django.shortcuts import render import paho.mqtt.client as mqtt import json valor_mqtt = 0 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("mhub/hr") def on_message(client, userdata, msg): global valor_mqtt valor_mqtt = (msg.payload) print(valor_mqtt) def print_on_m(request): global valor_mqtt message = str(valor_mqtt) return render(request, 'home/index.html',{'context':message}) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("mqtt.eclipseprojects.io", 1883, 60) I'm passing print_on_m in urls.py to use {{context}} in home/index.html to show the data PS: I don't want to use functions like "setInterval(function() {" or ".load(window.location.href" to update part of the web page after some time, I want to update only when I get new message from mosquitto/topic -
Get_queryset() missing 1 required positional argument: 'request' when i'm trying to filter objects by logged in user
I'm trying to list all facilties owned by a user on a "facility list page" using the django rest framework and react. I tried the following to make this happen (admin_uid is a one to one field of the user owning the facility): class FacilityListView(ListAPIView): permission_classes = [AllowAny] serializer_class = FacilitySerializer def get_queryset(self, request): return Facility.objects.filter(admin_uid=self.request.user) I'm getting this error: django | queryset = self.filter_queryset(self.get_queryset()) django | TypeError: get_queryset() missing 1 required positional argument: 'request' This is what i had before which worked but listed all facilities: class FacilityListView(ListAPIView): permission_classes = [AllowAny] serializer_class = FacilitySerializer def get_queryset(self): return Facility.objects.all() -
Why Django doesn't have an on_update=models.CASCADE option?
My question comes from a situation where I want to emulate the ON UPDATE CASCADE in SQL (when I update an id and I have a Foreignkey, it is going to be automatically updated) in Django, but I realized that (apparently) doesn't exist a native way to do it. I have visited this old question where he is trying to do the same. My question is: Why Django doesn't have a native option? Is that a bad practice? If so, why? Does that bring problems to my software or structure? Is there a simple way to do this? Thanks in advance! -
How to use custom labels from Django models.Choices field together with enum.auto?
Before Django v3.0 I used to use enum.Enum together with enum.auto (see reference) for my choices fields. The reason was mostly so I could use my enumeration class for type hints and the auto enforced the usage of the enumeration class instead of instead of using the constant value in code. However Django v3.0+ introduced the enumeration types which is similar to the enum module but with some interesting features. I'd like to use it together with enum.auto but wasn't able so far. The further I got was to something like this: class MyChoices(models.IntegerChoices, Enum): FIRST = auto() SECOND = auto() THIRD = auto() The enumeration values and the auto-generated labels are correct: MyChoices Out[13]: <enum 'MyChoices'> MyChoices.choices Out[14]: [(1, 'First'), (2, 'Second'), (3, 'Third')] MyChoices.labels Out[15]: ['First', 'Second', 'Third'] MyChoices.values Out[16]: [1, 2, 3] MyChoices.FIRST Out[17]: <MyChoices.FIRST: 1> The issue is when I try to define custom labels: class MyChoices(models.IntegerChoices, Enum): FIRST = auto(), '1st' SECOND = auto(), '2nd' THIRD = auto(), '3rd' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3441, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-20-cf882f261e5f>", line 1, in <module> class MyChoices(models.IntegerChoices, Enum): File "/usr/local/lib/python3.8/site-packages/django/db/models/enums.py", line 28, in __new__ cls = super().__new__(metacls, classname, bases, classdict, **kwds) … -
Django 3.2 view fails when filtering on Boolean field
I'm currently upgrading a Django project from 2.2 to 3.2, but I'm getting an error from SQL Server when trying to load a View: ProgrammingError at /my/django/url ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW)") I have a queryset that is filtering on a Boolean Field ('islead'), the queryset contains .filter(islead=True), however when I load the View, I can see from Django debug toolbar that the SQL query doesn't include "WHERE islead = TRUE", it only has "WHERE islead" with no condition. This works fine in Django 2.2. Here is an extract of my code: models.py: class LecturerCourseYear(models.Model): ay = models.IntegerField(db_column='AY', primary_key=True) code = models.CharField(db_column='Code', max_length=12) lecturer = models.ForeignKey('Lecturers', models.DO_NOTHING, db_column='lecturer', max_length=12) islead = models.BooleanField(db_column='IsLead') views.py: def edit_course(request, code, ay): primary_lecturer_response = LecturerCourseYear.objects.filter(ay=ay, code=code, islead=True).order_by('position') initialData = {'primary_lecturer': ','.join([lecturer.lecturer.id for lecturer in primary_lecturer_response]), form = editCourseForm(initial=initialData) return render(request, 'courses/edit-course.html', {'form': form}) -
Django S3 file to InMemoryUploadedFile
There is a way to convert or use S3 file as a InMemoryUploadedFile : For example i want to get my file from S3 using storage : image = default_storage.open('example.png', 'r') Then convert it to an InMemoryUploadedFile in order to use it in my Serializer : image_temp = InMemoryUploadedFile(image, 'image_example', 'example.png', 'png', None, None) Thanks. -
Integration of paypal with android app using django
how create Paypal payment gateway for an app which used a volley and has Django on server-side . i need views.py for an app on server-side and full source code. -
Celery issue in a kubernetes pod
While trying to create a super user for this application using manage.py I am getting the following error. root@taiga-back-675fcdbd67-rx552:/taiga-back# ./manage.py createsuperuser Username: testuser Email address: testuser@abc.com Password: Password (again): Traceback (most recent call last): File "/opt/venv/lib/python3.7/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/venv/lib/python3.7/site-packages/amqp/transport.py", line 173, in _connect host, port, family, socket.SOCK_STREAM, SOL_TCP) File "/usr/local/lib/python3.7/socket.py", line 752, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -5] No address associated with hostname This is the CELERY Configuration. Sorry, it's Nano This application running as a pod in a Kubernetes cluster. I searched for this but could not find anything meaningful to begin troubleshooting. Any hints/answer would help. -
Django. How can i bypass a form page, right after login if the user already completed it
I have a sign up form which does the user registration part and after that u are prompted to the login page. After you login, you are prompted to another form which gathers additional info about the user. How can i bypass this form if the user already completed it ? -
Django Makemigrations No changed detected
app/models: from django.db import models # Create your models here. class Blogpost(models.Model): topic = models.TextField(null=True) descrip = models.TextField() fd = models.CharField(max_length=150) ->I installed app already INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.SbuiltConfig', 'rest_framework', ] ->I Register models already from django.contrib import admin from models import Blogpost, Blog, testblog # Register your models here. admin.site.register(Blogpost) but it's still no change detected