Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
How to filter and order by with Sum while keeping the summed data in Django
OK..I even do not know how to describe the situation in the title. But considerate below models: class TheModel(models.Model): qty = models.IntegerField() name = models.CharField() type = models.CharField(choices=['A' ,'B', 'C']) The requirement is to get the sum of qty and sort by sum of qty, but also has sum of A, B, C. assume there are 5 rows in total: name, qty, type (name1, 3, A) (name1, 3, B) (name1, 4, C) (name2, 5, A) (name2, 10, C) The result should be like this: name sum_qty, type A, type B, type C name1 10 3 3 4 name2 15 5 0 10 -
Best practices for authenticating Django Channels
Django 4.1.4 djoser 2.1.0 channels 4.0.0 I have followed the documented recommendation for creating custom middleware to authenticate a user when using channels and I am successfully getting the user and checking that the user is authenticated though I am sending the user ID in the querystring when connecting to the websocket to do this. The user is not automatically available in the websocket scope. I am unsure if there are any potential security risks as the documentation mentions that their recommendation is insecure, I do check that the user.is_authenticated. So I believe I have secured it. I do believe that using the token created by djoser would be better though I am not sure how to send headers with the websocket request unless I include the token in the querystring instead of the user's ID. I am keen to hear what the best practices are. I am passing the user ID to the websocket via querystring as follows at the frontend: websocket.value = new WebSocket(`ws://127.0.0.1:8000/ws/marketwatch/? ${authStore.userId}`) middleware.py from channels.db import database_sync_to_async from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist @database_sync_to_async def get_user(user_id): User = get_user_model() try: user = User.objects.get(id=user_id) except ObjectDoesNotExist: return AnonymousUser() else: if … -
IntegrityError at /station/Add/ (1048, "Column 'user_type_id' cannot be null")
I'm trying to create new station using generic views when i try without user_type forigen key I received this error IntegrityError at /station/Add/ (1048, "Column 'user_type_id' cannot be null") if i tried without user_type and submit button cilck form automatic refresh and same clean Here is my code: station/views.py class StationCreateView(LoginRequiredMixin, CreateView): model = Station fields = ('station_name', 'station_address','connectors','status', 'start_time','end_time','open_day', 'state', 'city', 'area', 'user_type') template_name = 'owner/add_station.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) here is my code: add_station.html <form method="post" action="" novalidate> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.station_name|as_crispy_field }} </div> <div class="form-group col-md-12 mb-0"> {{ form.station_address|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.connectors|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.status|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.start_time|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.end_time|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.open_day|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.state|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.city|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.area|as_crispy_field }} </div> <button type="submit" class="w-full rounded-full bg-red-gradient p-3 text-white font-bold hover:ring">Add Station</button> </div> </form> -
HOW TO OUTPUT DATA GOT FROM combined queryset IN DJANGO TEMPLATE (html file)?
Am having a problem. And l request for your Help. Am having 3 apps in Django project action adventure others `#action/ models.py .... class Action(models.Model): name=models.Charfield() os= models.Charfield( choices=OS).... #adventure/models.py .... class Adventure(models.Model): name=models.Charfield() os= models.Charfield( choices=OS).... #Others/views.py from itertools import chain from action.models import Action from adventure.models import Adventure def windows_games(request): win_action = Action.objects.filter(os='windows') win_adventure = Adventure.objects.filter(os='windows') combined_list = list(chain(win_action,win_adventure)) context = ['combined_list':combined_list,] return render(request, 'others/os/windows_game.html' , context) #others/os/windows_game.html ..... {{combined_list.name}} 1). I need to correct me in #others/ views.py if there is any mistake done. 2). I would like to know how to know how to write the tag that outputs the results in #others/os/windows_game.html because I tried that but outputs nothing. And l would like to be in form of, #{{combined_list.game_pic}}, etc It needed to display all items created in those models to display in windows_game page, after filtering those that only follow in category of windows. I tried creating the context but there was no output results. -
Django ModelChoiceField with custom queryset not validating
My ModelChoiceField is not validating saying that the selected choice is not an instance. I am passing a custom queryset to my modelChoiceField that uses a custom manager (objects_sys) to return extra entries that are archived and do not normally display with normal queries. The entries are displayed and I can select them, but when the form posts and Django tries to validate, it must be using another query that filters out the archived items so those are not valid choices. I'm using class based views - this vails in form_valid() Models: class Item(models.Model): name = UpperCaseCharField(max_length=10, primary_key=True) description = models.CharField(max_length=200) class ItemLoc(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) location = models.CharField(max_length=200) My Form: class ItemForm(forms.ModelForm): class Meta: model = ItemLoc fields = ( 'item', 'location' ) def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['item'].queryset = Items.objects_sys.filter(qty_on_hand__gt=0) Do I need to pass this custom query in again to the ModelChoiceField at some point so that the extra values are available for validation? Thank you for your help -
Django select_related returning empty query set if the PK deleted from other table
Consider I am having a table that having a foreignkey relation with the user model. class MyModel(models.Model): created_user = models.ForeignKey(settings.AUTH_USER_MODEL) I am taking queryset like this qs = MyModel.objects.select_related('created_user').all() This query working fine , but if the user deleted from the database, then it is showing empty queryset. -
how to improve the reading time of files in an S3 bucket from Django?
I have a process in which I have to read several files from S3 to show them in a report. list_images = Inspection_File.objects.filter(inspection_id=inspection.pk).order_by('category__name') for image in list_images: image_data = image.file.read() #this process is very slow list_img.append({'file': img}) Analyzing the code I saw that the process of reading the file from the model is one that takes a long time, about 20 images take approximately 20 seconds, which is too long to wait, I understand that they are images, however, these images weigh less than 1MB, any ideas to improve the response time?