Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save Django Website State across all browsers the app is accessed at
I have created a Django webiste which fetches data on a realtime basis through view and renders to the Html Template, I am already running serveral ajax queries to refresh my specific views to render and display data every second, but now i have a bigger problem which is to maintain the same state of the template accross all the browsers the Django server is accessed at. For example If user 'A' logs in and do certain operations on the webiste which changes the states of tables in my pstgres, and after an hour user 'B' logs in with same credentials he should be able to see the same operations running but right only the raw template is visible to user 'B'. I have created the middleware using postgres. I am not getting the solution to this since a long time now. I tries using ajax to call every view once but i don't think this solution is a long term because as more views get added more and more ajax calls will slow down the system. -
GraphQL I am trying to get a list based on a variable and getting "Expected Iterable, but did not find one for field 'Query.reservationsByPlace'."
Initially, I had a problem with the error: There is no current event loop in thread 'Thread-2'." but after adding async to the resolver code another error appeared: "Expected Iterable, but did not find one for field 'Query.reservationsByPlace'." There is Query and resolvers: class Query(graphene.ObjectType): prices = graphene.List(PriceType) tours = graphene.List(TourType) users = graphene.List(UserType) reservations = graphene.List(ReservationType) reservations_by_place = graphene.List(ReservationType, place=graphene.String()) def resolve_prices(root, info, **kwargs): return Price.objects.all() def resolve_tours(root, info, **kwargs): return Tour.objects.all() def resolve_users(root, info, **kwargs): return User.objects.all() def resolve_reservations(root, info, **kwargs): return Reservation.objects.all() async def resolve_reservations_by_place(root, info, place: String): return Reservation.objects.all(place=place) GraphQl query: query GetReservationByTour($tour_place: String!) { reservationsByPlace(place: $tour_place) { id tour { id place } } } and full error: { "errors": [ { "message": "Expected Iterable, but did not find one for field 'Query.reservationsByPlace'.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "reservationsByPlace" ] } ], "data": { "reservationsByPlace": null } } I've already tried changing from all to get and from Field to List etc. -
How to get confirmation from rabbitmq after publishing a message
I'm trying in python to get an acknowledgment from rabbitmq after publishing a message to a queue. I am using this example for test. https://pika.readthedocs.io/en/stable/examples/blocking_delivery_confirmations.html But the desired result is not obtained. -
no errors thrown when running pipenv install, but running a python manage.py migrate after results in errors
ModuleNotFoundError: No module named 'django_on_heroku' I've got a new machine at work and I'm attempting to run an old project which I've cloned. Cannot get the api server up and running. (ps, my first stack overflow post -- sorry if the format isn't great or specific enough!) Have tried installing django on heroku in the pipenv - that is sucesfull, the error reoccurs though on the next dependency when i attempt a migrate and then run server. -
Django is showing me a 404 error instead of my image
my friends, this is my first question here. So, I follow the Django documentation and some questions here, but the problem keep happening. I did what was said on other similar questions, like this one, for examaple: Issue with image in django But the problem persists. So, my model looks like this: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True) picture = models.ImageField(blank = True, null = True, upload_to = user_directory_path) whatsapp = models.PositiveIntegerField(blank = True, null = True) My settings looks like this: MEDIA_ROOT = f"{BASE_DIR}/media" MEDIA_URL = '/media/' I added + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) to the end of my urls.py file. The folder and images are being created on my file system when I add them via the admin, but when I click to see them over there I recieve a 404. admin screen error screen I am making a mobile app and serving my data using Django Rest Framework, the images are the only thing giving me a headache right now. -
React, Django and FastAPI architecture
My team is developing a platform where our clients upload data through an API (typically once per hour). The data is analyzed and then made accessible through a web/dashboard of sorts. I don't have experience with Django/React so I'm struggling to understand how a good architecture should look like combining the following tools/frameworks: React for frontend Django as our web-server FastAPI as the API to upload data (and as DB access layer) (Note: FastAPI will run separatly - Django and FastAPI communicate through HTTP/JSON) My struggle is this: Do I need django? Can I just use React and the expose all data through FastAPI? Should I throw out FastAPI because I'm using Django anyway? (for API's FastAPI is so much better imo) The original idea was to have no public APIs and only allow our clients to upload data through our data upload API from specified IP addresses with authentication. Only our web-server should access our internal API's to serve data back to our dashboards. Is that an overdesign? Im running with the assumption that Django REST and authentication support is superior to using just React/FastAPI to service web-pages. The FastAPI is alread implemented based on current needs and the … -
How to override the default login for Django rest framework browsable API
I have a django rest fw application and when we are using the browable api page and click login it goes to default django login page. When I try to reach https://my-app/api/v1/getdetails and my login has expired, I get defaulted to this page: https://my-app/api-auth/login/ But the new login page i wan is this: http://my-app/signin/ the auth is done by Okta in the application. I did try overriding this LOGIN_REDIRECT_URL = '/signin/' LOGIN_URL = '/signin/' -
add ordinal number to django admin list_view
I want to add an ordinal number for each row in in list view in the admin panel for my models. I tried adding something like this in my MYModelAdmin(ModelAdmin) line_numbering = 0 def line_number(self, obj): self.line_numbering += 1 return self.line_numbering but i add more and more numbers, is there an easy way to add an ordinal number without adding a field to your model ? -
fastAPI send data to list of user
I am trying to create an endpoint where admin has created orders and team leader(tl) has list of employees, whichever employees the tl selects a set of 60 orders has to be send to that employees ps : this is my first time creating an api, by far i have written this @app.get('/send-order-to-emps-from-tls') def Send_orders_to_emps(id:List[str]=Query(None, alias="Id"),userid=Depends(auth_handler.auth_wrapper)): emp_id=userid emp_data=user_collection.find_one({"_id": ObjectId(emp_id)}) if(emp_data["tl_id"]==""): all_order=[] order_created_by_admin=order_options_by_admin_collections.find() for order in order_created_by_admin: order.parse_json(order) all_order.append(order) -
each time button clicked print string html/python django
I would like to to print a string each time somebody clicks the like button. the string would get a new line each time. so it would look like tis for example: like like like like like like --> adding one row with the string every time i click the button It is already possible to like/dislike and the number of each is saved within the post. Here is the views.py def like_post(request): post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) new_like = LikePost.objects.create(post_id=post_id) new_like.save() post.number_of_likes = post.number_of_likes+1 post.save() return redirect('/') def upload(request): if request.method == 'POST': image = request.FILES.get('image_upload') caption = request.POST['caption'] num_post = Post.objects.count()+1 new_post = Post.objects.create(image=image, caption=caption, num_post=num_post) new_post.save() return redirect('/'), folder_path else: return redirect('/') models.py: I would love to put have the line to create the string in here, so that I can just transfer that to the html form, just as i put in all the other values of the post. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) num_post = models.IntegerField(default=0) image = models.ImageField(upload_to=post_images) caption = models.TextField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) number_of_likes = models.IntegerField(default=0) number_of_dislikes = models.IntegerField(default=0) interaction_count = models.IntegerField(default=0) def __str__(self): return self.caption class LikePost(models.Model): post_id = models.CharField(max_length=500) def __str__(self): return self.post_id this is the html part of … -
Django- how to save formset model
I have the following view code def edit_pal(request,pal_id): pals=palabout.objects.get(id=pal_id) form2=editpalForm(request.POST or None,instance=pals) RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0) formset = RecipeIngredientFormset(request.POST or None,prefix=pals) context={ "formset": formset, "form2":form2, "pals":pals } if request.method == 'POST': if form2.is_valid() and formset.is_valid(): parent = form2.save(commit=False) parent.save() for form in formset: child = form.save(commit=False) child.recipe = parent child.save() context['message']='Data Saved' return redirect('hod:manage_pal') return render(request,"edit-pal.html",context) I have used formset so why isn't saving file or details show? Can anyone help this? -
Problem with database when I use .env file
When I try to migrate some changes on one of the models I get this error but only when I use env. file in settings.py django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. My setting.py DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } My .env file # DB DB_ENGINE=django.db.backends.postgresql DB_NAME=db DB_USER=user DB_PASSWORD=password DB_HOST=127.0.0.1 DB_PORT=5432 My Pucharm .env settings enter image description here When I set up my settings.py back to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } I don't have any problems to migrate. -
can't work with vscode python django html autocomplete features not working
first I created a project to work with django, but when I add index.html to it it doesn't autocomplete! When I type, nothing comes up, I also get an error like "This extension is deprecated because it is no longer maintained". "!" in the html files of my codes. When I put the tick I wanted autocomplete but it didn't happen and I searched a lot and couldn't find any result. I would be glad if you help. -
How to manage static files in Django
First I created a "static" folder and added a css file in this folder. Then I added "STATIC_ROOT = BASE_DIR / 'myStaticFiles'" in the 'settings.py'. I followed a tutorial. I run this command: py manage.py collectstatic All the files copied to 'myStaticFiles'. Now, it's my question: Should I add more css files in the 'static' folder or 'myStaticFiles'? It's a bit confusing to me. Django Tutorials I followed the tutorials step by step, but didn't get the result. Explained as above. -
Redirect URL with forward slash part to other URL with the same domain
I have a following url, which leads to server "A": abc.com/en/about Then, when user hits the next url, I need it to lead to server "B": abc.com/fr/about As you can see these are two same domains and different after slash. The idea is that one server has new code and the other old one. Normally I would use nginx rewrites rule for this. However, now I'm in a situation when Divio platform is being used and I don't have an access to underlying webserver. They only provide DOMAIN_REDIRECTS env variable, which I don't understand how to apply in such a situation. -
Unknown column 'gameApp_questions.id' in 'field django
hi everybody i make a quizz app in django i make choose 6 questions from database in views.py question_list = Questions.objects.filter(grade=15,subject=2).order_by('?')[:6] for i, question in enumerate(question_list): question.point = i + 1 question.save() context['questions'] = question_list return context and i have a eror mesage OperationalError at /gameApp/gameplay (1054, "Unknown column 'gameApp_questions.id' in 'field list'") -
django template rendering error when template have comparison 'equal'
I got problem about template rendering in django. It's show up when there is kind of integer comparison with '=='. I have a view like .. def mailtemplate_GetSchema(request, id=None): if id == None: svars = [] this_var = {} this_var['s_id']=str(uuid4()) this_var['varname'] = f"varname_{this_var['s_id']}" this_var['varlabel'] = f"varlabel_{this_var['s_id']}" this_var['vartype'] = f"vartype_{this_var['s_id']}" this_var['varformat'] = f"varformat_{this_var['_sid']}" this_var['varname_value'] = '' this_var['varlabel_value'] = '' this_var['vartype_value'] = 1 this_var['varformat_value'] = '' svars.append(this_var) return render(request, 'mailtemplate_all.html', {'svars': svars}) try : obj = MailTemplate.objects.get(pk=id) schema = obj.schema schema = json.loads(schema) # it's a list of dictionary vars = [] for s in schema: this_var = {} this_var['field_id']=str(uuid4()) this_var['varname'] = f"varname_{this_var['field_id']}" this_var['varlabel'] = f"varlabel_{this_var['field_id']}" this_var['vartype'] = f"vartype_{this_var['field_id']}" this_var['varformat'] = f"varformat_{this_var['field_id']}" this_var['varname_value'] = s.get('name','') this_var['varlabel_value'] = s.get('label','') this_var['vartype_value'] = s.get('type',1) this_var['varformat_value'] = s.get('format',None) if this_var['varformat_value'] == '': this_var['varformat_value']=False vars.append(this_var) print(f'VARS:{vars}') return render(request, 'mailtemplate_all.html', {'vars': vars}) except MailTemplate.DoesNotExist: return HttpResponseNotFound() the 'mailtemplate_all.html' is : {% for v in vars%} <div id={{ v.field_id }} class="divTableRow"> <div class="divTableCell"> <input type="text" name={{v.varname}} value={{ v.varname_value}} class="vTextField" maxlength="20" > </div> <div class="divTableCell"> <input type="text" name={{v.varlabel}} value={{ v.varlabel_value}} class="vTextField" maxlength="20" > </div> <div class="divTableCell"> <select name={{v.vartype}}> {% if v.vartype_value==1 %} <option value=1 selected> {% else %} <option value=1> {% endif %} Integer</option> {% if v.vartype_value==2 %} <option value=2 … -
My custom templates for 404 page not working in Django
I've been trying to use my custom 404- and 403 pages for my django project and I used code for it that I already used in other projects, but somehow it's not working yet. This is my function: def error_404(request, exception): return render(request, 'main_app/errors/404.html', status=404) And this is where i call the function in the urls.py: handler404 = 'main_app.views.error_404' This is my 404.html: {% extends "../base.html" %} {% load static %} {% load i18n %} <html> <header> {% block title %}<h1>404 - {% trans "Page not found" %}</h1>{% endblock %} </header> <main> {% block content %} <p>The page your looking for could not be found</p> {% endblock %} </main> </html> The pathes should actually be fine, since I used render(template_name=) alot in this project and I just copied it and changed the file name. I also set the DEBUG=False in the settings.py Does anybody have an idea? -
How to combine two or more QuerySets from different models and order objects chronologically?
I have two querysets I need to combine and iterate through the objects chronologically, based on a datetime field which is common to both models. What is the best way to do that ? I'm able to combine querysets with union but objects are not sorted properly. model_combination = model_set1.union(model_set2, all=TRUE) -
NGINX Docker reverse proxy not working on server (Works locally)
I am running a Django app on Docker with Nginx, the configuration works perfectly locally but on the server, it doesn't. i get the error 502 Bad Gateway in the web page and the logs I get 2023/01/13 07:55:56 [error] 28#28: *1 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xxx.xx.xxx, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://xxx.xx.x.x:8000/favicon.ico", host: "xx.xxx.xxx.xxx", referrer: "http://xx.xxx.xxx.xxx/" This is how the configuration looks Dockerfile FROM nginx:1.23.3-alpine RUN rm /etc/nginx/conf.d/default.conf COPY ./default.conf /etc/nginx/conf.d/default.conf default.conf upstream apii { server api:8000; } server { client_max_body_size 20M; listen 80; location / { proxy_pass http://apii; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } # location = /favicon.ico { access_log off; log_not_found off; } location /api { proxy_pass http://apii; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /realestateadmin { proxy_pass http://apii; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /app/staticfiles/; } location /mediafiles/ { alias /app/mediafiles/; } } docker-compose.yml version: "3.9" services: api: build: context: . dockerfile: ./docker/local/django/Dockerfile command: /start volumes: - .:/app - static_volume:/app/staticfiles - media_volume:/app/mediafiles # ports: # - "8000:8000" expose: - 8000 env_file: - .env depends_on: - postgres-db networks: - real-estate postgres-db: image: postgres:12.0-alpine ports: - "5432:5432" … -
Timeout reading a post request containing heavy dictionnary
I am receiving a POST request containing a 3 mB Json dictionary. When i receive de POST, my view tries to read the args in the request but that causes a timeout on the Heroku server. When i try it locally, it works fine though. Here is the code: def send_request(): with open(file) as f: data = json.loads(f.read()) data = json.dumps(data) response = requests.post(url=url_recette, data=data) return response @csrf_exempt def view(request): print('the server gets here') _args = json.loads(request.body.decode('utf-8')) print('the server never gets here so the timeout occurs when i load the args') error on Heroku => Jan 13 09:00:03 gestion-ugip-recette app[web] INFO [2023-01-13 09:00:03 +0100] [18] [INFO] Worker exiting (pid: 18) Jan 13 09:00:03 gestion-ugip-recette heroku[router] error at=error code=H13 desc="Connection closed without response" method=POST path="/resiliation/api_get_requete_from_ak" host=gestion-ugip-recette.herokuapp.com request_id=ccd0a85b-8454-458d-90f8-ab9a59a203fb fwd="83.205.21.231" dyno=web.1 connect=0ms service=30826ms status=503 bytes=0 protocol=https Jan 13 09:00:04 gestion-ugip-recette app[web] INFO [2023-01-13 09:00:04 +0100] [26] [INFO] Booting worker with pid: 26``` Has anyone an idea of what could be the problem? thx in advance. -
Unable to apply migration on altered model in django
I am new to django. I have changed some fields in my already created Django model. But It says this message when I try to apply migrations on it: It is impossible to add a non-nullable field 'name' to table_name without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. Although I have deleted the data of this table from database. I cannot set it's default value because the field has to store unique values. Do I need to delete my previous migration file related to that table? -
How to hide the column assigned to "list_display" and "list_display_links" for "list_editable" in Django?
I have Person model below: # "store/models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) Then, I assigned "first_name" and "last_name" to list_display and list_editable to make them editable as shown below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ("first_name", "last_name") # Here list_editable = ("first_name", "last_name") # Here Then, I got the error below: ERRORS: <class 'store.admin.PersonAdmin'>: (admin.E124) The value of 'list_editable[0]' refers to the first field in 'list_display' ('first_name'), which cannot be used unless 'list_display_links' is set. So, I assigned "id" to list_display and list_display_links as shown below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here list_display = ("first_name", "last_name", "id") list_editable = ("first_name", "last_name") list_display_links = ("id", ) # Here Then, the error was solved and 3 columns were displayed as shown below. Now, I want to hide the 3rd column "ID" which I don't need: So, how can I hide the 3rd column "ID"? -
Difference between patch at /product/ vs /product/{id} Django Rest Framework
I am trying to make a project, which allows creating a patching a product model. Everything works fine according to all my code when I put the patch request for that object at /product/ Payload tried : { "id": 46, "name": "DBZ", "created": "2022-12-08T12:48:48.232455Z", "max_nodes": 22, "allowed": false } And I get validation field 422 error with "detail": "Please enter only the whitelisted fields" which is expected. But when I put patch request in /product/46 with payload: { "name": "DBZ", "created": "2022-12-08T12:48:48.232455Z", "max_nodes": 22, "allowed": false } I get a 200 OK message and the object with that id gets patched. I am new to this DRF, can someone let me know what is happening here. models.py class Product(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=256) max_nodes = models.IntegerField() allowed = models.BooleanField(default=False) auto_delete = models.BooleanField(default=False) def __str__(self): """ The string to represent this object. We use the name field to provide a reasonable value in the Admin pages. """ return self.name serializers.py class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('id', 'name', 'created', 'max_nodes', 'allowed', 'auto_delete') views.py class ProductViewSet(viewsets.ModelViewSet): """ API Endpoint that allows patching product objects """ queryset = Product.objects.all() serializer_class = ProductSerializer def create(self, request): if request.user.is_anonymous: logger.warning("ANONYMOUS … -
Django 'ModuleNotFoundError: No module named 'my_app''
I have been working for some time in a project. One of the apps inside of it, 'my_app' has its models, views, forms, etc. working fine. It is included in INSTALLED_APPS as well. Now I try to create a new file inside the my_app folder to write some logic but can't import the models. I tried: from my_app.models import MyModel But I get this error: ModuleNotFoundError: No module named 'my_app' Also tried this one as I was doing the imports in, for example, views.py: from .models import MyModel But this time I get this error: ImportError: attempted relative import with no known parent package These imports are working fine in other files in the same folder. Recently I deployed the app to Railway, maybe that has something to do with this error? Why suddenly this error happened? EDIT: my_app/apps.py file: from django.apps import AppConfig class My_appConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_app'