Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django rest framework How to fix many-to-many n+1 error?
I have models: class Group(models.Model): number = models.CharField(choices=CLASS_NUMBERS, max_length=2, verbose_name="Номер класса") name = models.CharField(max_length=20, verbose_name="Название класса") group_teacher = models.ForeignKey('users.Teacher', on_delete=models.CASCADE, verbose_name="Классный руководитель", related_name='group_teacher') students = models.ManyToManyField('users.Student', verbose_name="Ученики", blank=True, related_name='group_students') code = models.CharField(max_length=8, unique=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Преподаватель", related_name='teacher_user') class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Ученик", related_name='student_user') and serializers: class TeacherSerializer(ModelSerializer): class Meta: model = Teacher fields = [ 'user' ] class StudentsSerializer(ModelSerializer): class Meta: model = Student fields = [ 'user' ] class GroupSerializer(ModelSerializer): class Meta: model = Group fields = [ 'id', 'number', 'name', 'code', 'group_teacher', 'students', ] When I make an appeal to the api I get warnings: Potential n+1 query detected on Teacher.user Potential n+1 query detected on Teacher.user Potential n+1 query detected on Student.user Potential n+1 query detected on Student.user Potential n+1 query detected on Student.user Potential n+1 query detected on Student.user querries my view set: class GroupModelViewSet(viewsets.ModelViewSet): serializer_class = GroupSerializer def get_queryset(self): return Group.objects.all().prefetch_related('students') How to fix these errors n+1, select_related does not let me select the model of students and teachers -
Copy file to non-project directory after webpack compliation
I would like to be able to develop a React app for work in a directory and copy the bundle file over to a local instance of our website, which runs on a Django backend in a different directory on my local file system. I can easily develop in one directory and copy the bundle to another directory using my file system but I was hoping to automate this each time I compiled. I have written a plugin for my webpack config file and am able to read the bundle and write it to a separate file within the project directory (using the fs package) but can't seem to find a way to write the copy to a different directory on my file system. It either ends up in the project directory I am compiling from or I get an error Error: ENOENT: no such file or directory Is such a thing possible? I suppose I could simply write the bundle to the other directory in the first place and not copy it if the webpack output can write to a different location. Here is my code for my plugin in my webpack.config.js so far. In this example I was … -
Update ManyToManyField by calling view via ajax("Like" button)
Not sure if this is more of a javascript question or a django question so please forgive me if it is in the wrong spot. I am trying to update a ManyToMany field representing "likes" on an image by calling a view via ajax. The "like" portion is working, the "unlike" portion is not. I have an Image model with a users_like field: class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name = 'images_created', on_delete=models.CASCADE) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="images_liked", blank = True) # etc The view: def image_like(request): image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Image.objects.get(id = image_id) if action == 'like': image.users_like.add(request.user) else: images.users_like.remove(request.user) return JsonResponse({'status': 'ok'}) except: pass return JsonResponse({'status': 'ko'}) Url: path('like/', views.image_like, name = 'like'), html/js: <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} Like {% else %} Unlike {% endif %} </a> <!-- other html, skipping down to the jQuery--> {% block domready %} $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "images:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // … -
How do i get Django to store already uploaded cover image to a user without getting it deleted
How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models: class AccountCover(models.Model): account = models.ForeignKey(Account,on_delete=models.CASCADE) cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,) My view.py cover = AccountCover.objects.filter(account=account.id).first() if request.user: forms = CoverImageForm(request.POST, request.FILES,instance=cover, initial = {'cover_image':cover.cover_image}) if request.method == 'POST': f = CoverImageForm(request.POST, request.FILES,instance=cover) if f.is_valid(): data = forms.save() data.account = cover.account data.save() return redirect('account:edit', account.id) else: f = CoverImageForm() context['f'] = f -
Django Python none of the css or js appears when running
Learning and new to Django and Python in general. I have this code where I am trying to run my Django application on local host by using the command python manage.py runserver The application seems to run just fine. However, when I go to local host I only see the basic stuff and I do not see any of the css or javascript. Now I do not get any errors and I think I set everything up for static correctly in the settings.py file. Here is the settings file: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&1myw#x5mwq=%wn!cc202+&63q-ar-i1yp4ao6a=uu2fs-vzm_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['verdam.dundulio.lt', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'brewery.apps.BreweryConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #buvo commented 'tempus_dominus', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'brew.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / '/templates/', BASE_DIR / '/',], 'APP_DIRS': True, … -
How to pass selection from Django template to Class view
I am struggling with something that should be routine for me by now but I have a mental block. I have a model that stores Country names and a slug version of the name. Eg. "United States", "united-states" I want to display the country names in a template for selection, then return the selected country's slug value to the Class based View which will then obtain the data. The list of countries can be links or dropdown - whatever. But I need to obtain the selected value in the View. Here is a simplified version: Template {% extends 'base.html' %} {% block content %} <form method="POST"> {% for country in object_list %} <a href="{{country.slug_name}}">{{ country.pretty_name }}</a></br> {% endfor %} </form> {% endblock content %} View class CountryView(TemplateView): country_name = THE SLUG country_obj = Country(country_name) country_obj.build_country_dictionary() country_obj.display() So I think I need one of the get methods to access this but I cannot work it out. Thanks for any help. -
Django: is it possible to make the statement displayed with red color when we use a form crispy?
Hi i want if a user forgot to fill out any field from the form , the phrase "" This field is required. "" displayed with red color and not with black color , is it possible if yes! , How i can do that please or is there another way to do that! enter image description here -
Integrating a custom function in Django
I would like to access and print metadata (attributes and values) served by an ERDDAP server, which is a variety of OPeNDAP, on my Django website. so I prepared a simple example function called get_conventions to access a metadata field on this public server hosting data and metadata. To get started, I install the required packages: $ pip install pandas erddapy and then, import pandas as pd from erddapy import ERDDAP def get_conventions(dataset_id): e = ERDDAP(server='https://gliders.ioos.us/erddap/', protocol='tabledap', response='csv') url = e.get_info_url(dataset_id, response='csv') df = pd.read_csv(url) # this replace spaces with underscores in column names df.columns = [col_name.replace(' ', '_') for col_name in df.columns] conventions = df[df.Attribute_Name == 'Conventions'].Value return conventions Using a Python interpreter, one could call the function like this with this sample dataset id as an argument (amelia-20180501T0000), which is found on the server; the output follows: >>> get_conventions('amelia-20180501T0000') 6 Unidata Dataset Discovery v1.0, COARDS, CF-1.6 Name: Value, dtype: object >>> I would like my website to print on a webpage the output of the above function. I can print the argument string in a page (model.py, views.py and a related html templates - those being similar to the Django tutorial), but I am unsure how to refer … -
How to run Jupyter in Django?
Hello this is a bit of a strange question but how would I get my Django website to display a jupyter notebook(or all of Jupyter lab I don’t mind) that is being run on the server, and be able to edit it? I seriously have no idea and have been trying to find info for days.