Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem to load the Css on a Django application deployed in Vercel
I've created an application in django, but when I deployed it in Vercel, the HTML works just fine, but the CSS don't load. I pasted some of my project below, please ask me if you need any other files to make the necessary changes. Project Structure C:. │ .gitignore │ db.sqlite3 │ manage.py │ README.md │ requirements.txt │ vercel.json │ ├───.mypy_cache │ │ .gitignore │ │ CACHEDIR.TAG │ │ │ └───3.11 │ │ @plugins_snapshot.json │ │ abc.data.json │ │ abc.meta.json │ │ builtins.data.json │ │ builtins.meta.json │ │ codecs.data.json │ │ codecs.meta.json │ │ contextlib.data.json │ │ contextlib.meta.json │ │ dataclasses.data.json │ │ dataclasses.meta.json │ │ enum.data.json │ │ enum.meta.json │ │ genericpath.data.json │ │ genericpath.meta.json │ │ io.data.json │ │ io.meta.json │ │ manage.data.json │ │ manage.meta.json │ │ ntpath.data.json │ │ ntpath.meta.json │ │ pathlib.data.json │ │ pathlib.meta.json │ │ posixpath.data.json │ │ posixpath.meta.json │ │ re.data.json │ │ re.meta.json │ │ sre_compile.data.json │ │ sre_compile.meta.json │ │ sre_constants.data.json │ │ sre_constants.meta.json │ │ sre_parse.data.json │ │ sre_parse.meta.json │ │ subprocess.data.json │ │ subprocess.meta.json │ │ sys.data.json │ │ sys.meta.json │ │ types.data.json │ │ types.meta.json │ │ typing.data.json │ │ typing.meta.json │ │ typing_extensions.data.json │ │ typing_extensions.meta.json … -
Need to add fields of another serializer to the serializer. I pass only id and amount, and json should return in response
There is a recipe serializer that needs to receive ingredients, which is also handled by another serializer. The recipe and ingredient models are connected through a Many-to-Many relationship. Only the ingredient's ID and quantity need to be passed, and that's what I receive in response. { "ingredients": [ "Invalid type. The primary key value was expected, dict was received." ] } I need to somehow override the create method differently. # serializers.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ('id', 'name', 'measurement_unit') class RecipeCreateSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) author = UserSerializer ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all() ) image = Base64ImageField() class Meta: model = Recipe fields = '__all__' read_only_fields = ('author',) def create(self, validated_data): tags = validated_data.pop('tags') ingredients = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) for tag in tags: current_tag, status = Tag.objects.get_or_create(**tag) TagsInRecipe.objects.create(tag=current_tag, recipe=recipe) for ingredient in ingredients: current_ingredient, status = Ingredient.objects.get_or_create(**ingredient) IngredientsInRecipe.objects.create( ingredient=current_ingredient, recipe=recipe, amount=ingredient['amount'] ) return recipe expected { "id": 0, "tags": [ {} ], "author": { "email": "user@example.com", "id": 0, "username": "string", "first_name": "Name", "last_name": "Last Name", "is_subscribed": false }, "ingredients": [ { "id": 0, "name": "potato", "measurement_unit": "g", "amount": 1 } ], "is_favorited": true, "is_in_shopping_cart": true, "name": "string", "image": "http://example.org/media/recipes/images/image.jpeg", "text": "string", "cooking_time": … -
Python Protocols and Django Models
Suppose I have a simple protocol A and a class B which fails to implement that protocol: from typing import Protocol class A(Protocol): def foo(self) -> str: ... class B: pass Mypy will correctly complain when the code below is type checked x: A = B() mypy . error: Incompatible types in assignment (expression has type "B", variable has type "A") If however I have it so that B inherits from django.db.models.Model as follows class A(Protocol): def foo(self) -> str: ... class B(models.Model): pass x: A = B() mypy no longer throws an error when checking the line x: A = B(). I would have expected it to throw an error since B does not (seemingly) implement the A protocol. I assume this must have something to do with some inherited properties of models.Model which makes mypy think that the foo method is there. Does anyone know what's going on here and have advice on how to have mypy check whether or not a Django model implements a protocol? Note that I would prefer that the model did not need to explicitly subclass the protocol. -
CSS styling not displayed when deployed to Vercel
Im making a Django app that displays a users top tracks and artists, when i deploy this app to vercel i lose all my css styling. Im new to django and developing apps any help would be appreciated! This is my repo: https://github.com/KevinL0206/spotify_stats_project Vercel Site:https://spotify-stats-project.vercel.app/ -
Adding fields to a form and a model dynamically in django
Lets say we have a model called SimpleModel and it has an attr connected_field which is ForeignKey of NotSimpleModel i.e. class SimpleModel(models.Model): connected_field = models.ForeignKey('NotSimpleModel', on_delete=models.CASCADE, related_name='connected') class NotSimpleModel(models.Model): ... and we have a form called NotSimpleForm class NotSimpleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... class Meta: model = NotSimpleModel fields = '__all__' Well, actually i wanna do a thing where user can dynamically add "connected_field" in the form which is ModelForm of NotSimpleModel, then all the fields, which user added dynamically should be sent to the view and saved to the db (i doesnt insist on ForeignKey, but i guess it gotta be the easiest way to solve it tho) -
changes to my github contributions not showing on my graph
Initial repositories count as contributions on my graph but follow up changes do not reflect on my graph however they indicate on my code that modification has been done on GitHub. I have enabled both private and public repository viewing and I ensure I make changes to the same branch in which I committed but still the problem persists. any help would be very much appreciated . Thank you in Advance. i tried creating a new branch and comiting to it but still the changes would not reflect on the graph -
TypeError at /admin/accounts/order/add/ (__str__ returned non-string (type Customer))
I wanted to use many to many and many to one with Django. Then I write this codes but when I try to add an Order from Admin Panel I got this error and I cannot find the solution. I hope someone can help me. In the below I share my models.py file I hope it will enough. from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) email = models.EmailField(null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name=models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): STATUS = ( ('Indoor','Indoor'), ('Out Door', 'Out Door') ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True,choices=STATUS) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending','Pending'), ('Out for deliver', 'Out for delivery'), ('Delivered', 'Delivered') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.customer I'm watching Dennis Ivy's Django Crash Course Tutorials and I did exactly what he did but he didn't get this error and I wonder what's the problem more than the solution. I … -
Share Docker image via Container Registry - DRF API
I prepared API with Django Rest Framework. I am using docker to run my API, everything works fine on my machine. So I just run docker-compose up and I can test API with Swagger in my browser. Now I want my friend to test it locally on his machine. I want to do this by sharing my docker image with Container Registry (GitLab service) and docker-compose file. So his scenario will be: Pulling repo from Registry Container by: docker pull registry.[...] Run: docker-compose up And after that, he can test it. The main goal is to run this API without downloading repo with code - just using docker-compose and Docker image. We then want to run it on VPS. I have already tried to do this but to no avail. Here are the steps I followed: docker login registry.gitlab.com docker build -t registry.gitlab.com/[...]:latest . docker push registry.gitlab.com/[...]:latest . Remove all images and containers related to project. Create new directory and paste there docker-compose file. docker pull registry.gitlab.com/[...]:latest . docker-compose up And then I'm getting error: python: can't open file '/app/manage.py': [Errno 2] No such file or directory What can I do in that situation? Is it even possible to work? … -
Django template dynamically add rows and colums does not work
I'm displaying blog list looping through the list in django and the blogs are displayed 3 columns in a row and the rows and columns are dynamically added but it doesn't work yet. <div class="container"> {% for post in post_list %} {% if forloop.counter0|divisibleby:3 %} <div class="row py-5"> {% endif %} <div class="col-md-4 mb-5 pb-5"> <div class="card blog-card my-5"> {% if post.image %} <img src="{{ post.image.url }}" class="card-img-top" alt="Blog Post Image"> {% endif %} <div class="blog-card-text"> <div> <img src="{% static 'blog/images/logo.png' %}" alt="MMDT logo" class="blog-created-img"> <small>{{ post.created_on }}</small> </div> <div class="card-title mb-0"> <h6 class="font-weight-bold">{{ post.title}}</h6> </div> <div class="card-text"> <small>{{ post.author }} | {{ post.view_count }}</small> </div> <div class="card-text"> {{ post.content|slice:":120" | striptags }} <span>...</span> <a href="{% url 'post_detail' post.slug %}" class="mt-0 mb-3"> Read More </a> </div> </div> </div> </div> {% if forloop.counter|divisibleby:3 or forloop.last %} </div> {% endif %} {% endfor %} </div> Any idea to fix this and thanks in advance. -
How to setup azure communication services (email) with django
I'm working on a django project where I want to send emails for account creation. Particularly, I am using djoser. I want to integrate azure communication services and their email service to send emails but I don't know how to do that. Can someone tell me how to use azure communication services in django and djoser. I tried using the endpoint connection string and access keys as password but it did not work. -
How do depoy a Django Project on a Webgo server
im new to Django i did made a tutorial from w3school, now im at the point to deploy the project but i dont want to deploy the project on my own webhost at Webgo. On the Server there is python and modWSGI. But all tutorial i had read they there realy complicated to deploy a project. Can somebody help me to deploy my project on that webserver its running with apache. I tried to upload the Project but that was not enought im not sure what to do. The docs are a bit to complicated for me. Thats why i hope sombody can descripe me the approach so a newbie can understand that. I uploaded my project but its not working -
Book a specific appointment on a specific day
I want to book a specific time for the user (start hour and end hour ) and no one else can book at the same time Example Like : John made an appointment on the 5th day of the month at 7 to 8 o'clock i want no one else can booking at the same time and day and i want to check the Period because if someone like john booking start time 5pm to 8pm no one can booking like stat 6pm to 7 pm at the same day How I can Do This in Models Django I could not find a solution to this problem enter image description here im using timing to know how long the booking take and i dont know what can i should do enter the link tow show the image of code -
How can I make the queryset filter `or` conditions dynamically from the array?
I have array and try to use this as filter key for database I want to make this dynamically from the array = [AC" ,"BC"] queryset = queryset.filter(Q(username__icontains="AC")| Q(username__icontains="BC")) For example, I try like this below but it is obviously wrong. array = ["AC","BC"] qs = [] for k in array: qs.append(Q(username__icontains=k)) queryset = queryset.filter(qs.join('|')) How can I do this ? -
Django + Celery + Redis
I have this settings in my social_media.settings: CELERY_BROKER_URL = "redis://0.0.0.0:6379/0" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_BACKEND = "redis://0.0.0.0:6379/0" CELERY_TIMEZONE = "Europe/Kiev" Also I register in my social_media.init: from .celery import app as celery_app __all__ = ("celery_app", ) Also I have this celery.py file: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social_media.settings") app = Celery("social_media") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() And I run redis with docker command: docker run -d -p 6379:6379 redis So after I run my django project and my docker, I want to run celery with this command: celery -A social_media worker -l info I get this error: Traceback (most recent call last): File "C:\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "D:\projects\social-media-api\venv\Scripts\celery.exe\__main__.py", line 7, in <module> File "d:\projects\social-media-api\venv\lib\site-packages\celery\__main__.py", line 15, in main sys.exit(_main()) File "d:\projects\social-media-api\venv\lib\site-packages\celery\bin\celery.py", line 236, in main return celery(auto_envvar_prefix="CELERY") File "d:\projects\social-media-api\venv\lib\site-packages\click\core.py", line 1157, in __call__ return self.main(*args, **kwargs) File "d:\projects\social-media-api\venv\lib\site-packages\click\core.py", line 1078, in main rv = self.invoke(ctx) File "d:\projects\social-media-api\venv\lib\site-packages\click\core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "d:\projects\social-media-api\venv\lib\site-packages\click\core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) File "d:\projects\social-media-api\venv\lib\site-packages\click\core.py", line 783, in invoke return __callback(*args, **kwargs) File "d:\projects\social-media-api\venv\lib\site-packages\click\decorators.py", line 33, in new_func return f(get_current_context(), *args, **kwargs) … -
Deleting image related to a product from static folder when deleting product. Django
I have a model: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() is_digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self) -> str: return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url I want to delete the related image to this product when product deleted(for example from admin page). I searched and found out that overriding del or delete functions are not the correct way to do that. Can you please help me. And I also wonder if it's even good logic to deleting unecessery files from static folder. -
'Settings' object has no attribute 'EMAIL_HOST_USESR'
I wanna send email by django and gmail smtp and I see this error. the code below is my email setting EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'MY EMAIL' EMAIL_HOST_PASSWORD = 'MY PASSWORD' EMAIL_PORT = 587 i expect to send email without any problems -
Django Query: Annotating queryset list with Sum of fields Values
I have 3 simple models: from django_better_admin_arrayfield.models.fields import ArrayField class Skill(BaseModel): value = models.IntegerField() item = models.ForeignKey(Item, on_delete=models.CASCADE related_name="skills") class Item(BaseModel): name = models.CharField(max_length=100) class BuildItem(models.Model): base = models.ForeignKey(Item, on_delete=models.CASCADE) mandatory_skills = ArrayField(models.IntegerField(null=True, blank=True), default=list) I would like to have a list of BuildItem annotated with the sums of the value field of the Skill table, only if the Skill id is contained in the mandatory_skills field. To annotate the list of BuildItem I have the following query which works: q = BuildItem.objects.annotate(sum_skill=Coalesce(Sum("base__skills__value"), 0)) I would also like to add up the Skills having an id present in mandatory_skills. I tried many things but without success, does anyone have a solution? -
Django admin page showing PATH module not found
I am trying to access: http://127.0.0.1:8000/admin/login/?next=/admin/ but I am shown with this error: ''' ModuleNotFoundError at /admin/login/ No module named 'path' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.2.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'path' Exception Location: , line 1004, in _find_and_load_unlocked Raised during: django.contrib.admin.sites.login Python Executable: C:\Program Files\Python310\python.exe Python Version: 3.10.6 Python Path: ['C:\Users\ROHIT\Documents\Project\hospital2\hospital_project', 'C:\Program Files\Python310\python310.zip', 'C:\Program Files\Python310\DLLs', 'C:\Program Files\Python310\lib', 'C:\Program Files\Python310', 'C:\Users\ROHIT\AppData\Roaming\Python\Python310\site-packages', 'C:\Users\ROHIT\AppData\Roaming\Python\Python310\site-packages\win32', 'C:\Users\ROHIT\AppData\Roaming\Python\Python310\site-packages\win32\lib', 'C:\Users\ROHIT\AppData\Roaming\Python\Python310\site-packages\Pythonwin', 'C:\Program Files\Python310\lib\site-packages'] Server time: Sun, 10 Sep 2023 08:21:55 +0000 ''' I have included from django.urls import path in all the urls.py -
How can I get the data used as key for group by
id num tuser 1 2 user1 2 2 user2 3 3 user2 4 1 user4 5 1 user4 For example I have table like this . Now I want to get the unique data appeared in tuser so, the result should be user1,user2,user4 I guess it should be related with group by. So, I made this sentence. p = m.MyTables.objects.all().values('tuser') However how can I get the user1,user2,user4 ? -
vscode's testing interface does not work properly with django
unittest does not create a test database and runs on the production database. `"python.testing.unittestEnabled": true,` pytest creates a test database but fails with psycopg2.errors.DuplicateDatabase, if the database was not manually deleted. `"python.testing.pytestEnabled": false,` Both also don't seem to run django manage.py command since: the test runner does not execute TEST_RUNNER = 'test.test.test'. the overridden test Command class does not run either. "python.testing.pytestArgs": [ "-v", "./app1/tests.py", "./app2/tests.py", ], "python.testing.unittestArgs": [ "-v", "-s", ".", "-p", "tests.py" ], Note that the following launch command in launch.json works 100% properly (test runner and command execute) and all tests run and pass correctly but I would like to use the vscode testing interface. { "name": "Test", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "test", "-v" ], "envFile": "${workspaceFolder}/.env", "django": true, "justMyCode": false, }, -
Install django-ads-txt causing ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
Hi I trying to Install django-ads-txt to my Django Project. My first step was to pip install django-ads-txt then I added in the urls path('ads.txt', include('ads_txt.urls')), when I tried to python manage.py migrate I got the following error: from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' I tried to pip install six but the same error kept showing My question: How to fix this error to install django-ads-txt? -
it shows OS error if i try to open the links
i am making a webpage which looks like this using django : the webpage while opening the links , it shows OS error : [Errno 22] Invalid argument: 'C:\Users\Lenovo\Desktop\django projects\env\Lib\site-packages\django\contrib\admin\templates\home\ran_num_gen.html' i am unable to find out the cause of it. help me understand more about it . following is the relevant code and screenshots : DIRECTORIES **views.py **: from django.shortcuts import render from django.template.context import Context # Create your views here. def home(request): return render(request , 'home\home.html' ) def num_guess_game(request): return render (request ,'home\num_guess_game.html') def ran_num_gen(request): return render (request ,'home\ran_num_gen.html') def ran_pwd_gen(request): return render (request ,'home\ran_pwd_gen.html') urls.py : """ URL configuration for core project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from home.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', home ,name='home'), path('ran_num_gen/', ran_num_gen … -
ModuleNotFoundError: No module named 'django' (deploying on Heroku)
I ran into an error when running the command: heroku run python manage.py migrate. When I run it it raises en error: ModuleNotFoundError: No module named 'django'. My app runs fine locally. Django is installed. I tried to search the internet but I see the answers for the errors with the module "django-heroku", not just "django". If anyone has any suggestions, I would be grateful! -
TypeError "Cannot filter a query once a slice has been taken." while running self.client.get(reverse()) function in django
I'm currently learning some basics of django using tutorials in documentation (https://docs.djangoproject.com/en/4.2/intro/tutorial05/) and have a problem with chapter about testing. class QuestionDetailViewTests(TestCase): def test_past_question(self): question = create_question('text', -30) response = self.client.get(reverse('polls:detail', args=(question.id,))) self.assertContains(response, question.question_text) create_question is just a shortcut for creating Question(models.Model) object with second argument meaning offset in days for publication date, which is set relatively to current date. 'polls:detail' is the name of path to this concrete view, which takes number of question as argument. Running of py manage.py test app results in following error: Traceback (most recent call last): File "C:\web\django\project1\mysite\polls\tests.py", line 59, in test_past_question response = self.client.get(reverse('polls:detail', args=(question.id,))) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 927, in get response = super().get(path, data=data, secure=secure, headers=headers, **extra) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 457, in get return self.generic( File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 609, in generic return self.request(**r) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 891, in request self.check_exception(response) File "C:\web\django\project1\lib\site-packages\django\test\client.py", line 738, in check_exception raise exc_value File "C:\web\django\project1\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\web\django\project1\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\web\django\project1\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\web\django\project1\lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "C:\web\django\project1\lib\site-packages\django\views\generic\detail.py", line 108, in get self.object = self.get_object() File "C:\web\django\project1\lib\site-packages\django\views\generic\detail.py", line 37, in … -
Django's Success messages displayed like error messages
I'm working on a Django project and I'm using Django's built-in messaging framework to display success and error messages to the user. However, I'm encountering an issue where success messages are being displayed in a way that makes them look like error messages.error messages displyed like success messages here is my Html code: {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="rounded border-s-4 mb-1 border-green-500 bg-emerald-50 p-4"> <strong class="block font-medium text-green-800"> Successfully </strong> <p class="mt-2 text-sm text-green-700"> {{ message }} </p> </div> {% else%} <div class="rounded border-s-4 mb-1 border-red-500 bg-red-50 p-4"> <strong class="block font-medium text-red-800"> Something went wrong </strong> <p class="mt-2 text-sm text-red-700"> {{ message }} </p> </div> {% endif %} {% endfor %} {% endif %} here is example enter image description here