Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What changes to do to get more objects instead of one?
I am doing a project for my college work. In that, I need to change a function. That function is giving error saying multiple objects returned. The function works well if there is only one object to return. But I need to change it to return it to return all the objects. So what changes do I need to do. I am attaching the function code. Pls provide the code to modify also. I am just beginner in coding. Thanks I am using Pycharm, Django and. MySQL to do my project def vpay(request) : b=request.session['uid'] ob=TurfManager.objects.get(t_id=b) bb=ob.tf_id obj=Booking.objects.get(tf_id=bb) nn=obj.b_id o = Payment.objects.filter(book_id=nn) context = { 'obval': o, } -
How do I display my database models as a table form Django
from email.policy import default from django.db import models import uuid # Create your models here. class Brazzaville(models.Model): city = models.CharField(max_length=100) twenty = models.CharField(max_length=100) fifty = models.CharField(max_length=100) hundred = models.CharField(max_length=100) id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key= True, unique= True) def __str__(self): return self.city,self.twenty,self.fifty,self.hundred ``` from django.shortcuts import render from django.http import HttpResponse # Create your views here. from .models import Brazzaville def services(request): brazzaville = Brazzaville.objects.all() tb = {'brazzaville':brazzaville} return render(request, 'expresscargo/services.html',tb ) <br/> {% extends 'index.html' %} {% block content %} {% for city in brazzaville %} {{city.city}} {% endfor %} {% for city in brazzaville %} {{city.twenty}} {% endfor %} -
Self-incrementing primary keys, values that follow or not. Foreign key bindings (django)
Salvation, I am making a classic bdd and I had a doubt expressed by another dev: To put it simply, I have 2 tables (with very very few updates), one of which has an FK (foreign key) on the other. There is an autoincrement on the PK (primary key). With Django I make fixtures (basic filling) to fill these 2 tables and I put the following PK values: id | codes | name | zone_id 1 | 13 | bla1 | 1 2 | 84 | bla2 | 2 3 | 06 | bla3 | 4 Simple, basic. But this colleague changed my fixtures because it's "better", maybe for convenience: id | codes | name | zone_id 13 | 13 | bla1 | 1 84 | 84 | bla2 | 2 6 | 06 | bla3 | 4 As a result, the values of the PK no longer follow each other. Is this correct?, or should the auto-increment be removed?. For me it's completely absurd to have changed that. Thank you F. -
i am passing none value
from django.shortcuts import render from django.db.models import Q from shop.models import Product def search(request): products=None query=None if 'q' in request.GET: query1=request.GET.get('q') products=Product.objects.all().filter(Q(name__contains=query) | Q(description__contains=query)) return render(request,'search.html',{'query':query,'products':products}) this is my code i always get a none value for products and query -
Sending an email with attach file and render it in HTML on Django 4
I make a website on django 4, and i have a form with many inputs. I want to send an email in HTML format and attach at my mail the file "a photo". I have make the code and i have read many subjects on stackoverflow with no success. This is my forms.py: class FantasyForm(forms.Form): madame = forms.CharField(label="Madame", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Madame *'})) monsieur = forms.CharField(required = False, label="Monsieur", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Monsieur'})) age = forms.ChoiceField(required = True, choices=YEAR_CHOICES, widget=forms.RadioSelect()) photo = forms.ImageField(required = True, label="Une photo ?", widget=forms.FileInput()) site_q = forms.ChoiceField(required = True, label="As tu un pseudo sur un site de rencontre ?",choices=SITE_CHOICES, widget=forms.RadioSelect()) site_c = forms.ChoiceField(required = False, label="Sur lesquels ?",choices=SITE2_CHOICES, widget=forms.CheckboxSelectMultiple()) site_pseudo = forms.CharField(required = False, label="Votre pseudo", help_text="", widget=forms.TextInput()) rech_tu = forms.ChoiceField(required = True, label="Que recherche tu ?",choices=RECHTU_CHOICES, widget=forms.CheckboxSelectMultiple()) content = forms.CharField(label="Parle nous de ton fantasme (1000 caracteres maxi)", help_text="", widget=forms.Textarea()) when = forms.DateTimeField(label="Quand ça ?") phone = forms.CharField(label="Téléphone", help_text="", widget=forms.TextInput()) email = forms.CharField(required = False, label="Email", help_text="", widget=forms.TextInput()) class Meta: fields = ('madame', 'monsieur','age','photo','site_q','site_c','site_pseudo','rech_tu','content','when','phone','email') And this is my views.py: def page_fantasme(request): if request.method == "POST": form = FantasyForm(request.POST,request.FILES) if form.is_valid(): madame = request.POST.get('madame', '') monsieur = request.POST.get('monsieur', '') age = request.POST.get('age', '') photo = request.FILES.get('photo', … -
Django forms: dynamic adding new input fields due to already entered data
I'm new in django. I have created a simple model and now my goal is to build form where i would like to input information about particular objects. In these example i have model which contains two types totally different products. Common are only name and color. Is there any way in django to display form that includes only common fields. In this example name ,products and category and after choosing category display furthere fields that suit to chosen category? In my example I would like extend my form witch size and shape if hat is chosen and model and age if car is setted model.py class Products (models.Model): products=(('1','hats'),('2','car')) name=models.CharField( max_length=30) category=models.TextField(choices=products,blank=True, null=True) color = models.CharField(max_length=40, blank=True, null=True, default='') model=models.CharField(max_length=40, blank=True, null=True, default='') age=models.CharField(max_length=40, blank=True, null=True, default='') size = models.CharField(max_length=40, blank=True, null=True, default='') shape= models.CharField(max_length=40, blank=True, null=True, default='') forms.py class ProductsForm (ModelForm): class Meta: model = Products fields = ['name','category', 'color', 'model','shape','size'] -
How to resolve environment error while upgrading django version
I got the following error while upgrading the django version=2.2.12 I tried the following command for upgrading django: enter code here:python3 -m pip install -U Django I got the below error Collecting Django Using cached Django-4.0.2-py3-none-any.whl (8.0 MB) Requirement already satisfied, skipping upgrade: asgiref<4,>=3.4.1 in ./.local/lib/python3.8/site-packages (from Django) (3.5.0) Requirement already satisfied, skipping upgrade: backports.zoneinfo; python_version < "3.9" in ./.local/lib/python3.8/site-packages (from Django) (0.2.1) Requirement already satisfied, skipping upgrade: sqlparse>=0.2.2 in ./.local/lib/python3.8/site-packages (from Django) (0.4.2) Installing collected packages: Django ERROR: Could not install packages due to an EnvironmentError: [Errno 20] Not a directory: '/home/vamsi/.local/lib/python3.8/site-packages/django/core/management/templates.py I tried the another code : enter code : sudo pip install --upgrade django I got: Requirement already up-to-date: django in /usr/local/lib/python3.8/dist-packages (4.0.2) Requirement already satisfied, skipping upgrade: sqlparse>=0.2.2 in /usr/lib/python3/dist-packages (from django) (0.2.4) Requirement already satisfied, skipping upgrade: asgiref<4,>=3.4.1 in /usr/local/lib/python3.8/dist-packages (from django) (3.5.0) Requirement already satisfied, skipping upgrade: backports.zoneinfo; python_version < "3.9" in /usr/local/lib/python3.8/dist-packages (from django) (0.2.1) But when i checked the version using command:python3 -m django --version I got the previous version:2.2.12 So how can i resolve this .Is there any way to upgrade the django version ??. I saw lot of issues in online but i cant find anyone -
Django wont display my comments on template
I've tried to implement the comments within the html page after creating them in my models and I have migrated them but they still wont appear within the page although when I add a comment from the admin side of the website the add comment button I added in before the else statement in the html disappears, which means that it isn't empty but the comments still wont show? Models.py class Photo(models.Model): category=models.ForeignKey(Category,on_delete=models.SET_NULL,null=TRUE,blank=TRUE) image=models.ImageField(null=False,blank=False) description= models.TextField() def __str__(self): return self.description class Comment(models.Model): user = models.ForeignKey(UserProfile, related_name="profile", on_delete=models.CASCADE) photo = models.ForeignKey(Photo, related_name="comments", on_delete=models.CASCADE) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.user.username + ': ' + self.text and then here is the Html portion <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible" content="IE-edge'> <title>Photo</title> <meta name='viewport' content='width-device-width, initial-scale=1'> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body class="m-5"> <div class="container"> <div class="row justify-content-center"> <div class="col"> <a href="{% url 'Clinician' %}" class="btn btn-dark my-3">Go Back</a> <div style="height: 90vh;"> <img style="max-width: 100%; max-height: 100%;" src="{{photo.image.url}}"> <p> {{photo.description}} </p> <h4>Comments...</h4> {% if not photo.comments.all %} No Comments Yet...<a href="#"> add one </a> {% else %} {% for comment in photo.comment.all %} <strong> {{ comment.date }} </strong> <br/> {{ comment.text }} {% endfor %} {% … -
How to deploy dockerised react + django web app to google app engine?
I have created a web app which uses react as frontend and django as backend. I have also added nginx proxy to my both backend and frontend. I use docker compose to build and start all of my containers and everything works perfectly. Now i want to deploy it to google app engine and I have no idea how to do that. I found this well written article, but it uses aws. I want to use app engine because its free (for now). It would be really helpful if someone could guide me through this. -
Find difference between two time for verification token in Django
I am creating an app in Django where I have to send a token to a user but I want to make it expire after 5 minutes, now the issue I am getting time from django field in this format token_time = Token.objects.filter(user_id=user_id).last().user_token_timestamp current time = datetime.now().time() is there any way to find the time difference in minutes in pythonic way, although I have done by converting the time into string and then striping it but it just feels like not a good way. -
My django models are returning serialised data in json format for my view but i also want a string representation for my admin. How do i do that
class PerfumesImages(models.Model): entry = models.ForeignKey(Perfumes, default=None, on_delete=models.CASCADE, related_name="perfumesphoto") images = models.ImageField(upload_to='Perfumes', verbose_name='Image') def serialize(self): return { "id": self.id, "entry": {"entryid" : self.entry.id, "brandsection" : self.entry.brandsection, "brand" : self.entry.brand, "price" : self.entry.price, "color" : self.entry.color,"description" : self.entry.description}, "images": self.images.url } -
Django 4. Invalid block tag on line 45: 'item.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I work on Django 4 I am trying to create a view that will load a template view in django and I am getting the above error. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 45: 'item.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Exception Location: C:\Users\zinnurov.ramil\PycharmProjects\django_full_guide\venv\lib\site-packages\django\template\base.py, line 552, in invalid_block_tag Python Executable: C:\Users\zinnurov.ramil\PycharmProjects\django_full_guide\venv\Scripts\python.exe Python Version: 3.9.4 views.py def index(request): template_name = 'news/index.html' news = News.objects.order_by('-created_at') categories = Category.objects.all() context = { 'title': 'Список новостей', 'news': news, 'categories': categories, } return render(request, template_name, context) model.py class Category(models.Model): title = models.CharField(max_length=200, db_index=True, verbose_name='Категории') class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' ordering = ['-title'] def __str__(self): return self.title <div class="col-md-4"> <div class="list-group"> {% for cat in categories %} {% item.title %} {% endfor %} </div> </div> enter image description here Have you got an idea ? -
Is there a way to pass options values during mod_wsgi server start up in Django app
I am using mod_wsgi to run my Django app. As there are a plethora of options to define when the server run command is fired, I was trying to create some kind of python script to pass the options and their pre-set values. For example: Instead of using: $python3 manage.py runmodwsgi --processes 3 --threads 1 I am trying to use a python script and use it as: $python3 runme.py where runme.py is the script file I am trying to use to start the server. What I have done so far? Created the script file: import os from django.core.management import execute_from_command_line os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings') myargs = 'runmodwsgi' list_of_args = ['', myargs] execute_from_command_line(list_of_args) As expected the server started with preset options, for example: Now what I am trying to achieve is the pass values of certain options like: --processes 3 --threads 1 and so on. Is there a way I may pass the preset values (as I may be able to define in my script file runme.py), say something like adding to the list of arguments: list_of_args = ['', myargs, addl_args] I have been checking SO queries posted in addition to help available on python site, but could not get my head around … -
Need to execute my SQL queries in my model to display the result as API in django
Model class Consolidated(models.Model): emp_name=models.ForeignKey(Users,on_delete=CASCADE) proj_name=models.ForeignKey(Project, on_delete=CASCADE) custom_name=models.ForeignKey(Client,on_delete=CASCADE) Cons_date=models.ForeignKey(Add_Timelog, on_delete=CASCADE) bill_no_bill=models.ForeignKey(Users,related_name="billable_and_non_billable+", on_delete=CASCADE) hour_spent = models.ForeignKey(Add_Timelog,related_name="hour_spent", on_delete=CASCADE) def __str__(self): return str(self.emp_name) viewset permission_classes=(permissions.IsAdminUser,) queryset = models.Consolidated.objects.raw("select public.App_add_job.id, employee_name, billable_and_non_billable, client_id, project_id from public.App_add_job join public.App_users on public.App_add_job.employee_name_id = public.App_users.id") serializer_class=serializers.Consolidated_serializers I have a sql query updated in my viewset and i dont know how to run that query in my API model to display the table values in the api. kindly help me to change the code for the model to execute the sql queries in that Consolidated model. -
Reportlab pyhton alignment issue
Style3 = TableStyle([('VALIGN',(0,0),(-1,-1),'TOP'), ('ALIGN',(0,0),(-1,-1),'RIGHT'), ('LEFTPADDING',(0,0),(-1,-1), 130), ('RIGHTPADDING',(0,0),(-1,-1), 0), ('TOPPADDING',(0,0),(-1,-1), 0), ]) I want response and categories label in starting but it show at the end of line, i want response and categories in from starting not end of line.. any special styling i need. -
How to count foreign key objects with annotation in Django?
Hi all! New in Django, and confused, help is appreciated! Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) Objects of Organization model: organization_name Organization 1 Organization 2 Objects of AppealForm model: form_name In written form In oral form Objects of Appeal model: organization appeal_form applicant_name Organization 1 In written form First and Last name Organization 1 In oral form First and Last name Organization 1 In oral form First and Last name Organization 2 In written form First and Last name Organization 2 In oral form First and Last name I'm trying to create a table in the template, like: Organization Total amount of appeals Amount of written form appeals Amount of oral form appeals Organization 1 3 1 2 Organization 2 2 1 1 The content in the table contents has to be retrieved from Appeal model, that is rendered to the template. Question: How the query look like in views.py using Appeal model? -
Django SMTP email does not send any emails and shows SMTPAuthenticationError as a response
I used windows(10) IIS server to upload my Django(ver. 3) project. I also added google SMTP mail service to send email. I tested that project locally. At that time all emails sent without any issues. But in my IIS web server, It doesn't send any email. It always shows this error, SMTPAuthenticationError at /send_email (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 TJtoTOBiMuXdqvUyrO5XGEpv5y-vj2Ebs2xhNf_6KSPlcDKxqWeTORJr3MvuzPqEMKvUM\n5.7.14 CuojHIAZKcwqRCyp8b6d7tFFeTM-LfQjq6dQe9rPfHPDS3xrgumMcQCe3PrPIsbm>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 w9sm9003338ool.31 - gsmtp') Can anyone tell me reason or how to solve this issue? -
Docker-compose + Django on AWS C9
I'm trying to use a docker container to run a django application on the cloud base IDE from AWS (AWS C9). The application is started correctly and the development server is started on http://127.0.0.1:8080/ However when browsing to the public URL of the cloud 9 application I'm getting the error 'no application seems to be running'. When creating a django application without docker, the preview on AWS coud 9 works fine. Are there any addtional settings required to get the cloud 9 preview to work? This is my docker-compose file. services: web: build: . command: python manage.py runserver $IP:$PORT volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres -
Add css style to django ckeditor
I'm using django ckeditor I can add and edit HTML tags, but can't add CSS styles Is there any way to add CSS style to the content? -
Django Browser Cache Issues
My Django app has a forgot password functionality where I am sending emails containing a password reset link. However when this link is clicked, the browser automatically redirects it to the home page (I'm pretty sure this has to do with the caches stored by the browser rather than Django directly). This happens both on Firefox and Chrome. Clearing cache or opening the link in incognito works but I can't tell users to do this every time and need a permanent solution. The password reset urls are of the form: reset/<uidb64>/<token>. Any idea why this is happening and how to fix it? The problem persists in the deployed app as well as while testing. -
I built a photo album on django using photos in models but now im trying to convert it to posts in order to allow for a comment section to be added
For the models page I have my Photo model here which I used to create a photo album with categories that let me add and delete photos from the album. Models.py class Photo(models.Model): category=models.ForeignKey(Category,on_delete=models.SET_NULL,null=TRUE,blank=TRUE) image=models.ImageField(null=False,blank=False) description= models.TextField() def __str__(self): return self.description I am trying to add in a comment section within the admin interface that will go below each of the photos added and I am stuck on how to do this as all the other examples online use a post method without my categories and image and description fields. I also have a comment section that I tried to convert to but couldn't manage to get it to work Models.py class Comment(models.Model): user = models.ForeignKey(UserProfile, related_name="profile", on_delete=models.CASCADE) Photo = models.ForeignKey(Photo, related_name="Comments", on_delete=models.CASCADE) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.user.username + ': ' + self.text -
Django : "TypeError: unsupported operand type(s) for +: 'FloatField' and 'FloatField'"
I am trying to add 2 models.FloatField variables in Django before saving the model, and getting an error. from django.db import models class MyModel(models.Model): def __init__(self): self.value1 = models.FloatField(default=10.0) self.value2 = models.FloatField(default=20.0) def add_values(self): return self.value1 = self.value1 + self.value2 When I create MyModel object and call add_values function, I get following error my_model = MyModel() my_model.add_values() **Error Stack** line 8, in add_values self.value1 = self.value1 + self.value2 TypeError: unsupported operand type(s) for +: 'FloatField' and 'FloatField'``` -
How do I designate a wagtail page as a login page?
I kind of know how I might do this in Django but not in Wagtail and this is because Wagtail has a notion of Pages whereas Django only knows about views. I have google search results about designating an HTML template as a login template but not a Wagtail Page instance. In my case I would redirect to a Wagtail Registration/Sign Up/Login page that I have created. (That's why django-allauth doesn't seems not to be a good fit for me. ) Thus when trying to view a private Wagtail page it would get directed to the a Wagtail Page I designate for logging in and passing as an argument (perhaps by URL query string) the next page to visit after successfully logging in. What mechanism can I use in wagtail for a Wagtail Page based solution to do this? -
How to speed up flight price api for loop
In my Django view I am using an API that retrieves a origin airport id and a destination airport id which it then uses to calculate a flight price. The for loop that gets the destination airport id and respective flight price for each city seems to be really slowing down the page (it takes about 13 seconds to load). I was wondering if there were ways to speed up the process of gathering this data and displaying it. views.py def results(request, result1, result2, result3, result4, result5, result6, broad_variable1, broad_variable2, broad_variable3, specific_variable_dictionary, user_city): result1 = City.objects.filter(city=result1).first() result2 = City.objects.filter(city=result2).first() result3 = City.objects.filter(city=result3).first() result4 = City.objects.filter(city=result4).first() result5 = City.objects.filter(city=result5).first() result6 = City.objects.filter(city=result6).first() broad_variable1 = broad_variable1 broad_variable2 = broad_variable2 broad_variable3 = broad_variable3 # get the first user selected specific variable value for each result result1_value1 = City.objects.filter(city=result1.city).values(broad_variable1)[0][broad_variable1] result2_value1 = City.objects.filter(city=result2.city).values(broad_variable1)[0][broad_variable1] result3_value1 = City.objects.filter(city=result3.city).values(broad_variable1)[0][broad_variable1] result4_value1 = City.objects.filter(city=result4.city).values(broad_variable1)[0][broad_variable1] result5_value1 = City.objects.filter(city=result5.city).values(broad_variable1)[0][broad_variable1] result6_value1 = City.objects.filter(city=result6.city).values(broad_variable1)[0][broad_variable1] # assign variables before referencing them result1_value2 = None result2_value2 = None result3_value2 = None result4_value2 = None result5_value2 = None result6_value2 = None # check if the user chose a second variable # get the second user selected specific variable value for each result if broad_variable2 != "Nothing": result1_value2 … -
Error 404 Django - Nginx - Gunicorn - AWS Ubuntu Static Files Serving Correctly
I am deploying my Django App to AWS on an Ubuntu Server, so far I managed to configure Ngnix - Gunicorn and both of them are working correctly,the logs files are not showing any error; my application is being served in the Public IP without problem and I can access the static files using the url: Https://myip/static/assets/img/image.jpg But when I try to access another url in my project, Nginx sends me a 404 error, so I do not know how to narrow and solve this problem, because the static folder is being served by nginx correctly but the urls and the project is not working. My project.settings configuration file for loading the static folder looks like this: Project Settings Configuration And my nginx file configuration is like this one: Server Configuration