Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Django docker logging
I am running docker on my Mac. I am having an issue with my views.py and I am trying to print out to the Mac docker desktop some messages to try to debug my code. I have followed Django and docker: outputting information to console and it doesn't seem to work for me. The only thing that gets printed out to the docker desktop logs is just errors when they occur, Normally all I get is just the 200 ok from the http request. I have used the print statement and the info statement and neither of them print out. ------------------------------------ setttings.py ------------------------------------ from pathlib import Path import os import logging.config import json # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #Logging Config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[DJANGO] %(levelname)s %(asctime)s %(module)s ' '%(name)s.%(funcName)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'default', } }, 'loggers': { '*': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, } }, } ------------------------------------ views.py ------------------------------------ from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse_lazy from .login_model import LoginForm import logging logger = logging.getLogger(__name__) # … -
using primarykeyrelated for post and string for get call in django rest framework
I have a model in which some fields are a foreign key to another model. Hence while creating the object of that model I have to use primary key but while calling get api I need to show those fields as stringrelated field. How to achieve that?? My model: class Example(models.Model): tour = models.ForeignKey( Package, on_delete=models.CASCADE, null=True, related_name="example" ) site = models.ForeignKey( Destination, on_delete=models.CASCADE, null= True, related_name= "example", ) location = models.CharField(blank=True) /...........other fields........../ My serializer: class ExampleSerializer(serializers.ModelSerializer): # tour = serializers.StringRelatedField() # site = serializers.StringRelatedField() class Meta: model = OnlineClass fields = ['id','tour','site','other fields.....'] def to_representation(self, instance): data = super(ExampleSerializer, self).to_representation(instance) return data Here while creating the example object, I need to pass tour and site as ids but while calling list method I need to show both fields as string related fields. As I define them as stringrelated field as above (later commented out) , I can create the object but those fields will be set as null. I don't want to make another serializer. How to achieve this?? -
Django validate_unique error while updating from admin
I have created a validate_unique based in two fields (asset and portfolio), it work well when i try to create a new object that already exists, i get the correct message. But i get the same error message if i try to update an existing object. Should i change something to make the update work? class PortfolioAsset(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) asset = models.ForeignKey(Asset, on_delete=models.CASCADE) shares_amount = models.FloatField() share_average_price_brl = models.FloatField() total_cost_brl = models.FloatField(editable=False) total_today_brl = models.FloatField(editable=False) def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if self.__class__.objects.\ filter(portfolio=self.portfolio, asset=self.asset).\ exists(): raise ValidationError( message='This asset already exists in this portfolio.', code='unique_together', ) def save(self, *args, **kwargs): self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2) self.total_today_brl = round(self.shares_amount * self.asset.price, 2) super(PortfolioAsset, self).save(*args, **kwargs) -
How to authenticate user using custom model in Django?
I am working on a Django project. The project has three pages Home, login, registration. Home page's nav bar has three buttons Home, login and registration. I have created a custom model I don't want to admin model. I already did the login part but now I want is after login the home nav login and register button disappear and a new button/text appear Hello user or whatever the name whoever is logged in. Is there any way to do it I know we can do it with the admin User model but I don't know how to do it with a custom model? -
Django Admin Access Parent Object Value From Tabular Inline
I am attempting to setup an admin TabularInline and carry the value of the GenerationMode selection to the ModeVersion mode field. models.py: class GenerationMode(models.Model): mode=models.CharField(max_length=35, choices=GENERATION_CHOICES, default='None', blank=False, null=False) disabled=models.CharField(max_length=1, choices=DISABLED_CHOICES, default='N', blank=False, null=False) active=models.CharField(max_length=1, choices=ACTIVE_CHOICES, default='Y', blank=False, null=False) created_when=models.DateTimeField(auto_now_add=True) modified_when=models.DateTimeField(auto_now=True) class Meta: db_table = 'main_GenerationModes' def __str__(self): return self.mode def __unicode__(self): return self.mode class ModeVersion(models.Model): mode=models.CharField(max_length=35, choices=GENERATION_CHOICES, default='None', blank=False, null=False) version=models.DecimalField(max_digits=5, decimal_places=2, blank=False, null=False) active=models.CharField(max_length=1, choices=ACTIVE_CHOICES, default='Y', blank=False, null=False) created_when=models.DateTimeField(auto_now_add=True) modified_when=models.DateTimeField(auto_now=True) FK_mode=models.ForeignKey(GenerationMode, on_delete=models.SET_NULL, blank=True, null=True) class Meta: db_table = 'main_ModeVersions' def __str__(self): return self.mode + '_' + self.version def __unicode__(self): return self.mode + '_' + self.version admin.py: from .models import GenerationMode from .models import ModeVersion class GenerationModeVersionInline(admin.TabularInline): model = ModeVersion min_num = 1 extra = 0 class GenerationModeAdmin(admin.ModelAdmin): inlines = [GenerationModeVersionInline] model = GenerationMode list_display = ['mode', 'disabled', 'active'] admin.site.register(GenerationMode, GenerationModeAdmin) I've looked here, as well as, read the docs. I am confused on how to achieve what I am trying to do. Is there a recommended approach to solve this? -
SMTPAuthenticationError at /reset_password/ (535, b'5.7.8 Username and Password not accepted in django
When i use any email from these in reset password it is giving me the error SMTPAuthenticationError at /reset_password/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o10sm21802621wri.19 - gsmtp') But when i use any email which is not present in these emails i am not getting any mail what should i do? My EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are right i manually checked it. -
Sharing data in local thread python in different threads
I have stored request_id in local thread python, this thread creates three more threads which won't have access to request_id. How can I share or send request_id info from one thread local to another. -
Django aws getting mysql OperationalError
I was using localhost mysql database. After integrating aws rds mysql I am getting this error django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') Here is my mysql configuration for aws rds: settings.py DATABASES = { 'default': { 'ENGINE': config('AWS_MYSQL_ENGINE'), 'NAME': config('AWS_MYSQL_DB_NAME'), 'USER': config('AWS_MYSQL_DB_USER'), 'PASSWORD': config('AWS_MYSQL_DB_PASSWORD'), 'HOST': config('AWS_MYSQL_DB_HOST'), 'PORT':config('AWS_MYSQL_DB_PORT'), } } my local host mysql is working fine. I am not understanding why I am getting this error after move to aws rds. I am straggling from several hours for solve this problems. I tried to run migrate after delete all of my migrations files but didn't work. here is full error log: site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') -
How can I check if a boolean from a different model is true for a user of a team?
I have the following model I want to use to add rights to users that are part of a team: class Rights(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Teams, on_delete=models.CASCADE) read = models.BooleanField(default=True) write = models.BooleanField(default=False) edit = models.BooleanField(default=False) Some Users need to be able to make new entries. Some are not allowed to have that possibility. So, if some user sends a request, how can I check if one or more of these boolean values are true or false for this specific user? -
How to access auth_user_group table by ID
How can I directly specify the ID column of auth_user_group table in queries/DML? I am referring to auth_user_group.id, not auth_group.id nor auth_user_group.group_id. For example, I want to directly issue DML like: delete from auth_user_group where auth_user_group.id = 1 select id, user_id, group_id from auth_user_group where auth_user_group.id = 1; I am not interested in the following workaround which avoids auth_user_group by requiring knowledge of the group name, instead of the auth_user_group.id, and results in two queries instead of 1: group = Groups.get(name='foo') user.groups.remove(group) If you wanted to directly query a junction/M:N table in Django, normally you would create a "through Model" and can then query it directly. However in this case, the django.contrib.auth.models definition do not use a through model.