Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relational queryset not showing properly in template
I believe is a quite basic problem, but I'm trying to render in a template all the titles for an specific page, and inside that title its corresponding text. With these models: class Page(models.Model): page_title = models.CharField(_("title of the page"), max_length=50) category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.page_title class Category(models.Model): category_name = models.CharField(_("name of the category"), max_length=50) def __str__(self): return self.category_name class Title(models.Model): title = models.CharField(_("titulo"), max_length=50) page = models.ForeignKey(Page, on_delete=models.CASCADE) def __str__(self): return self.title class Text(models.Model): title = models.ForeignKey(Title, verbose_name=_("titulo de la pagina a la que pertenece"), on_delete=models.CASCADE, default='') content = models.TextField() def __str__(self): return f"{self.title}" I am using this view to render the logic: def index(request): pages = Page.objects.all() titles = Title.objects.filter(page__id=2) for title in titles: title_id = title.id texts = Text.objects.filter(title__id=title_id) context = { 'pages' : pages, 'titles' : titles, 'texts' : texts, } return render(request, 'index.html', context) But with this approach the texts only gives me the text of the last title when rendered this way in template: {% for page in pages %} <h1>{{page}}</h1> {% for title in titles %} <h3>{{title}}</h3> {% for text in texts %} <p>{{text}}</p> {% endfor %} {% endfor %} {% endfor %} The desired rendering would be all the … -
how do I remove repition of tags used in posts
I want to display the tags in a dropdown list. But the problem here is that same tags are being displayed per post. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> It would be handy if there are any JS script or anything else to avoid this repetition. Thanks! -
Debugging django project in docker-compose in VS code
I cannot tune debugging django project from docker-compose in VS code. Docker-compose: version: '3' services: helpdesk_web: build: context: ./ dockerfile: Dockerfile container_name: helpdesk_web volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media ports: - "8000:8000" - "5678:5678" env_file: - ./.env restart: always depends_on: - helpdesk_db helpdesk_db: image: postgres container_name: helpdesk_db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env ports: - "5432:5432" environment: POSTGRES_DB: something POSTGRES_PASSWORD: something POSTGRES_USER: something nginx: build: context: ./docker/nginx dockerfile: Dockerfile container_name: helpdesk_nginx restart: on-failure depends_on: - helpdesk_web - helpdesk_db ports: - "80:80" volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media volumes: postgres_data: media: DockerFile: FROM python:3.10 # Задаем рабочую директорию(app) внутри контейнера WORKDIR /usr/src/app # Запрещаем Python писать файлы .pyc на диск ENV PYTHONDONTWRITEBYTECODE 1 # Запрещает Python буферизовать stdout и stderr ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip # Копируем файл из рабочей директории на диске в рабочую директорию(/usr/src/app) контейнера COPY requirements.txt . RUN pip install -r requirements.txt # Копирует все файлы из рабочей директории на диске в рабочую директорию контейнера COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] launch.json: "version": "0.2.0", "configurations": [ { "name": "Django DEBUG", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/usr/src/app" } ], "port": 5678, "host": "0.0.0.0", }, { "name": "Python: Django", "type": "python", … -
How to deploy jupyter notebook development version using django in own website?
I am working on Jupyter Notebook and want to add only the retro version of it to my django app to run code on my website. I installed it using mamba(mambaforge) and build but where are the build versions or files stored or how do I launch only the retro version using Django URLs? I think it creates some js files like the Jupyter-lite version of it but didn't find where it is and how do I run it using my django app. -
Django runs on pm2 but nginx fails to start
We are running Django app using PM2 with following script: apps: [{ name: "app_name", script: "manage.py", args: ["runserver", "127.0.0.1:8000"], exec_mode: "fork", instances: "1", wait_ready: true, autorestart: false, max_restarts: 5, interpreter : "python3" }] } And we expect nginx to tunnel it to world. While nginx -t results ok but nginx fails to start. Following is the nginx configuration: upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 8000 default_server; listen [::]:8000 default_server; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/app_name/app_name/media; } # your Django project's static files - amend as required location /static { alias /home/django/app_name/app_name/static; } # Proxy the static assests for the Django Admin panel # Warning! This location is highly sensitive to how django is installed sys> location /static/admin { alias /usr/local/lib/python3.8/dist-packages/django/contrib/admin/static> } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://127.0.0.1:8000/; } } When we restart nginx with: sudo service nginx restart We get control process exited with error code. After debugging with journalctl -xe we get: The unit nginx.service has entered the 'failed' state with result 'exit-code'. Failed to start … -
django.db.utils.DataError: integer out of range
I have a Postgres Database in my django project. I have a model called enquiry class Enquiry(models.Model): product_name = models.CharField(max_length = 100) product_id = models.ForeignKey(List, on_delete = models.CASCADE) user_name = models.CharField(max_length = 100) user_email = models.CharField(max_length = 50) user_address = models.CharField(max_length = 200) user_mobile = models.IntegerField(default=0) And I createed a ffunction to create a new enquiry Enquiry.objects.create( product_name = product_name, product_id = product_id, user_name = user_name, user_email = user_email, user_address="None", user_mobile = user_mobile ) But I get an error django.db.utils.DataError: integer out of range how to solve this? -
how to store user details into database using serializers
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
how to run python file from flask and see the console output on the browser itself?
I have a python script suppose a+b=c. I want to run this script using flask from the browser and how to get the output of the python script in the browser itself. like a console in the browser. -
Django Rest API issue with retrieving correct information from urls. It is a Grandparent - Parent - Child relationship. How do I correctly map them?
I have been stuck on this problem for about 9 hours and am having trouble understanding the Grandparent - Parent - Child relationship with a One to Many Relationship(foreign key) in Django. I am currently creating an E-Commerce website and am trying to display the information in 4 different ways to fetch from my React frontend. I have 3 models setup: Category Subcategory (Foreign key to Category) Products (Foreign Key to Subcategory) This is the result I am attempting to create in my urls/views/serializer files: For some reason I can successfully retrieve at a granular level for a single product but as soon as I start going up nested models I am running into the following errors: Desired Result I have api/ included in the core urls folder already. I want JSON to display the information like this. # URLSearch api/Category/ # Category - # | # Subcategory 1 - # | # Product 1 # Product 2 # Subcategory 2 - # | # Product 1 # Proudct 2 I also want JSON to display the information like this. # URLSearch api/Category/Subcategory/ # Category - # | # Subcategory - # | # Product 1 # Product 2 Errors … -
How to Encrypt a Django Project inorder to deliver to a customer without seeing the code inside
I have a project which is a web application which is using Django framework which contains python and shell scripts in it. I wanted to Encrypt the package, so that the customers couldn't read/write what's there inside. Is there a way to encrypt the packages. -
Property of a self instance in Django Models?
recently i have created a model for storing some states in my DB. It's very simple i only store id and name. class PayType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) class Meta: ordering = ('-name',) def __str__(self): return "[{0}] {1}".format(self.id, self.name) Here you can see a migration where i insert default values in the DB. from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('stockmanager', '0023_pagotipo_remove_carrito_unidades_totales_and_more'), ] def insertPayType(apps, schema_editor): PayType = apps.get_model('stockmanager', 'PayType') PayType(name="Credit").save() PayType(name="Debit").save() PayType(name="Cash").save() operations = [ migrations.RunPython(insertPayType) ] As you can see, i'll have fixed rows in DB. I'd like to add properties in the PayType Model, in order to have easy access the instances of the model. Like a static attribute in java. class PayType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) class Meta: ordering = ('-name',) def __str__(self): return "[{0}] {1}".format(self.id, self.name) # I'm looking for something like this @property def CREDIT(self): return self.objects.get(self, id = 1) @property def DEBIT(self): return get_object_or_404(self, id = 2) @property def CASH(self): return get_object_or_404(self, id = 3) In order to acces in a diferent part of my code with this class Pay(models.Model): id = models.AutoField(primary_key=True) order_id = models.IntegerField() value = models.FloatField() pay_type = models.ForeignKey(PayType, on_delete=models.CASCADE) Pay( order_id = order_id, … -
Django - Auto populating Many-To-Many-Field relation
I am trying to make a form that auto populates a many-to-many relation for my user model. The goal is to have a submit button that adds the views instance object (the SingelWorkout object) to a many-to-many field relation within my user model. The view accurately displays the correct object, and the form appears as intended within the template. I do not wish for the user to see the many-to-many field selection. Aside from the submit button, I am trying to have all logic to occur on the backend. How would I assign an object instance to a field within a form? Would this occur in the views.py or the forms.py? Here is why my user model looks like: class FitnessUser(AbstractUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=60) age_category = models.ForeignKey( AgeGroup, on_delete=models.CASCADE, blank=True, null=True ) goal = models.IntegerField(default=1 ,choices=Purpose.choices) weight = models.CharField(max_length=30) height = models.CharField(max_length=30) gender = models.ForeignKey( Gender, on_delete=models.CASCADE, blank=True, null=True ) exercise_frequency = models.IntegerField(default=1 ,choices=Frequency.choices) template_id = models.ForeignKey( Workout_template, on_delete=models.CASCADE, blank=True, null=True ) completed_workouts = models.ManyToManyField(SingleWorkout) def get_absolute_url(self): return reverse('detail', args=[self.id]) This is my form in forms.py: class CustomWorkoutChangeForm(UserChangeForm): class Meta(UserChangeForm): model = FitnessUser fields = ('completed_workouts',) exclude = ('completed_workouts',) UserChangeForm.password = None This is … -
Field 'id' expected a number but got 'prashant'
I'm trying to get value of user field from my employee model but it's showing above error.I would request your solution to this problem.I have mentioned my models.py & views.py for reference. models.py class Employee(models.Model): First_Name = models.CharField(max_length=200,blank=False,null=False) Last_Name = models.CharField(max_length=200) DOB = models.DateField() Primary_skill=models.TextField(max_length=1000) user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) Employee_Id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,unique=True) views.py def loginp(request): page ='login' if request.method=="POST": username = request.POST.get("Username") password = request.POST.get("Password") name = Employee.objects.get(user=username) context={'use':name} try: username = Employee.objects.get(username=1) except: messages.error(request,"Invalid Username") user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return render(request,'profile.html',context) else: messages.error(request,"Authentication Failed.Please Try again with correct credentials") context={'page':page} return render(request,'login.html',context) -
Can't get attribute 'ModelCreation' on <module '__main__
I have started to machine learning deployment using Django. I have successfully create a model and dump it using pickle file .I also dumbed Column Transformer. when I load these file in Django project column Transformer works fine but model file gives error like this . "Can't get attribute 'ModelCreation' on <module 'main" . I searched many places but I could not solve it . -
how to receive array of int's in django form modelmultiplechoicefield
here is my multiselect(vue js) value at template: .... <input type="hidden" name="related_parties" id="id_related_party" :value="[3]"> .... in the above code , :value is actually a vue js computed value , for simplicity using [3] .. in my django forms, my field is: ... related_parties = forms.ModelMultipleChoiceField( required=False, queryset=Party.objects.none()) ... in the Django form later I loop through the values received from template to create a list like below: ... for item in self.initial.get('related_parties'): "" if item.id: party_ids.append(item.id) ... afterwards i assign the queryset value in Django form like below: ... if party_ids: self.fields['related_parties'].queryset = Party.objects.filter(id__in=party_ids or None) else: self.fields['related_parties'].queryset = None ... this setup works great if its just :value="[3]" ,,, but in case of different values like "[3,2]", i end up getting validation error: "3,4" is not a valid value. do i have to use a different django field in django forms? how can i avoid the validation error in this case? -
React env could be dynamic with django?
Frontend: React Backend: django Description I use create-react-app For example, one of component is below # link is from .env <a href={link}></a> After React application is finished. I use npm run build So, link will always be same I want to thak link could be autmatically change to where I deployed on server e.g. # lab1 <a href="100.100.100.1"></a> # lab2 <a href="100.100.100.2"></a> This scenario happend if I doployed in lab1, lab2, lab3 ,labs all have their own ip. I need to change that IP in React application .env file and re-build again. So, if there are n labs, I need to re-build n times. Is this possible do not build anymore? -
Django request.data is giving wrong JSON
I send a request to the server with {"name" : "Robert"} but the request.data looks different. This works fine in runserver. But when used uwsgi in docker it gives something like, { "_content_type": "application/json", "_content": "{"name":"robert"}" } -
What is the best way to receiving data and polling it
My scenario is a webhook and a polling. Explaning... I have a view that receive a post with a json like {"status": "processing"}. And I need to make the value of this field available for another system polling the data. My idea is make a new endpoint for GET. But I no have idea of the how to make this value available? Need I create a table to save this data? Can I uses cache? -
Django model form with field not existing in model
I am using Django 3.2 I have a model like this: class BannedUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="ban_info") reason = models.PositiveSmallIntegerField(choices=BANN_REASON_CHOICES) banned_at = models.DateTimeField(auto_now_add=True) expiry_date = models.DateField(null=True, blank=True, help_text=_('Date on which ban expires')) I want to create a form that instead of asking user to select a date, simply asks the user to select the Ban duration. The form will then calculate the expiration_date in the clean() method. BAN_DURATION_3_DAYS=3 # ... BAN_DURATION_CHOICES = ( (BAN_DURATION_3_DAYS, _('3 Days')), # ... ) class BannedUserForm(forms.ModelForm): class Meta: model = BannedUser fields = ['reason', 'ban_till'] The form field ban_till is a PositiveInteger that maps to the number of days. The intention is then to calculate the expiry_date from today by offsetting the integer amount. I suppose one way would be to: create a dynamic field ban_till add field expiry_date to the form field list (but somehow prevent it from being rendered) in the form's clean() method calculate the expiry_date and update that field How to create a form to display field that does not exist in Model? My solution: class BannedUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['ban_till'] = forms.IntegerField(widget=forms.ChoiceField()) super().__init__(*args, **kwargs) class Meta: model = BannedUser fields = ['reason'] Is this the correct way to … -
django.db.utils.OperationalError: connection to server at "database" failed: FATAL: sorry, too many clients already
I had a spike of this error in my Django application: django.db.utils.OperationalError: connection to server at "name-of-the-db" (172.17.0.11), port 5432 failed: FATAL: sorry, too many clients already My Django app is deployed on dokku and connected to a postgres database. The connection to the db is achieved using dj-datbase-url package and the setting looks like this: DATABASES = { "default": { **dj_database_url.parse( os.environ.get("DATABASE_URL", False), conn_max_age=600 ), "ATOMIC_REQUESTS": True, } } I use daphne in front of Django, and I’m running 3 processes with daphne. What could have been causing this issue? I have read that a possible solution is to drop the conn_max_age parameter or set it to a lower value, but I’m not sold on it and don’t completely understand how it works, so any guidance is welcome. Also, I haven’t registered any abnormal traffic on my website, but I’m wondering: is this something that can happen “spontaneously”, maybe due to an incorrect setup, or could it be due to malicious activity? The most likely explanation I can think of is there is some database connection leaks around my app, but I can’t figure out how to find them. -
Django Dynamically add choices to choicefield form
I would like to dynamically add choices to the form from data pulled in views.py. this list will change frequently so I can't hard code this. I'm running a query against the AWS API, and pulling down backups. I am trying to get these backups in a list then get these in a dropdown to submit in a form. forms.py class RestoreAMIForm(forms.ModelForm): ami = forms.ChoiceField() def __init__(self, *args, **kwargs): super(RestoreAMIForm, self).__init__(*args, **kwargs) self.fields['server_name'].widget.attrs['readonly'] = True self.fields['module_name'].widget.attrs['readonly'] = True self.fields['instance_id'].widget.attrs['readonly'] = True class Meta: model = RestoreRequest fields = ['server_name', 'module_name', 'instance_id', 'ami', 'justification'] views.py amis = helper_functions.get_all_backups(instance_id, GlobalrunEnv) context['ami'] = amis just_amis = [i[0] for i in context['ami']] formatted_picker = helper_functions.iterate_over_list(just_amis) context['restore_ami_form'] = RestoreAMIForm(initial={'server_name': context['tags']['Name'], 'instance_id': context['server_details']['InstanceId'], 'module_name': context['passed_slug'], 'ami': formatted_picker, }) html <form action="{% url 'instance_details' passed_slug %}" method="post"> <p class="standout"> Revert to Snapshot:</p> <table> {{ restore_ami_form.as_table }} </table> <div class="buttonHolder"> <button name="RevertRequest" value="{{ GlobalrunEnv }}">Submit New Values</button> </div> </form> the output of format_picker is... [('1', 'ami-04e05d8b305348d89'), ('2', 'ami-0f82b7ac27bdeb246'), ('3', 'ami-0eed0d484f0d61391'), ('4', 'ami-071cfbc9eda4cae4d'), ('5', 'ami-0dc61e733721e7e7a'), ('6', 'ami-05ba2995c14da2502'), ('7', 'ami-01cb5e766d77f8ecb')] my read only fields are working. Is is possible to provide initial= values for choice fields? -
Django complex filter with two tables
I am in need of some help. I am struggling to figure this out. I have two models class Orders(models.Model): order_id = models.CharField(primary_key=True, max_length=255) channel = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.order_id) class Meta: managed = False db_table = 'orders' class OrderPaymentMethods(models.Model): id = models.CharField(primary_key=True, max_length=255) payment_type = models.CharField(max_length=75, blank=True, null=True) fk_order = models.ForeignKey('Orders', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'order_payment_methods' My goal is to count the number of orders that have a OrderPaymentMethods specific payment_type Example: orders = Orders.object.filter(Q(channel="Green_House")) method_money = orders.filter(payment_methods = "credit").count() How can I get the count based on the orders that were filtered? Thank You -
Create sub category using jquery ajax when selecting a category in Django
I have a problem that when I select a category, sub categories are not showing or showing default option only. I want to show sub-categories about what the user category selected. This is my html code <div class="container pt-5" style="height: 800px !important;"> <div class="mx-auto" style="width: 500px" ;> <form id="form" action="../message/" method="post" name="contactForm" class="form-horizontal" data-subCat-url="{% url 'ajax_load_subCats' %}"> {% csrf_token%} <div class="col-xs-8 col-xs-offset-4 mt-5"> <h2 style="text-align:center;">Contact</h2> </div> <div class="form-group"> <label class="p-2" for="title">Title</label> <input type="title" class="form-control" name="text" id="title" placeholder="Enter A Title" required="required"> </div> <div class="form-group"> <label class="p-2" for="category">Category</label> <select class="form-select" aria-label="Default select example" id="category" required> <option selected>Select a category</option> <option value="theft">Theft</option> <option value="assault">Assault</option> <option value="accident">Accident</option> <option value="fire">Fire</option> </select> </div> <div class="form-group"> <label class="p-2" for="category">Sub Category</label> <select id="subCat" class="form-select" aria-label="Default select example" required> </select> </div> <div class="form-group"> <label class="p-2" for="subject">Subject</label> <textarea type="text" class="form-control" name="subject" cols="30" rows="10" placeholder="Enter Subject" required="required"></textarea> </div> <button type="submit" class="btn btn-primary float-end mt-2">Send</button> <br /> <div class="form-group"> {% for message in messages %} <div class="alert alert-danger" role="alert"> {{message}} </div> {% endfor %} </div> </form> </div> </div> I didn't add html tags like body, head, html, so the problem is not there. This is my Jquery script $(document).ready(function(){ $("#category").change(function(){ const url = $("#form").attr('data-subCat-url'); const catName = $(this).children("option:selected").val(); console.log(url) console.log(catName) $.ajax({ url: … -
How to use some variable that call a function to put inside of HTML template in DJANGO
I need to use that function below, here is in util.py try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None ``` Then I put that in my views.py with the var "get" def getFunction(request): return render(request, "encyclopedia/index.html", { "get": util.get_entry() }) So I want to use that function in my index.html {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href="{% get %}"><li>{{ entry }}</li></a> //{% get %} doesn't work {% endfor %} </ul> {% endblock %} The only for is to show up a list with 5 items and inside of li, using entry I can display all five items (e.g: apple, banana, tomato, pear, grape) I need to use href because When I click it will to another folder/file .md that will be writed about apple for example I wanna use that function to take in my file .md If you need more informations just ask me. thank u. :) -
Get url param in django
I have this view: @login_required def newAnswer(request, id): post = Post.objects.get(id=id) form = AnswerForm(request.POST) if request.method == 'POST': if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.post = post obj.save() form.save_m2m() return redirect('main:post', id=post.id) else: return render(request, 'main/newAnswer.html', { 'form': form, 'formErrors': form.errors, 'userAvatar': getAvatar(request.user)}) else: return render(request, 'main/newAnswer.html', {'form': form, 'post': post, 'userAvatar': getAvatar(request.user)}) When i try to post without loging in, it redirects me to "/accounts/login?next=/post/answer/new/81". My question is how can i get the "next" param in my login view thanks!