Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Any way to use CRUD TableBlock in Wagtail?
I'm talking about a table with data from a model (like Django). So that the visitor can make changes to the table fields without reloading the page. The description of the framework shows several options for developing such a solution in WAGTAIL make a snippet and link it to a table. There will be a filter option. But I still could not understand whether it is possible to make changes to the table cells without reloading. In that case, I suppose to use something like that: @register_snippet class Mapping(models.Model): map_code = models.OneToOneField('Map', models.DO_NOTHING, db_column='curr_map_code', primary_key=True) date_begin = models.DateField() class Meta: managed = True db_table = 'MAPPING' Using the STREAMFIELD add a TABLEBLOCK. the documentation says that it is based on handsontable 6.2.2 and it has the ability to make changes without rebooting page with table. But I cant achive managed to generate table data based on the Django model and possibility for user edit. That is, I can manually enter values in the cells in the admin panel. But in the custom view, there is no such possibility at all. Try to use something like that: class Mapping(models.Model): map_code = models.OneToOneField('Map', models.DO_NOTHING, db_column='curr_map_code', primary_key=True) date_begin = models.DateField() class Meta: managed … -
I need a brief explanation into how to connect my Django application to a Google Cloud MySQL database
I'm pretty new to web development and I'm currently deploying my first web application. It's pretty much built with stock Django and a few dependencies. Right now, I have it deployed on Railway.app with a very standard SQLite database. However, I would like to have my data stored in a more long term solution, so I'm looking at using MySQL inside of a Google Cloud instance. I have already tested my application using a local mySQL database, now, I'm trying to connect it to the remote one. However, I'm a bit stumped in how to do it on the Google Cloud instance. Google Cloud provides me an public IP, I have an user and password and a database created there, but that is not enough and I'd like some guidance in how to proceed from here. From what I understand, Google Cloud requires the user to access through an allowed network and I'm unsure what that means. I'm also unsure what this would look like once deployed on Railway. Google Cloud in general uses a lot of names that I don't quite understand. Do I need to use a Cloud Console to do anything? Is there anyway for me to … -
how to edit a django project?
Ive downloaded a django project, I wanna delete a feature from it, how to edit or modify the code? I know nothing about django I want to remove feature from a working code. The project is online examination system i want to remove the salary feature in it. (https://drive.google.com/file/d/1EqE4xqgp5YQKkQCwVrypxN6Hh3BR4tq1/view?usp=sharing) can anybody remove that salary feature from this? or tell me how to do it? -
Use Django Allauth with inertia.js & Vue
I'm trying to using Django Allauth with inertia + vue combination. Take a view like e.g.: from inertia import render def about(request): return render(request, "About", props={"pageName": "About"}) I have my project configured in a way that it will render this inside About.vue like so: <script setup lang="ts"> defineProps<{ pageName: string; }>(); </script> <template> <div> <h1>This is the {{ pageName }} page</h1> </div> </template> How would I go about connecting this to Django Allauth? Thinking of something like extending from e.g. their LoginView: from inertia import render from allauth.account.views import LoginView def login(request): return render(request, "Login", props={"context_obj": ?}) Not sure what I can do to pass the context object through. Anyone any ideas? -
Migrate from CharField to LocalizedCharField
I am integrating django-localized-fields and have to save current data in char field at least in default language. For example: from django.db import models class FineModel(models.Model): title = models.CharField(max_length=128) needs to migrate to from localized_fields.models import LocalizedModel from localized_fields.fields import LocalizedCharField class FineModel(LocalizedModel): title = LocalizedCharField(blank=True, null=True, required=False) and text from title column should be transferred to updated title column like that: new_obj.title.en = old_obj.title I tried to add new temporary field title_l and use 3 migrations to transfer all data from title field to title_l field delete title field rename title_l to title and delete title_l from model but this is not working, because first of these migrations will fail on production contour because title_l is not presented in FineModel. Any advices appreciated, I believe this can be done in single migration. -
How to render react images on django
After developing my react application, i decided to render it in my django using the npm run build command, which I have successfully done and it's working efficiently. But the only problem is that my images are not being rendered. Please any suggestion on how i can make django render my images. Django keeps saying this "Not Found: /images/blog/b2.webp [08/Aug/2023 17:43:02] "GET /images/blog/b2.webp HTTP/1.1" 404 3104" each time the app runs I created a static root to render all static files and also a media root for all media files. Here is the code STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'reactapp/myschool/build/static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'reactapp/myschool/build/media')