Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show Django static file on windows 10 IIS
I'm trying to deploy Django app on windows 10 iis my app is working fine but Django static file not serve. Here my setting which is I'm configure on windows 10 IIS Server **Web config ** <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="E:\django\crm\crm\crm" /> <add key="DJANGO_SETTINGS_MODULE" value="crm.settings" /> </appSettings> <system.webServer> <handlers> <remove name="crm" /> <add name="crm" path="*" verb="*" modules="FastCgiModule" scriptProcessor="E:\django\crm\crm\crm\env\Scripts\python.exe|E:\django\crm\crm\crm\env\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </configuration> Add Website FASTCGI Setting Handler Mapping Setting Py """ Django settings for crm project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d)et0_8*dvb(x9fytai2_2zz(*37vfm*1617*8ajyftycu@a49' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.11.59','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'dbbackup', ] DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': BASE_DIR / 'backup'} MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
The current path, admin/, didn’t match any of these
My django project does not find the admin path, when I try to access it. My project URLs are as follow: from myapp.views import UserView from django.contrib import admin urlpatterns = UrlPattern() urlpatterns.register(UserView) urlpatterns += [path('', include('myapp.urls'))] urlpatterns += [path('admin/', admin.site.urls)] the error I get when try to access: 127.0.0.1:8000/admin/ The current path, admin/, didn’t match any of these. -
Django stuck after doing code change (hot reload not working)
I upgraded my Django version from 3.2.15 to 4.2.1 and also my Python version from 3.7.13 to 3.11.0 and the hot reload of my Django project stopped working. The server starts as expected with the pipenv run python src/manage.py runserver {host}:{port} command, but when I do a code change and save the file the server gets stuck saying: [INFO] [django]: /my-route/my-file.py changed, reloading And I have to kill the process on the console and start it again to make it work. When I had my old dependencies, after saving a file the server just reloaded and it showed the changes. I tried to set the verbosity to 3, but I can't get any information explaining the error and I don't know how to debug it. It looks like it uses StatReloader to detect this file changes: [INFO] [django]: Watching for file changes with StatReloader gets printed before starting the server. I would really appreciate it if you can give me some help or direction to follow about this topic. Thanks in advance! -
Foreign key issue : (3780, "Referencing column 'user_id' and referenced column 'id' in foreign key constraint)
In my django website I have a user model : from django.contrib.auth.models import AbstractUser class User(AbstractUser): class Meta: app_label = "myapp" The issue is when I try to create a simple other model referencing to the User model : class TestTable(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) value = models.FloatField() I get this error when trying to migrate after makemigrations : (3780, "Referencing column 'user_id' and referenced column 'id' in foreign key constraint I think the issue is about the type of the "id" in user table and "user_id" in test table, when I describe the tables with SQL commands I get this : mysql> describe myapp_user; +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | password | varchar(128) | NO | | NULL | | | last_login | datetime(6) | YES | | NULL | | | is_superuser | tinyint(1) | NO | | NULL | | | username | varchar(150) | NO | UNI | NULL | | | first_name | varchar(150) | NO | | NULL | | | last_name | varchar(150) | NO | | NULL | | … -
Django Email Incorrect Accent Characters
I'm facing an issue with sending emails using Django where the accent characters are not rendered correctly. ** Problem:** When I send an email containing accent characters (e.g., é, à, ü), they SOMETIMES appear incorrectly in the received email. Instead of the correct character, I see a different symbol/letter. I'm using Django, in particular Celery do send the emails. Here is my code: Template: {% extends 'general/mail_header_and_footer.html' %} {% load settings %} {% load i18n %} {% block title %}{{ title }}{% endblock %} {% block description %} <p>Ciao {{ customer_name }},</p> <p> The booking for {{ experience_variant_name }} is not available for {{ starting_time|time:'H:i' }} of {% language 'it' %} {{ starting_date|date:'l, d F Y' }} {% endlanguage %}. </p> Python: email = EmailMessage( subject=subject, body=message, from_email=DEFAULT_FROM_EMAIL, to=[booking.customer_email], bcc=MANAGERS_EMAILS, headers={"Content-Type": "text/html; charset=UTF-8"}, ) email.content_subtype = "html" email.send() settings.py: EMAIL_CHARSET = "utf-8" And I'm using sendgrid. -
i have some questions about full-stack with django
I learned Python and I plan to become a web developer, but I don't know if it is better to become full stack or back end. I know Django is good for Python. Is it good to learn the backend first? This is the road map I decided to follow, do you approve? https://github.com/HHHMHA/django-roadmap -
Issue with accessing form.cleaned_data in Django view function
I'm encountering an unexpected issue while working on a Django project involving a registration form. I have two code snippets that are functionally similar, but I'm getting different outcomes regarding the access to form.cleaned_data. I'm hoping someone can help me figure out what might be causing this discrepancy. Code Snippet 1: def signup(req): if req.method == 'POST': form = RegisterForm(req.POST) if form.is_valid(): messages.success(req, 'Account Created successfully') form.save() print(form.cleaned_data) return render(req, 'signup.html', {'form': form}) else: form = RegisterForm() return render(req, 'signup.html', {'form': form}) Code Snippet 2: def signup(req): if req.method == 'POST': form = RegisterForm(req.POST) if form.is_valid(): messages.success(req, 'Account Created successfully') form.save() print(form.cleaned_data) return render(req, 'signup.html', {'form': form}) form = RegisterForm() return render(req, 'signup.html', {'form': form}) In both snippets, the form is submitted and processed similarly. However, when I use the first snippet, I can successfully access form.cleaned_data and print it after a successful form submission. But when I use the second snippet, form.cleaned_data seems to be unavailable, and the printed output is empty. I have double-checked the code for any typos or missed details, but both snippets are practically identical. I'm quite puzzled as to why this difference in behavior is occurring. -
css files are blocked when I am using production mode with Django
I have a django app. And I try to simulate production envrionment. So I have splitted the settings in three seperate files: local , prod and base. Part of the base.py looks like: import os from pathlib import Path from os import environ from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG') == "False" STATIC_URL = '/static/' STATIC_DIRS = [ (BASE_DIR, 'static') ] STATIC_ROOT = BASE_DIR /'staticfiles' STATICFILES_DIRS =['DierenWelzijn'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR /'media' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = BASE_DIR/'media' MEDIA_URL = '/media/' And the manage.py file looks like: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from DierenWelzijn.settings import base def main(): """Run administrative tasks.""" if base.DEBUG: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.local') else: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.production') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your … -
Display multiple images in one post content on social media
I'm making a social network website with django, html, css, jquery. I already can upload images to database and display it in my post but I want to organize it a little bit just like this. How can I do that with html and css? -
Why in Django many-to-many relation shows wrong data in the admin panel
I'm trying to implement the many-to-many relation to support in the user model these features: user followers (persons who follows the user) user following (persons the user follows) To achieve that I'm using double relation on the same model because followers/following are the same User models. Basically it works hoverwer I'm facing a weird behavior in the Django admin panel. When I add some user to other user to the following list (in the shell everything ok), the Django admin panel shows that user in the followers list but he should be in the following list. I can't understand why it happens. Many thanks for any help! My models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): followers = models.ManyToManyField('self',blank=True,related_name='user_followers',symmetrical=False) following = models.ManyToManyField('self',blank=True,related_name='user_following',symmetrical=False) pass Supppose Admin wants to follow Neo. Neo should have follower - Admin. Admin - should have Neo in his following list. Shell commands and result: admin = User.objects.filter(username='admin')[0] neo = User.objects.filter(username='neo_anderson')[0] // check that everything is empty neo.user_following.all() <QuerySet []> neo.user_followers.all() <QuerySet []> // --- admin wants to follow neo --- // add the admin to the neo followers neo.user_followers.add(admin) neo.save() // add the neo to the admin following admin.user_following.add(neo) admin.save() // check if … -
How to declare user_id on ModelViewSet in DjangoRestFramework
Foreignkey root is User> Comparelist > obj I don't know what's wrong with my code. Error message said me comparelist required user_id accounts> models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import UserManager from core.models import TimestampedModel class User(AbstractBaseUser, PermissionsMixin, TimestampedModel): email = models.EmailField(max_length=30, unique=True, null=False, blank=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' accounts> serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def create(self, validated_data): user = User.objects.create_user( email = validated_data['email'], password = validated_data['password'] ) return user ImageConverters> models.py from django.db import models from accounts.models import User class CompareList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) class Obj(models.Model): comparelist = models.ForeignKey(CompareList, on_delete=models.CASCADE) object_name = models.CharField(max_length=100) image = models.URLField(max_length=500) ImageConverters> serializers.py from .models import CompareList, Obj from rest_framework import serializers class ObjSerializer(serializers.ModelSerializer): class Meta: model = Obj fields = ['object_name', 'image'] class CompareListSerializer(serializers.ModelSerializer): objs = ObjSerializer(many=True, read_only=True) class Meta: model = CompareList fields = ['id', 'objs'] def create(self, validated_data): # print(dir(self)) print(self) print('------------------') images_data = self.context['request'].FILES texts_data = self.context['request'].data comparelist = CompareList.objects.create(**validated_data) print(texts_data) for image_data, text_data in … -
Django on_delete for Model with custom delete function
I have the following models: class Concert(models.Model): name = models.CharField(max_length=255) is_deleted = models.BoolField(default=False) def delete(self): self.is_deleted = True self.save() class Ticket(models.Model): concert = models.ForeignKey(Concert, on_delete=models.CASCADE) is_deleted = models.BoolField(default=False) def delete(self): self.is_deleted = True self.save() I noticed when I call delete on Concert, it doesn't call delete on Ticket. This is expected behavior, right? Is there any way to trigger CASCADE even in the case of this custom delete function? -
Google Ads API & Python - How to get all accounts (name + ID) that a user has access
I'm trying to get the account name and ID of all the accounts that the logged user has access to. I've managed to get the IDs using the code on https://developers.google.com/google-ads/api/docs/account-management/listing-accounts?hl=es-419. But I need the names too and apparently you have to make one API call for each ID to get their account names or any other info. I've tried with the following Python (Django) code, but it's not working (it probably could be improved a lot and maybe has mistakes, I'm a Python beginner): def one(request): client = credenciales(request) ga_service = client.get_service("GoogleAdsService") # Get customer resource names from the original code customer_service = client.get_service("CustomerService") accessible_customers = customer_service.list_accessible_customers() customer_resource_names = accessible_customers.resource_names # Prepare a list to store customer data list_clients = [] # Iterate through each customer resource name for resource_name in customer_resource_names: # Extract the customer ID from the resource name custom_id = resource_name.split('/')[-1] # Create a query using the customer_id query = f''' SELECT customer_client.descriptive_name, customer_client.id, customer_client.status FROM customer_client ''' stream = ga_service.search_stream(customer_id=custom_id, query=query) for batch in stream: for row in batch.results: data_clients = {} data_clients["descriptive_name"] = row.customer_client.descriptive_name data_clients["id"] = row.customer_client.id data_clients["status"] = row.customer_client.status list_clients.append(data_clients) # Pass the list of customer data to the template context = { … -
django object.id does not work when passed in an url in html
I have just started learning Django and I cannot figure out why my player.id kills the page when I try to pass it in an url, while it does work as a variable (see both in the code below.) When I omit the player.id from the url, the page works (except for the "delete" link, of course). {% for player in all_players%} <li>{{player.player_name|capfirst}} scored {{player.player_score}} and the id {{player.id}}!</li> <div class="link" id="link"> <a href="{% url 'delete' player.id %}"> delete </a></div> {% endfor %} Here is my urls and "delete" in view: urlpatterns = [ path('first', views.first, name='first'), path('delete/int:player_id', views.delete, name='delete'), path('third', views.third, name='third'), path('second/int:player_id', views.second, name='second'), path('', views.index, name='index'), ] def delete(request, player_id): player = Player.players_objects.get(id=player_id) player.delete() return render(request, 'all_players.html', {'player': player}) -
Deploy Django app on PythonAnywhere with custom domain [closed]
I have worked on one legacy project where I have build Django backed-end website. I want to put this on PythonAnywhere server, but problem is that domain registrar provider only supports NS and not CNAME. Is there any way to deal with this so I host the web on pythonanywhere? -
Is there a way to make a https post with only port 80 in nginx config file?
So, I a have Django app which needs to send data to an API. I am using request to send the data. First, it was warning me that -in short- I am not using SSL for sending the JSON data. To solve this I added "verify=PATH TO THE CERT FILE" requests.post(url, json=payload, verify='\fullChainCert.crt') After this I got 200, so I was happy. Question is, will it work like this on server? Port 443 is open on server, but only 80 in nginx config file. -
Uploading to azure blob storage via front end
I want to allow the user to upload large files to azure blob storage.. The problem is when I do it the regular way: [Javascript HTTP POST Request (with file attached) -> django web server -> azure blob storage] the request times out.. Is there a way I can have Javascript call and upload photos to azure blob storage directly and securely and skip the django web server? -
Why the result of embedded field with Djongo is empty set
This is My Code from djongo import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True def __str__(self): return self.name class Entry(models.Model): _id = models.ObjectIdField() blog = models.EmbeddedField( model_container=Blog, ) headline = models.CharField(max_length=255) objects = models.DjongoManager() def __str__(self): return self._id.__str__() This is My Query from generator.models import * e =Entry() e.headline='h1' e.blog={'name':'n1','tagline':"t1"} e.save() res = Entry.objects.all() #res[0].blog #{'name': 'n1', 'tagline': 't1'} res = Entry.objects.filter(blog__startswith={'name':'n'}) #res #<QuerySet []> Is the query right enter image description here The result of embedded field with Djongo query would not be empty -
Moving from Django signals to save override: How to translate the "created" parameter of a Django post_save signal for a save method override
I have made some bad decisions earlier regarding how I handle post_save events on a Django model and I am currently looking into changing my approach. Let's begin by making my example. Here is my model. class MyModel(models.Model): #... all my model creation and logic are here def do_something(self): # Actually do something, for the sake of simplifying the example, just write pass pass Now, what I am using is a receiver function like this one. It works, but for many reasons that are mine, I want to stop using signal in this case. @receiver(post_save, sender=MyModel) def foo(sender, instance, created, **kwargs): if created: instance.do_something() I imagine I could override the MyModel.save method, something like this: class MyModel(models.Model): #... def save(self): super().save() if created: # It is this line that I need to figure how to do. self.do_something() By what should I replace the if created: of my receiver function if I want to override the save() method? Or do you have something else to recommend? I would also be curious if it is the same thing for pre_save signals. -
Why is my base.html conflicting with my index.html
I have a Django blog site where I put my navbar inside the base.html at the root of the project, I also have an h3 in my index.html but the h3 just appears inside the navbar instead of stacking below the navbar. Folder structure This is my base.html This is the output](https://i.stack.imgur.com/8y9ZL.jpg)(https://i.stack.imgur.com/FJRmF.jpg) -
Django admin panel shifts to left
Just a simple question that I have no idea how to describe: Anybody knows what has happened here? -
Subtract datetimes, round result to full hour python
I am trying to calculate time between one date and another and give result in hours rounding up hours. I tried just substracting, both dates are datetime total_hours = self.valid_until - self.started_at the result is timedelta. I tried this one but it seems like it is viable for datetime field only (total_hours.replace(second=0, microsecond=0, minute=0, hour=total_hours.hour) +timedelta(hours=total_hours.minute//30)) -
After pushing my code from the production server to a gitlab repository, I have a problem with postgresql and migrations in my django webapp
Now maybe I'm getting this wrong but here's my story : Today, i decide to get the code that I've been writing in an uncontrolled manner on the production server to a gitlab repository. So I create the repository on gitlab and push my code using git init git add . git commit -m "message" git remote add origin https://gitlab.com/xxxxxx git branch -M master git push -uf origin master A few hours later I notice my django webapp is down and when i check in the error logs, it coincides roughly with the work I was doing on gitlab The error message I get is 2023-08-08 21:26:31,218: Error running WSGI application 2023-08-08 21:26:31,226: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' I reinstalled the module with pip3 install psycopg2 Then i get the error message psycopg2.errors.UndefinedTable: relation "app_pageview" does not exist LINE 1: ..."app_pageview"."url", "app_pageview"."count" FROM "app_pagev... pageview is a middleware I create to log the number of pageviews per page to the database I have a look in the database with python3 manage.py dbshell \dt and I see that there are no tables relating to the pageviews in the database So I think , maybe if I see … -
Trying to send Validation Email in django, getting error
Im trying to send validation email when creating a user in django. It used to work like that but then I did some refactoring on the URLs and used urlpattern = UrlPattern() and urlpattern.register(UserView). That is in the main django project url.py In the app url.py Im having urlpatterns = [ path('activate/<uidb64>/<token>', backend_logic.activate, name='activate') ] where activate is a function in backend_logic, which used to work and send the email to the one from request. However, now Im getting the error Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name. -
I have problem when I uploading my website in Heroku give me this error
error: subprocess-exited-with-error × Building wheel for twisted-iocpsupport (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [13 lines of output] running bdist_wheel running build running build_ext building 'twisted_iocpsupport.iocpsupport' extension creating build creating build/temp.linux-x86_64-cpython-311 creating build/temp.linux-x86_64-cpython-311/twisted_iocpsupport gcc -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Itwisted_iocpsupport -I/app/.heroku/python/include/python3.11 -c twisted_iocpsupport/iocpsupport.c -o build/temp.linux-x86_64-cpython-311/twisted_iocpsupport/iocpsupport.o twisted_iocpsupport/iocpsupport.c:1102:10: fatal error: io.h: No such file or directory 1102 | #include "io.h" | ^~~~~~ compilation terminated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for twisted-iocpsupport Successfully built autobahn paypalrestsdk psycopg2 pycountry Failed to build twisted-iocpsupport ERROR: Could not build wheels for twisted-iocpsupport, which is required to install pyproject.toml-based projects ! Push rejected, failed to compile Python app. ! Push failed I change Daphne package but still not working