Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to run unitest from specific file?
In my project I have a task to add few Unittests to APIs. We have many django apps and I need to do work only with one: apps\data\tests.py But when I'm trying to specify exactly this file/folder to start those exact Tests: python3 manage.py test data.tests or python3 manage.py test data.tests.py its still running ALL tests between ALL apps. I did make 1 hour search online but Everyone suggesting to use: python3 manage.py test + "path to the folder/file". But its still running everything. Maybe i'm missing some General test configuration in settings.py? Thank you, -
Celery Schedule, can't pickle nowfun
I'm trying to configure Celery to run different tasks in different time zones maintaining the shift in daylight savings. I set up my task like this: import datetime import pytz from celery import Celery from celery.schedules import crontab app = Celery('my_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() NOW_MT = lambda: datetime.datetime.now(pytz.timezone('America/Denver')) app.conf.beat_schedule = { "My Daily Mountain Time Task": { "task": "app.tasks.some_task", "schedule": crontab(minute='0', hour='0', nowfun=NOW_MT) }, "My Daily UTC Task": { "task": "app.tasks.some_other_task", "schedule": crontab(minute='0', hour='0') } } But my celery beat process is erring out with the following message: Can't pickle <function <lambda> at 0x7f71055a4670>: attribute lookup <lambda> on app.celery failed -
How to calculate time based on given days
Model : class PackageLabPrice(core_models.TimestampedModel): package = models.ForeignKey( Package, related_name="package_lab_price", on_delete=models.CASCADE ) assigned_lab = models.ForeignKey( "sampleregistration.LabsCredentials", null=True, blank=True, on_delete=models.CASCADE ) tat_time_duration = models.DurationField(blank=True, null=True,default=timedelta(hours=48)) package_price = models.FloatField(null=True, blank=True, default=None) offer_price = models.FloatField(null=True, blank=True, default=None) addon_price = models.FloatField(null=True, blank=True, default=None) is_active = models.BooleanField(default=True) is_outsource = models.BooleanField(default=False) days = models.ManyToManyField(core_models.Days, related_name="package_lab_price_days", blank=True) Here package field is Test. So I have to calculate time. So Suppose someone booked a test on Friday and its tat_time_duration is two days. But the assigned lab is closed on saturday and sunday. So the person should get the roport on Tuesday. But again assigned_lab can be closed on tuesday. (For every test the default_tat_duration and on which day lab is open or closed is given. So I need to get the final result. I would like to clear with this Image. So A person booked a test on Friday and its tat_time_duration is two days so he will get report on Tuesday. Because Sat Sun is not mapped for that test(Complete Blood Count). Next case if the test is booked on Monday. The person will get the report on Wednesday. Last case if it booked on wednesday the person will get the report on Tuesday as Sat and … -
DRF unexpected behaviour in API PUT method when passing value to object
I have a model and I am trying to build an API with PUT method to update the values. However, when I send request with postman, all of the values are returned wrapped inside ( ,). For example, if I pass the JSON data { "name" = "MyName" } and then in the API under PUT method data = request.data animal.name = data['name'] the returned values for animal.name is ( MyName,) (it gets stored in the database like that) which is not what I passed/expect (I was expecting MyName). I used print (data['name'], animal.name) to confirm the JSON data are received correctly, and that is so (the print output is MyName, ( MyName,) . So the problem is within the API. I have the feeling this might be related to the sex = model.ChaerField(choices=...) as it is the first time I use this method. I would really appreciate some help in understanding why this is happening and how to solve it. Below is my definition of model serializer and view. models.py MALE = 'M' FEMALE = 'F' SEX_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female') ] class Animal(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='animal') farm = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True, related_name='animal') custom_uuid … -
How to access thread results and render them on template
I have a main view that displays cities and flight prices. The web scraper function that gets the flight prices takes some time so instead of having it in my main view I created a separate function for it. That function runs async when the main view loads however I am wondering how I can pass the prices_list data from my function to the main view so it's rendered in the template. I'm new to Django and threading so would greatly appreciate any help! views.py def results(request): # user city user_city = "Madrid" # create list of cities city_list = ["Toronto", "Montreal", "Calgary", "Edmonton", "Vancouver", "Quebec"] t = threading.Thread(target=get_prices, args=[city_list, user_city], daemon=True) t.start() # change string dictionary into actual dictionary specific_variable_dictionary = ast.literal_eval(specific_variable_dictionary) context = { "user_city": user_city, } return render(request, 'Discovery_App/results.html', context) def get_prices(city_list, user_city): # create price list prices_list = [] # set origin for flight origin = user_city # set headers headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36" } for i in city_list: # set destination for flight destination = i # set search query url = "https://google.com/search?q=" + origin + " to " + destination + " … -
Draw a chart in HTML based on dynamic data within the input start and end time range
I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines) mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] It's a Django project, so my data is defined in views.py: I count the number of records with Mike, Jane and Jack. tsheet2022 = client.open('Return Record 2022') tinstance2022 = tsheet2022.get_worksheet(0) mylist = tinstance2022.get_all_records() mike=len(tuple(d for d in t2022 if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in t2022 if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in t2022 if d['Receiver'] == 'Jack')) count = [mike, jane, jack] I have already drawn a pie chart based on my counted data in my 'chart.HTML' file : <div class="card-body"> <div class="chart-pie pt-4"> <canvas id="myPieChart"></canvas> <script> var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Mike", "Jane", "Jack"], datasets: [{ data: {{count}} , backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", … -
What is the best way to store a user's availability as a custom object in the SQL database?
I am designing a web application that will be pairing up two different kinds of users: Volunteers and Participants. The Volunteers will have an "availability" schedule, that is essentially an array of 48 booleans for any given day. This is a rough draft of the "DailySchedule" object, where each boolean represents a 30 minute period of time in a 24 hour day: class DailySchedule(object): availability = [] def __init__(self): for i in range(48): self.availability.append(False) pass def make_available(self, index): self.availability[index] = True def make_not_available(self, index): self.availability[index] = False def make_range_available(self, start, end): assert 0 <= start <= 47 and 0 <= end <= 47, "Out of Range." for i in range(start, end + 1): self.availability[i] = True def make_range_not_available(self, start, end): assert 0 <= start <= 47 and 0 <= end <= 47, "Out of Range." for i in range(start, end + 1): self.availability[i] = False This is essentially how this object will be used: A Volunteer will have their regular "default" schedule, which consists of a DailySchedule object for each day of the week. For now, we won't worry about enabling them to overrate individual dates - we'll just assume this is their permanent schedule. A WeeklySchedule would have to … -
Uploaded images organisation (DIR Structure) in django or any without affecting the web app speed or load time?
I'm confused about organising files and media. Let say, I have a Django website, it has over 25 models, all of them contains at least one image field. Every submitted entry in the database, create 5-6 different versions of that image by size and format. Currently, I just have a DIR for each model inside the media root which store all uploaded image related to that specific model. What is the best way to organise them in terms of loading speed. If any model or models, let say have 10,000s of entries means 50,000 to 60,000 of images as well. And when someone visits the website does it affect the speed because it is looking through so many images and putting that specifics on the user requested page? Or it doesn't matter at all? Best way, I can keep them without putting any affecting the loading speed?: Storing all images in one dir of that model (MEDIA > MODEL DIR > All Images), because it doesn't matter. MEDIA > MODEL DIR > SIZES/FORMAT DIR (e.g. 200x200 or png) > All entries' images that are 200x200 in size, can have thousands of images. Storing every single entry's images in a separate … -
Issue with image in django
I have problem with image in django. I get 404. Settings.py MEDIA_ROOT = 'static/image/' MEDIA_URL = 'image/' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] Models.py img = models.ImageField(upload_to = '', verbose_name= 'Картинка',null=True ) (P.S I tried everything,but it isnt working)