Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: render django-countries's countries as a dropdown list (with search option)
I'm trying to make a drop down list, so users can: 1.- Select country they wanna see: from home, they'd be redirected to specific country. example: mydomain.com to: mydomain.com/mx 2.- to help them, they could also type and search specific country, and then would be redirected. I've this: forms.py: from django import forms from django_countries.fields import CountryField class CountryForm(forms.ModelForm): class Meta: model = CountryField fields = ['country'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['country'].widget.attrs.update({"class": "form-control"}) # or iterate over field to add class for each field for field in self.fields: self.fields[field].widget.attrs.update({'class':"form-control"}) html: {% extends '_base.html' %} {% load static %} {% block title %}Home page{% endblock title %} {% block content %} <form method="post" class="form-group"> {% csrf_token %} <div class="form-group col-md-12 mb-3"> <label for="{{ form.owner_name.label }}">{{ form.owner_name.label }}</label> {{ form.owner_name }} </div> <div class="form-group col-md-12 mb-3"> <label for="{{ form.car_type.label }}">{{ form.car_type.label }}</label> {{ form.car_type }} </div> <hr class="mb-4"> <button type="submit" class="btn btn-secondary btn-lg btn-block">Go to country</button> </form> {% endblock content %} -
Django signals pre_delete accessing request.user
Is there a way to access request.user within pre_delete signal? I found an answer but that was 10 years ago and doesn't work with the current version of Django. -
How to add a custom field to the Django admin login page
To authenticate, 3 fields are needed: user_id password account_id Each account_id defines an isolated space and the user_id is unique only inside its respective account_id. I've created a custom backend authentication and I can authenticate successfully. The problem is that the login Django Admin form has user_id and password fields by default. I would like to add the account_id field in the original Django form template by only subclassing AuthenticationForm, is it possible? There's a similar question here but he's using a custom login template: Add custom field to Django Admin authentication form Existing code.. Model: class HeliosUser(AbstractUser, DateModelBase): username = None user_id = models.CharField(max_length=255) USERNAME_FIELD = "user_id" REQUIRED_FIELDS = ["account_id", "role", "email"] objects = HeliosUserManager() email = models.EmailField() account_id = models.ForeignKey( "agent.Agent", on_delete=models.RESTRICT, ) ... Backend: class SettingsBackend(BaseBackend): def authenticate( self, request, user_id=None, account_id=None, password=None, **kwargs ): try: user = HeliosUser.objects.get( user_id=user_id, account_id=account_id ) except HeliosUser.DoesNotExist: return None if user.check_password(password): return user return None def get_user(self, user_id, account_id): try: return HeliosUser.objects.get( user_id=user_id, account_id=account_id ) except HeliosUser.DoesNotExist: return None Admin site: class HeliosUserAdmin(admin.AdminSite): site_title = "Helios Administration" site_header = "Helios Administration" index_title = "Helios Administration" login_form = HeliosAuthenticationForm admin_site = HeliosUserAdmin() Authentication form: class HeliosAuthenticationForm(AuthenticationForm): account_id = forms.ModelChoiceField(queryset=Agent.objects.all()) Thank's in … -
Is there any way to automatically set Debug True Django application
I have a Django API that is being deployed in PythonAnywhere. For that, I can not let the default option in settings.py as True: DEBUG=True However, the app also has a Swagger page using drf-yasg library. For that to work locally, I have to set the debug option as true. However is being troublesome to maintain it, and I often mistakenly commit it as True to the repository. Is there anyway I could manage this option so whenever I am running locally, it will automatically set it to True, but leave it as False by default? DEBUG=False -
Pass parameters or re use attributes in django serializer methods
i have this code: class InvoiceSerializer(serializers.ModelSerializer): val = serializers.SerializerMethodField() cost = serializers.SerializerMethodField() class Meta: model = Facturacion fields=["val", "cost", "others..."] def get_cost(self, object, va): print(va, "myvalue") return 1 def get_val(self, object): val = Va.objects.get(id=1) serializer = ValSerializer(valorUnitario) self.get_cost(self, object, (serializer.data)['val']) return (serializer.data)['val'] the (serializer.data)['valorUnitario'] is returning a number, i just want to pass this value to the get_cost function but it give me the message InvoiceSerializer.get_cost() takes 3 positional arguments but 4 were given. I dont want to make all the process of get_val again for optimization reasons, i just want to use the same data but in get_cost. Another form i was trying was this: def get_cost(self, object): return self.val val its supposed to be filled with the get_val method (and it shows correctly when i consume the api); but it gives the message: AttributeError: 'InvoiceSerializer' object has no attribute 'val' how can i re-use the attribute val? -
How to get ImageField url when using QuerySet.values?
qs = self.items.values( ..., product_preview_image=F('product_option_value__product__preview_image'), ).annotate( item_count=Count('product_option_value'), total_amount=Sum('amount'), ) product_option_value__product__preview_image is an ImageField, and in the resulting QuerySet it looks like product_preview_images/photo_2022-12-10_21.38.55.jpeg. The problem is that url is a property, and I can't use media settings as images are stored in an S3-compatible storage. Is it possible to somehow encrich the resulting QuerySet with images URLs with a single additional query, not iterating over each one? -
LTM Load Balancer drops connection while App waiting for big SQL query response
Newly implemented LTM Load Balancer drops connection while our App is waiting for big SQL query response. Now i need to find some workaround because appearently extending timeouts on LB is not a way to go. App runs on Django and MSSQL Is there any possibility to lets say send query to DB -> get some kind of transaction ID (JWT?) -> close connection -> create GET with some transaction ID to check if there is result of this query? (Not sure how this transaction ID would be stored on DB side tho) Is Pagination doin something like this? I would like to avoid making this like this: Create API endpoint which runs queries to DB -> Send request to API -> DB process with query and put results in new table -> send query to new table -
504 Gateway Timeout (Gunicorn-Django-Nginx) Docker Compose Problem
There is one process backend which take around 1-2 minutes to process. The loading screen runs for 1 minute and shows 504 Gateway Timeout Here's the log in nginx.access.log 172.18.0.2 - - [16/Dec/2022:23:54:02 +0000] "POST /some_request HTTP/1.1" 499 0 "http://localhost/some_url" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" But from the django debug log, I can see that the POST request is still processing at the backend docker-compose.yml timeout is set to 300, without it, the browser will return 502 error (connection prematurely closed) services: web: image: genetic_ark_web:2.0.0 build: . command: bash -c "python manage.py collectstatic --noinput && gunicorn ga_core.wsgi:application --bind :8000 --timeout 300 --workers 2 --threads 4" This is all the params I have tried in nginx.conf but still the 504 timeout is returned after 60s server { # port to serve the site listen 80; # optional server_name server_name untitled_name; ... # request timed out -- default 60 client_body_timeout 300; client_header_timeout 300; # if client stop responding, free up memory -- default 60 send_timeout 300; # server will close connection after this time -- default 75 keepalive_timeout 300; location /url_pathway/ { proxy_pass http://ga; # header proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_connect_timeout 300s; proxy_send_timeout … -
Django Comments Xtd Comments are not nesting
I followed the tutorial on https://django-comments-xtd.readthedocs.io, everything seems to work find, the forms and the comments are working, but on the website they are not displayed properly. instead of looking like this: They all look like this The reply is not nesting under the comment but in the admin its working you can see how it nests take a look: Please help -
Is it an antipattern to use `request.POST or None` to initialize a Django form?
I came across a blog post arguing that the following is an antipattern: def some_view(request): form = MyForm(request.POST or None) # … Source: https://www.django-antipatterns.com/antipattern/using-request-post-or-none.html However, I'm not clear on the problems that using it could cause. I have used this to keep my views concise, without noticing any unexpected behavior. Is this an antipattern? If so, why? -
Error after migrating django database to postgresql
I have recently changed my database from sqlite3 in django to postgresql as I prepare my app for production. After making changes in settings.py, I have tried making migrations and I am getting an error. After running python manage.py migrate --run-syncdb I get the error below in the terminal System check identified some issues: WARNINGS: users.Document.uploaded_at: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` users.Order.amount: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field users.buyer.uploaded_at: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` Operations to perform: Synchronize unmigrated apps: channels, chatapp, crispy_forms, messages, payments, staticfiles, users Apply all migrations: admin, auth, contenttypes, sessions Synchronizing apps without migrations: Creating tables... Creating table users_user Creating table users_document Creating table users_buyer Creating table users_category Creating table users_service Creating table users_profile Creating … -
Editing it in html when we pull data from Django
The news saved in the system will come to my page. I pulled data from django. Currently the data is coming one after the other. I want to pull 3 data side by side after it's will be 3 data below again and so it will go like that. How can i do this? My kategori.html: {% extends "homebase.html" %} {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} {% block head %} <link rel="icon" type='image/png' href='{{ setting.icon.url }}'/> {% endblock %} {% block header %}{% include 'header.html'%}{% endblock %} {% block sidebar %}{% include "sidebar.html" %}{% endblock %} {% block content %} {% load static %} <section id="news" data-stellar-background-ratio="2.5"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="section-title wow fadeInUp" data-wow-delay="0.1s"> <h2>TIBBİ BİRİMLER KATEGORİSİ</h2> </div> </div> <div class="col-md-4 col-sm-6" > <!-- NEWS THUMB --> <div class="news-thumb wow fadeInUp" data-wow-delay="0.4s"> {% for rs in category %} <a href="kategori.html"> <img src="{{rs.image.url}}" class="img-responsive" alt=""> </a> <div class="news-info"> <span>{{rs.create_at}}</span> <h3><a href="bos-sayfa.html">{{rs.title}}</a></h3> <p>{{rs.description}}</p> <div class="author"> <div class="author-info"> <p>{{rs.keywords}}</p> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </section> {% endblock %} {% … -
Postgresql with heroku
I have a Postgres database on my PC with all data that I need so far in the project, my app is deployed on Heroku without any data in the database Heroku gave to me. I want to provide my app on Heroku with data from my DB. I tried using pg_dump but couldn't figure out what I was doing wrong, I thought I could host my DB and then somehow connect it. -
Filtering Django API by time not working before "10:00:00"
I made this Django API to search by date and time, the date filter works perfectly but once I start trying to filter by time it only filters data from 10:00:00 to 24:00:00 and completely disregards filtering anything stamped 00:00:00 to 09:59:59. Here's an example of the way I'm storing my data in my db: "id": 10, "added_date": "2022-12-16", "added_time": "10:12:54", "name": "Name", Here is my code: class Search(generics.GenericAPIView): def get_queryset(self): start_date= self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') start_time= self.request.query_params.get('start_time') end_time = self.request.query_params.get('end_time') try: search= objects.filter(added_date__range=[start_date, end_date], added_time__range=[start_time, end_time]) return search.all() except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) def get(self, request): try: queryset = self.get_queryset() serializer = SearchSerializer(queryset, many=True) response = Response(serializer.data) return response except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) I believe the "0" in front of times such as 09:30:00 is throwing off the search. However in the table 09:04:10 would show up as 9:4:10 and it still giving problems. Any help would be greatly appreciated, thank you! -
use *args in django url paramater
I have a webpage within my site which shows a list of Lego set themes. Each theme may have sub-themes and those sub-themes may also have sub themes. In the image below each indentation level represents what themes are sub-themes of other themes. For example on my page a user could take the path: http://127.0.0.1:8000/themes (shows all parent themes) http://127.0.0.1:8000/themes/train (shows all sub themes of train) http://127.0.0.1:8000/themes/train/9V (shows all sub themes of train/9V) http://127.0.0.1:8000/themes/train/9V/My%20Own%20Train (no sub themes) In my view i suppose i would use *theme to handle any number of sub-themes url path http://127.0.0.1:8000/theme/train/9V/ views.py def theme(request, *theme): #theme = ('train', '9V') theme_path = "".join([theme + "/" for theme in themes]) #theme = 'train/9V/' theme_items = db.get_theme_items(theme_path) sub_themes = db.get_sub_themes(theme_path) context = { "parent_theme":theme[0], "theme_items":theme_items, "sub_themes":sub_themes, } return render(request, "App/theme.html", context=context) urls.py urlpatterns = [ ... path('theme/<str:theme_path>', views.theme, name="theme"), ... ] theme.html sub_theme.0 = name of the sub theme e.g '9V' sub_theme.1 = image url header = parent to sub theme e.g 'train' {% for sub_theme in sub_themes %} <div class="theme-container"> <p><a href="{% url 'theme' parent_theme %}/{{sub_theme.0}}">{{sub_theme.0}}</a></p> <img src="{{sub_theme.1}}" alt="{{sub_theme.0}}_url"> </div> {% endfor %} How could i pass multiple parameters into the url which can be handled by my … -
Django & Digital Ocean: Exception("DATABASE_URL environment variable not defined") When running local server
I built a django app on my local machine, and then used this tutorial to deploy it with app platform (https://docs.digitalocean.com/tutorials/app-deploy-django-app/) The deployment was successful. However, now when I try to run my django app locally to continue development, I’m getting the following error: …/settings.py", line 95, in raise Exception(“DATABASE_URL environment variable not defined”) Exception: DATABASE_URL environment variable not defined Current settings in settings.py: DEVELOPMENT_MODE = os.getenv(“DEVELOPMENT_MODE”, “False”) == “True” DEBUG = os.getenv(“DEBUG”, “False”) == “True” I am unsure of how to reset my settings.py file so that it points to a local sqlite3 db for development. -
Static files not loading
I'm trying to create an homepage for my app but my page keeps loading after adding the STATIC_ROOT and STATICFILES_DIR. it gives Broken pipe from ('127.0.0.1', 49634) in my terminal. This is my home.html This is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') this is my urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to update FileField or ImageField hosted by s3 in my Django project?
I have a Django web app that allows users to upload a picture or video, and it works perfectly when I upload it the first time, but when I go back to change it, it doesnt update, it allows me to to clear the field but I can't upload a new file. I'm totally new to s3 and am having a hard time reading the docs. I'm not sure what code I should attach, but this is in my settings.py AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I can also share my views.py but I feel like it has something to do with permissions. Any help would be greatly appreciated! -
Django return a ManyToMany field from other class
I have two classes in django: class MovementsGyn(models.Model): gyn_name = models.CharField('Name', max_length=70) gyn_desc = models.TextField('Description', blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] class Rod(models.Model): Rod_name = models.CharField('Rod Name', max_length=70) movements_gym = models.ManyToManyField(MovementsGyn) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] And a view to show the result grouped: def estatistica(request): template = 'moviment.html' estatic_movem_gyn = Rod.objects.filter(owner=request.user) \ .values('movements_gym').order_by('movements_gym') \ .annotate(qtde=Count('id')) context = { 'estatic_movem_gyn' : estatic_movem_gyn } return render(request, template_name, context) The result is movements_gym grouped and, in qtde, the quantity of register that we have in database. The question is, how can I show the field gyn_name that are in MovementsGyn models ? -
Receiving Error: 'apxs' command appears not to be installed
This is the error I am receiving: RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages. How can I get around this? I have received this while trying to install different packages. I am working on a Django project. I have already made sure the apache2-dev package is installed. -
Why does request.POST always contains name of the button? How to avoid it?
This is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <script src="{% static 'jquery-3.6.2.min.js' %}" ></script> <script src="{% static 'jquery.js' %}" ></script> </head> <body> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <button name="button1">button1</button> <button name="button2">button2</button> <input type="text" name="textbox"> </form> </body> </html> Every time I type some text in the textbox, let's say I type: "hi" and hit enter, the request.POST returns: <QueryDict: {'csrfmiddlewaretoken': ['FX1qFNzbQUX3fYzAwW27cOu83omLzifnlLU5X0WXXVdOiyNretM5b3VgsGy1OogA'], 'button1': [''], 'textbox': ['hi']}> Why does request.POST contain 'button1': [''] even though I haven't clicked on it? Is there a way to avoid request.POST to have 'button1': ['']? -
Use multiple workspaces containing django without PYTHONPATH
Sometimes I need to run our project with django backand in multiple workspaces on different git versions. While doing it I discovered that django is heavely relying on PYTHONPATH and probably because of that mixing up the workspaces. When I call python manger.py runserver for example, I can see sources being pulled from the other workspace. On contrary, if I remove both workspaces from PYTHONPATH (which was the only thing in there) the above command fails with the quite infamous error: File "/opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: XYZ For me it looks like, he can not find the modules outside django, which has been otherwise obtained from the PYTHONPATH path. Since all our modules including the one that is reported to be missing are on the same level as django I tried to extend the sys.path in manage.py like this: import pathlib def main(): current_dir = pathlib.Path().resolve() [sys.path.append(str(x)) for x in current_dir.parent.iterdir() if x.is_dir() and not x.name.startswith(".")] Although I can see the path being extended the above exception still occurs. Any help on … -
How to customize image toolbar in ckeditor and enable Upload outside admin panel?
The first problem: If click on the image toolbar, the wizard appears with additional settings. Can I modify it to upload the image in one click without entering additional information and sending the image to the server? The second problem: Outside the admin panel, there is no upload tab on the image toolbar. How to fix it? Thanks for your time. -
Django with DRF. Users cannot sign in with their credentials
I have a web app using Django as the backend and React as the frontend. I have a sign up form where the users enter their credentials and the profile is created in the database. However, when the users create their profile, they are unable to login even though the user data is available in the database. Altering the user password with the django-admin panel fixes this issue and the users can login sucessfully into their accounts. I'm assuming this is an issue with the password saving during profile creation but I can find the issue. Profile creation method # Create user @api_view(['POST']) def sign_up(req): serializer = UserSerializer(data=req.data) if serializer.is_valid(): if User.objects.filter(email=serializer.validated_data['email']).exists(): return Response({'email': 'The email entered is already in use by another account.'}) serializer.save() return Response({'status': 'success'}) else: return Response(serializer.errors) User sign in method # Sign in user @api_view(['POST']) def sign_in(req): username = req.data['username'] password = req.data['password'] user = authenticate(req, username=username, password=password) if user is not None: return Response({'status': 'success'}) else: return Response({'err': 'The username or password entered is incorrect.\nThe username and password are case sensitive.'}) I have tried forcefully resaving the password on profile creation but that doesn't work. Have also tried some online solutions but to no … -
How to pull information from html and use it in a view in Django
Im trying to send a post request with a payload that includes a username and password. The post request works fine on its own but I'm not sure how to get the user and pass that are entered and use them with the post request. Trying to take the data entered into the html and use it in a view I've looked around online and found something suggesting something similar to which doesn't fail but instead returns none: username = response.GET.get['username'] password = response.GET.get['password'] I see this stack overflow:Django request.POST.get() returns None that definitely has the correct answer in it but I don't quite understand whats going on/what I need to do in order to get the result im trying for. I can see its something to do with that I have to post the data to the url or something for it to be eligible to grab from the above statements or something, but again, I don't really understand whats happening. Honestly what im looking for here is an ELI5 of the answer from the link