Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django increment value on submitting form
class Project(models.Model): dept= models.ForeignKey(Department, on_delete=models.SET_NULL, null=True) count = count = models.IntegerField(blank=True,null=True) What i am trying to do is everytime i add project increase the project count of Department. For example 'x' has no project and i add a new project and count will be = 1 then count will be 2. Then department 'y' will add project count will be = 1 for 'y' but stays 2 for 'x' department. -
Django filters with conditional field
I have a User modal and UserAddress model. I am trying to sort users based on UserAddress.city field. #models class User(AbstractUser): ... class UserAddress(TimeStampedModel): ... city = models.CharField(max_length=50, null=True) ... primary = models.BooleanField(default=False) #User can only have 1 primary record active = models.BooleanField(default=True) #viewset class UserViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = serializers.UserSerializer ordering_fields = [ ... 'useraddress__city' ] #serializers class UserBasicSerializer(serializers.ModelSerializer): user_city = serializers.SerializerMethodField() def get_user_city(self, obj): try: address = models.UserAddress.objects.filter( primary=True, active-True, user=obj ).first() return address.city except: return None class Meta(object): model = User fields = ( ... "user_city", ... ) If it use domain?sort=London it works, however, it does not take active and primary fields into account. So i get sorting with gaps of null in the result. I want to treat those gaps as real null values, bit not sure how. P.S. I am using JSON API hence sort and not ordering in url. -
Django Static css and js file not found but image show | Itry all method of stackoverflow solution but not work
Add path in setting path is correct also port change no solve change static file location from app to project and project apply documentation code not solve I totally frustrated now STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,"/static/") # ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/gbHfU.png -
I had an error when I wanted to install Django Didocker, this is what the error says :
error while fetching server api version: (2, 'createfile', 'the system cannot find the file specified.') [2196] failed to execute script docker-compose -
How to implement folder like path on web using django
Currently I'm trying to implement path like on this screen,but I have no idea how to do this. What is the best approach to create this path using django? screen -
Using a middleware in Django make my path not accessible
I got an app, that ref to two installed app, one is api, another is webapp. the webapp got a middleware. to avoid the middleware discard my /api request, I use self.get_response to handle it, if the request path is start with /api. Here is my urls.py in api and it is my views.py in api I call localhost:3000/api/foo, it returns me a 404 not found error. I tried to update the api/urls.py to api/foo, but it is not success. -
Send money to multiple accounts via PayPal SDK or API
A website where users can buy digital products from other users and the host takes a cut out of those transactions. How to implement this system using the PayPal SDK or API? Scenario: One buyer with a personal PayPal account One receiver with a personal PayPal account The host with a business PayPal account I wonder if it's possible that the buyer's money to be split and sent to the receiver and host account simultaneously. -
how to style django-select2 dropdown field with bootstrap
I am using django-filter, django-select2 and crispy forms to create a selectable dropdown but the django-filter field looks like bootstrap but I cannot change to style to match the other input fields. This is my crispy forms layout: self.helper.layout = Layout( FieldWithButtons( Field( "original_filename", placeholder=SEARCH_TEXT, css_class="rounded" ), StrictButton( '<i class="fas fa-search"></i>', type="", css_class="no-spinner", ), css_class="mb-0 ml-5 input-group-sm input-icon input-icon-right rounded", ), Div( Field( "location", css_class="form-control my-0", wrapper_class="my-0 mx-1 w-200px" ), css_class="d-flex h-100 " ), Div( Div( HTML(SEARCH_TEXT), css_class="btn btn-secondary ml-1", onClick="$(this).closest('form').submit();", ) ), Div( Div( Div( HTML(mark_safe('<div class="fas fa-sort-amount-down"></div>')), css_class="mx-2", ), css_class="d-flex align-items-center", ), Field( "o", css_class="mb-0 input-group-xs", wrapper_class="mb-0 input-group-xs", onChange="$(this).closest('form').submit();", ), css_class="d-flex flex-row ml-5", ), Div(css_class="ml-5 spinner spinner-primary d-none"), ) This is the current result. I tried using bootstraps classes like form-control, input-group but it did not change the outcome. As you can see is the second input field different from the others. -
Django using id to write foreign key fields
I need to have a CRUD interface for interconnected django models. Can i use _id fields to fill in ForeignKey fields? i.e. will this work: class MyModel(models.Model): foreign_key = ForeignKey('AnotherModel') class MyModelSerializer(serializers.ModelSerializer): foreign_key_id = serializers.IntegerField(write_only=True) foreign_key = AnotherModelSerializer(read_only=True) class Meta: model = MyModel fields = ('foreign_key', 'foreign_key_id') -
Django standalone apps with one app depending on another app - django.db.migrations.exceptions.NodeNotFoundError
I am using Django 4.0 I have written two standalone apps. Foo and FooBar. Application Foo uses package django_nyt. Application FooBar uses functionality from application Foo. I am able to makemigrations and migrate models in application Foo, however, when working with application FooBar, when I attempt to makemigrations, I get the following error trace: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/loader.py", line 276, in build_graph self.graph.validate_consistency() File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 198, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 198, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 60, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration foo.0001_initial dependencies reference nonexistent parent node ('django_nyt', '0010_auto_20220802_2211') Since these are standalone apps, I am using the design pattern advocated for in Django Standalone Reusable Libraries. common.py (foo … -
Avoiding the unique_together constraint when updating a Django Model instance with request.POST
Model: class myModel(models.Model): project_id = models.IntegerField( null=False, blank=False, default=0, ), field_1 = models.CharField( max_length=250, null=False, blank=False ), field_2 = models.CharField( max_length=250, null=False, blank=False ) class Meta: unique_together = ('project_id', 'field_1', 'field_2') views.py: model_instance = myModel.objects.get(pk=id) if request.method == 'POST': form = NewMyModelForm(request.POST, instance=model_instance) form.save() forms.py: class NewMyModelForm(ModelForm): class Meta: model = myModel fields = '__all__' Problem: When I edit something in the front-end and I submit the changes (via POST), this code is basically creating a 'new object' so the unique_together constraint can't be satisfied. Is there a way to update the instance bypassing the constraint? -
Django how to override the HttpResponse 404 instead of raise exception
Currently I am implementing the custom error page for my Django Project. I have faced problem where when my project return the HttpResponse (404), the custom error page is not shown instead of, it shows the debug page. #in the views.py (i define 4 functions for error 400,403,404,500) but not for Http404 from django.shortcuts import render def page_not_found_view(request, exception): return render(request, 'error.html',status = 404,context = { 'status_code' : 404, 'message' : "The page you were looking for doesn't exist anymore.", 'title' : "Page Not Found" }) def internal_server_error_view(request, *args, **argv): return render(request, 'error.html',status = 500,context = { 'status_code' : 500, 'message' : "500 Internal Server Error.", 'title' : "Internal Server Error" }) def forbidden_error_view(request, exception): return render(request, 'error.html',status = 403,context = { 'status_code' : 403, 'message' : "403 Forbidden Error.", 'title' : "Forbidden Error" }) def bad_request_error_view(request, exception): return render(request, 'error.html',status = 400,context = { 'status_code' : 400, 'message' : "400 Bad Request Error.", 'title' : "Bad Request" }) #in the urls.py (link 4 error handler) hanlder400 = "gotani.views.bad_request_error_view" handler404 = "gotani.views.page_not_found_view" handler403 = "gotani.views.forbidden_error_view" handler500 = "gotani.views.internal_server_error_view" So my problem is, when the project return HttpResponse404, the custom error page is not shown normally. How can i override the … -
Can I get some help to fix the error I'm getting in my hosted Django app on Heroku?
here is the link to my Django app on Heroku where you can review the error : https://get-udemy.herokuapp.com/ how can i fix it please? -
does Laravel have choices in model? like Django
I'm wondering does Laravel have something like Django choices in models? for example in Django: Django document class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) -
What's the best way to store multi-select checkboxes (with the same values each time) in Django (PostgreSQL)?
I've got and Item and each Item should be able to select options from 3 checkboxes, and these checkboxes have the same values between all of them. I'm not sure on the best way to organise/store this. It will come back as an array from the browser, request.POST.getlist('options[]') so I had been thinking of using a JSONField: options = models.JSONField() But was also wondering if it's better as a ManyToManyField? The only thing stopping me there is that it's always the same 3 values, so they'd need to be populated into the database manually. Any opinions? -
Django queryset : I have a Employee model with below fields
Class Employee(models.Model): name = models.CharField(max_length=100) age = models.CharField(max_length=100) salary = models.CharField(max_length=100) I need to write a queryset to fetch all the details with an additional field called Group. So Group will set "A" if salary is grater than 10000 else "B". -
type object 'Case' has no attribute '_meta'
I keep getting the above error when i try to access the following URL. What am i doing wrong here? http://127.0.0.1:8000/case_portal/cases/ Model Class: (models.py) class Case(models.Model): id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=255, null=True) status = models.CharField(max_length=255) receipt_number = models.CharField(max_length=255) description = models.TextField() Serializer Class: (serializers.py) class CaseSerializer(serializers.ModelSerializer): class Meta: model = Case fields = ['id', 'name', 'status', 'receipt_number', 'description'] View Class: (views.py) class CaseViewSet(ModelViewSet): queryset = Case.objects.all() serializer_class = CaseSerializer def get_serializer_context(self): return {'request': self.request} -
Running Background task with possibility to check the current state?
I'm currently looking for an easy way to run a function that performs a shell command in the background and check if the task is still running or already completed. Short explanation of the goal: user calls a view the background function is triggered if the user calls the view again, instead of triggering a new background job, the user is told that the job is already running. I have already read about celery, django-background-tasks and django-cronjobs. Celery feels like overkill for my task. django-background-tasks seems perfect but has no way to check the current progress of the task or? What is a simple way to achieve the goal? -
Query using related name in django
I've two models: class User(models.Model): email = models.EmailField() name = models.CharField(max_length=255) password = models.CharField(max_length=255) class Profile(models.Model): group = models.ForeignKey(User, related_name='profiles') image = models.ForeignKey(Media, on_delete=models.CASCADE) #more attributes I've user's id and I want to get his image. user = User.objects.get(id=id) image = user.profiles.image This is throwing error. How can I do it? Thanks in advance. -
Static files 404 django (docker+nginx)
Whats wrong in settings of static files? If start without docker and nginx - works fine. I trieed mannually collectstatic, but its not help settings.py import os from pathlib import Path, PurePath BASE_DIR = Path(__file__).parent.parent STATIC_ROOT = PurePath(BASE_DIR.parent, "static/") STATIC_URL = "/static/" nginx.conf events { worker_connections 1024; } http { sendfile on; upstream app_server { server django:8000; } server { server_tokens off; listen 80; add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Methods GET,POST,DELETE,PUT,PATCH,OPTIONS; add_header Access-Control-Allow-Headers X-Requested-With,Content-Type; location /static/ { alias /static/; expires 1y; access_log off; add_header Cache-Control "public"; include /etc/nginx/mime.types; } location / { root /var/www/contacts/static/; index index.html; } location ~ ^/(manage|categories|events|persons|swagger|redoc|events) { proxy_pass http://app_server; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } } part of docker-compose django: tty: true build: context: ../backend dockerfile: Dockerfile command: bash -c "poetry run gunicorn -c /etc/gunicorn/gunicorn.conf.py project.wsgi:application & poetry run python manage.py makemigrations & poetry run python manage.py migrate & poetry run python manage.py rundramatiq" container_name: contacts_django env_file: ../secrets/django.env depends_on: - postgresql image: contacts_django networks: - contacts_app_to_db ports: - 8000:8000 restart: unless-stopped volumes: - ../static:/static nginx: tty: true build: context: ../services/nginx/ dockerfile: Dockerfile container_name: contacts_nginx depends_on: - django env_file: ../secrets/nginx.env image: contacts_nginx networks: - contacts_nginx_to_app ports: - … -
django-simple-history3.1.1 error when cascade deletion
For a Django project I work on, I use django-simple-project to get a history of each of my models. Everything works very well when I create, modify or delete an object, the library generates a <HistoricalObject> each time. My problem is when I perform a cascade deletion. For example, I have a table B that inherits a table A. When I delete an object from my table A, it also deletes all its related objects in table B. Django-simple-history generates a <HistoricalObject> for my table A's object but for the B's it is a "corrupted" object with "formating error" because the deleted B object refers to an A object that no longer exists and this create an error. I can't even read the <HistoricalObject> of B when i query it. The error is : MyApp.models.tableA_object.DoesNotExist: tableA_object matching query does not exist. I haven’t found anything on the forums about it and it really blocks me, I can’t do without cascade deletion and django-simple-history meets all my needs except this one. Some infos : Django 4.0.3 django-simple-history 3.1.1 MySql Python 3.9.7 Thank you for your help -
Convert file path to url using CharField
I have a charfield model. All of charfields is a path to some file how to convert this paths to url. The path is relative to the media folder. Thanks in advance!!! -
Django - how to persist selected language throughout session?
I have a multi-page art gallery app that supports Japanese and English with Japanese being the default language on startup. In the header I have a button that should append the url with the selected language between English and Japanese. When the button is clicked, my app redirects to the homepage and displays the page with the new translated content. However, while in that new language, when I navigate to a different page within my app, it renders the page in Japanese, even if English was chosen. How can I persist the chosen language throughout the session regardless of where I navigate to? Do I need to pass the language as a parameter in my view? If so, how to do that? I've read the relevant Django docs but they didn't have an answer to this kind of problem. Thank you! index.html a tag button: {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'ja' %} <a href="/en/" role="button"> English </a> {% else %} <a href="/ja/" role="button"> 日本語 </a> {% endif %} Main Project urls.py: urlpatterns += i18n_patterns ( path('', include('Art_Gallery_App.urls')), path('admin/', admin.site.urls), prefix_default_language=True ) Art_Gallery_App urls.py: urlpatterns = [ path('', views.index, name='index'), # by default, URL looks like this: … -
How to add headers into iframe src?
I have html like this: <iframe src="https://google.com" width="450" height="200" frameborder="0"></iframe> I need to add headers into src. How to do it? My app in Django. -
Cant delete folder after creating it with PyPDF2 - Python 3.10.1 and Django 4.0.6
Im creating a folder with PDF Files in it. Im using PyPDF2 in Django. It works all fine, the folder with the files in it is created. But after that, i cant delete it without stopping the running server. It throws an error saying the file is used by another application. Do anyone know how i can fix that problem? Here is the code snippet, which creates the folder with the pdf files in it: # Merge Befunde for folder in os.listdir(os.getcwd()): mergeFile = PyPDF2.PdfFileMerger() for filename in os.listdir(os.getcwd() + "\\" + folder): if filename.endswith(".pdf"): file = os.getcwd() + "\\" + folder + "\\" + filename try: mergeFile.append(PyPDF2.PdfFileReader(file)) except: print("Error in", file) else: continue mergeFile.write(folder + ".pdf") mergeFile.close()