Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gitlab CI set up django postgres service
I am facing this service for hours but still I do not have solutions. My gitlab.yml looks like this image: python:3.6 services: - postgres:latest variables: POSTGRES_DB: test POSTGRES_USER: postgres POSTGRES_PASSWORD: "" POSTGRES_HOST_AUTH_METHOD: trust job:on-schedule: only: - schedules script: - export DATABASE_URL=postgres://postgres:@postgres:5432/test - apt-get -yq update - apt-get -yq install python-pip - pip install -r requirements.txt - python manage.py test and settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'postgres', 'PORT': '5432' } } at first I have come about a connection error like is it listening to 5432 and locally etc. Now I am facing time out. All processes passed when it comes to the python manage.py test it does not run next. I do not know why. Please anybody can help??? Thanks in advance -
Uncaught TypeError: Cannot read property 'then' of undefined problem
the update works after i send it to the API const UpdateClick = () =>{ API.updateMovie(props.editdMovie.id,{title,description}).then(resp => console.log(resp)) } but when I get to the then part its fall the api part export class API{ static updateMovie(mov_Id,body){ fetch(`http://127.0.0.1:8000/api/movies/${mov_Id}/`,{ method : 'PUT', headers : { 'Content-Type' : 'application/json', 'Authorization' : `Token ${TOKEN}` }, body : JSON.stringify( body ) }).then(resp => resp.json()) } } -
Occasional 404 error in aws nginx django app (restframework)
Hi I am using aws server with average cpu load of 60-70% made in django(restframework) with nginx server and flutter frontend. The problem is sometimes it gives occasional 404 error but on refreshing the page (api) it works fine. How should I debug this? I was thinking of cpu overload but in monitoring section of aws ec2 , it shows the max load is around 80% and average load is aroung 60-70%. This problem has started recently with no changes in the code. What are the steps I should take to debug this? -
Why Django List Iterator's item doesn't return?
In my database, I have 2 table Spider Table: id, spider_name Market Table: market_timezone, market_location, market_year, market_day, market_month I have list iterator like this: @register.filter def getSpiderItem(datas, spider_id): return iter(datas.filter(spider=spider_id)) @register.filter def market_timezone(iitem): return next(iitem)['market_timezone'] @register.filter def market_location(iitem): return next(iitem)['market_location'] @register.filter def market_year(iitem): return next(iitem)['market_year'] And my Django-template like this: <td>{{markets|getSpiderItem:spider.id|market_timezone}}</td> <td>{{markets|getSpiderItem:spider.id|market_location}}</td> <td>{{markets|getSpiderItem:spider.id|market_year}}</td> The First 2 function works well and the outputs don't have any problem but when I try to get the third one it returns: Exception Type: KeyError Exception Value: 'market_year' It works by itself and my database doesn't have any NULL element. I also try market_month, market_day, or another table. However, it gives me "Key Error" all the time at third return. -
Django ORM: Join two tables using a linked table
I want to integrate a function has_permission(self, permission_name) in the class Profile. For this I want to do make a ORM statement which returns a list of permission names. The data model is: 1 User has 1 Profile (extends Django's User model) Each Profile is assigned to one ProfileGroup. However, different Profiles can belong to the same ProfileGroup. Each ProfileGroup can have one or more ProfilePermissions. Groups can have the same subsets of ProfilePermissions. The Link-Table GroupPermissions handles this using two ForeignKeys instead of a ManyToMany relation. My models.py looks like this: class ProfileGroup(models.Model): name = models.CharField(max_length=64) class ProfilePermission(models.Model): name = models.CharField(max_length=64) class GroupPermissions(models.Model): group = models.ForeignKey(ProfileGroup, on_delete=models.RESTRICT) permission = models.ForeignKey(ProfilePermission, on_delete=models.RESTRICT) class Meta: constraints = [ models.UniqueConstraint(fields=['group', 'permission'], name='Unique') ] def __str__(self): return f'Group "{self.group.name}" has permission "{self.permission.name}"' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) group = models.ForeignKey(ProfileGroup, on_delete=models.RESTRICT) def __str__(self): return f'Profile of {self.user.username}' def has_permission(self, permission_name): return True The function has_permission (in the Profile class) should check if the permission permission is included in the list of Permissions. I tried it with list_of_permissions = GroupPermissions.objects.filter(group=self.group) But this returns a list of ProfilePermission. What I want is a list of names of the permission (permission.name). So I have to … -
Forms DateField with automatic separators
If i create a form with a standard forms.DateField() the user has to manually type "01-01-2001". How can i create an input such as the user types in "01012001" straight and the "-" separators will still be there as a default? Is this a django thing or javascript? If i could get some examples that would be great. -
Update Profile model that extends default User with middleware (last_activity field) DRF
I'm trying to update Profile model, which extends the default User model. But something clearly off because Profile displays no entries. Could you please suggest how to properly update model in middleware that extends another one? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) last_activity = models.DateTimeField() # filled in by middleware def __str__(self): return str(self.id) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' view.py class ProfileList(ListAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer middleware.py from django.utils import timezone class UpdateLastActivityMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_response(self, request, response): if request.user.is_authenticated(): # Update last visit time after request finished processing. # I'm trying to create record - in case user had no activity before Profile.objects.filter(user__id=request.user.pk).update_or_create(last_visit=timezone.now()) return response settings.py MIDDLEWARE = [ ... 'core.middleware.UpdateLastActivityMiddleware', ] -
Configuring existing django project on a linux shared hosting using cpanel
I want to make my django project live. I am having trouble in uploading and running my existing Django project on cpanel. -
Django, Sqlalchemy: Cannot drop table ganalytics_article because other objects depend on it
I have this models in my Django ganalytics app: class Article(models.Model): id = models.IntegerField(unique=True, primary_key=True) article_title = models.CharField(max_length=250) article_url = models.URLField(max_length=250) article_pub_date = models.DateField() def __str__(self): return "{}".format(self.article_title) class Company(models.Model): company_name = models.CharField(max_length=250) class Meta: def __str__(self): return "{}".format(company_name) class Author(models.Model): author_sf_id = models.CharField(max_length=20, null=True) author_name = models.CharField(max_length=250) class Meta: def __str__(self): return "{} - {}".format(self.author_name, self.author_sf_id) class AuthorArticleCompany(models.Model): author = models.ForeignKey(Author, to_field="id", on_delete=models.CASCADE, related_name='authorarticle_author_id') company = models.ForeignKey(Company, to_field="id", on_delete=models.CASCADE, related_name='authorarticle_company_id') article = models.ForeignKey(Article, to_field="id", on_delete=models.CASCADE, related_name='authorarticle_article_id') class Meta: def __str__(self): return "{}-{}-{}".format(self.author, self.article, self.company) class Ganalytics(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='ganalytics_author_id') totalview = models.IntegerField() totalinteractions = models.IntegerField() class Meta: def __str__(self): return "{}".format(self.article) class Unsubscribers(models.Model): email = models.EmailField() reasonwhy = models.CharField(max_length=90) class Meta: def __str__(self): return "{}".format(self.email) I am getting this error message: DETAIL: constraint ganalytics_ganalytic_article_id_d37f2464_fk_ganalytic on table ganalytics_ganalytics depends on table ganalytics_article constraint ganalytics_authorart_article_id_7f4ff374_fk_ganalytic on table ganalytics_authorarticlecompany depends on table ganalytics_article HINT: Use DROP ... CASCADE to drop the dependent objects too. [SQL: DROP TABLE ganalytics_article] I have tried to change the on_delete field to different values but it wont help. What am I doing wrong? -
Video group conference using Django
How to use Webrtc with Django ?? I think That I shall use django-webrtc module for this but i havee already tried this with node js or directly use rtcmulticonnection javascript library for room connection. Can anyone recommend me how to use Django for peer to peer mesh networking model or star networking model -
404 on a link and no idea why
I generate a link using javascript that assigns devices to a location. The underlying information comes from a product and I am using a TemplateView which redirects after it is done: class AssociateView(TemplateView): model = Product template_name = "app/product_all.html" def get(self, request, *args, **kwargs): device_ids = request.GET["device_ids"] page = request.GET["page"] ... some logic ... return redirect("product-all") the corresponding url pattern: path(r'link/<int:pk>', views.AssociateView.as_view(), name="link"), Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/link/8/?device_ids=659252%2C659260%2C743044%2C743045&page=2 The current path, link/8/, didn't match any of these. -
How can I verify user and password using Python ldap3 via OpenLdap?
For a django project, I designed a different login page. The users here will log in via openldap. I can access users' full information with their uid id, but I could not find how to verify the password. Do I need to hash the user's password and compare it with the password on ldap? Isn't there any other method? Thank you from ldap3 import Server, Connection, ALL, SUBTREE from ldap3.core.exceptions import LDAPException, LDAPBindError, LDAPSocketOpenError from ldap3.utils.conv import escape_filter_chars ldap_server_uri=f"ldap://xxx:389" ldap_base = 'dc=xx,dc=xx,dc=xx' def ldap(uid,password): try: ldap_server = Server(ldap_server_uri, get_info=ALL) ldap_connection = Connection(ldap_server, user = 'uid=admin,ou=xx,dc=xx,dc=xx',password='adminpassword') if ldap_connection.bind() == True: if ldap_connection.search(search_base=ldap_base, search_filter=f'(uid={uid})',search_scope = SUBTREE, attributes=['uid']) == True: ent = ldap_connection.entries[0] entry = {'uid': ent['uid']} ldap_connection.unbind() return entry else: return None except LDAPSocketOpenError: print('Unabled to connect to the LDAP server!') return None -
django cannot overwrite STATIC_URL
I want to upload my static files to my azure blob, and I changed the default static url to STATIC_URL = "https://myazurestorage.blob.core.windows.net/static/" STATIC_ROOT = os.path.join(STATIC_URL, 'staticfiles') and I have this settings in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'adminrestrict', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] 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', 'adminrestrict.middleware.AdminPagesRestrictMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.static', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', if I print out {{STATIC_URL}} in my html files, it always shows /static/ I have been stuck in this problem for a few hours, can anyone give me a hint, please. -
override __str__ method that allow display conditionnal string based on browser language
I have a Django project that is internationalized I have a model Pays that contain 2 fields (french and english) to manage translation In my form, I have a ModelChoice Field that display a list of country in french How can I manage language in Pays model str method ? def __str__(self): return f"{self.pay_nom_eng}" ... self.language = request.session.get('language') PAYS = Pays.objects.filter(pay_ran = 1).order_by('pay_ide') ... self.fields["pay_ide"] = forms.ModelChoiceField(queryset = PAYS, label = _("Country"), widget = forms.Select) -
Django static file href incorrectly formatted
So I have the following static loading in Django with DEBUG=True: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> Now in my settings.py I have the following: STATIC_URL = "/static/" When I run the server python manage.py runserver and inspect my webpage in the console, the sources appear correctly, but the href attribute points to /static/css/styles.css, rather than static/css/styles.css (notice the omission of the leading /). Notice that the href on line 18 points to the wrong folder, but static/css appears correctly in the sources. So, clearly django, behind the scenes, just replaces {% static 'css/styles.css' %} with STATIC_URL + 'css/styles.css'. If I now change STATIC_URL to STATIC_URL = "static/" The href is correct (points to the right file) but the files themselves are not present!! So in order for the css file to appear, STATIC_URL needs to be /static/, but the href references a non-existent directory. If I change STATIC_URL to static/ the href is correct, but the files don't appear! Does anyone know how to fix this? I feel like it's such a basic problem, but it's doing my head in... -
How can I print the respnse json format datat in a table format in jinja template? Every time when I hit url I got 'Could not parse the remainder:'
"I want to print these response in template in table format using django but it gives "could not parse".I tried to resolve but failed. Someone please help.Below is the response which I am getting and want to print in template.I get this data when I hit an url in views.py file." { "display_free": 1, "display_paid": 1, "free": [ { "city": "", "confEndDate": "19 Feb, 2020", "confName": "AWS Innovate Online Conference", "confRegUrl": "https://aws.amazon.com/events/aws-innovate/machine-learning/", "confStartDate": "19 Feb, 2020", "confUrl": "https://aws.amazon.com/events/aws-innovate/machine-learning/", "conference_id": 1579503272, "country": "", "emailId": "", "entryType": "Free", "imageURL": "https://storage.googleapis.com/konfhub-bd9c9.appspot.com/54497.jpg?Expires=4733103270&GoogleAccessId=firebase-adminsdk-r3qh4%40konfhub-bd9c9.iam.gserviceaccount.com&Signature=GSihzq4Vf8koeEGcawKXeQmwT%2FQLZhooWUS%2BqJeNtPXtJqnNfky%2F5RgeOTEWKYCEjqAGFLSEx02cCdZ8CBTO7T2HlMjAZl6yTmDRMTH5mNawUHOrxqjsiNzSwCj4KLqHo8KlEqQrgE%2FTbxmWpT28zKfoOS20C88HrDXFMELmj5aHi4f0V%2BTF30rIlQJkNlFy6fkko2ipkLLxtYOMh0i%2B0tV1vZ0gI21mlpyNzfn6hC%2BGtN1BIz4BciB4IpMkkw7FUydFbXwJOVNm2FJs9AafozJdwdy0gOCtFDrMB2wY8JiPL2oSa%2BkBFlhIgjnIg3LaCPlfj%2Bqn9FTT%2FP5TrOioSg%3D%3D", "keywordSupport": " Artificial Intelligence ,Machine Learning,Cloud", "lat": "", "long": "", "searchTerms": " AWS Innovate Online Conference, Artificial Intelligence ,Machine Learning,Cloud, Online, February, Free, 1579503272, India", "state": "", "twitter_handle": "", "user_id": "1578287153", "venue": "Online" }, { "city": "Bangalore", "confEndDate": "22 Jan, 2020", "confName": "Redis Day Bangalore", "confRegUrl": "https://connect.redislabs.com/redisdaybangalore", "confStartDate": "21 Jan, 2020", "confUrl": "https://connect.redislabs.com/redisdaybangalore", "conference_id": 1578891826, "country": "India", "emailId": "", "entryType": "Free", "imageURL": "\"https://storage.googleapis.com/konfhub-bd9c9.appspot.com/5887.jpg?Expires=4732491826&GoogleAccessId=firebase-adminsdk-r3qh4%40konfhub-bd9c9.iam.gserviceaccount.com&Signature=JF33AcXB854Ndqw4VRN29NTQow51wGfuCSnAMIvmUUuZcmUEto3eREIrNYgqKqUpuRvGG8NIw3or6Jj8uTtl5dWVNaI93S5heRFhl3NJ1fj9zETiNE9tp6gcv1BiIkyJGCEJzXWxgUpNuqrq%2BUPzQGq4o6w1bQ0izgFP%2Fe5XhvOQmYvWDpnvsltvdppY8%2FFuVm3G13xZH3h5utMleXXqcKjGkf%2FqXHf4gSrMESrfbAZ0MPXRhZS9mGxiE2hg7DHcOweZkEY6spfLrVS2%2BEIePF4ZeXNDeDxv3bgOH6hX3VlyQFKcRCvvDzVWpvYubr0d8PJ7DK9OuMZWMmXe96BK9A%3D%3D\"", "keywordSupport": " Redis, Redis Clustering, Probabilistic Data Structures", "lat": "13.0291377", "long": "77.540708", "searchTerms": " Redis, Redis Clustering, Probabilistic Data Structures, Redis Day Bangalore, Bangalore, January, Free, 1578891826, India", "state": "Karnataka", "twitter_handle": "@redislabs", "user_id": "1578287153", "venue": "Taj Yeshwantpur, Bengaluru, 2275, Tumkur Road, Yeshwanthpur Industrial Area, Phase 1, Yeshwantpur, Bengaluru, Karnataka … -
django login not redirecting to index
I have got a login screen, which upon successful authentication should show user details on the same base URL , it used to work just fine all these days, and all of a sudden it's throwing 302 response code HTTP POST /login/ 302 [0.60, 127.0.0.1:53864] when the correct username and password is entered, no redirection is initiated, it forever keeps loading. What's more strange is that when I reload the same tab or open a new tab, it is correctly logged in and shows the appropriate details. No changes related to login functionality were made, the only recent change I made was to add reset password functionality which had nothing to do with this. user_login def user_login(request): field = None if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) try: field = UserModel.objects.get(user__username=username) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: messages.error(request,'username or password not correct') return HttpResponseRedirect('../') else: print("Error logging in{}".format(password)) messages.error(request,'Invalid username/password combination') return HttpResponseRedirect('../') except Exception: #return HttpResponse("ACCOUNT NOT ACTIVE!!!") messages.error(request,'Entered username does not belong to any account') return HttpResponseRedirect('../') else: return render(request,'app/login.html',{}) urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^$',views.IndexView.as_view(),name='index'), url(r'login/',views.user_login,name='login'),] It was working without any problems all these days, not sure of … -
Why is my django app deployed on heroku not working when debug=False?
My django app deployed on heroku doesn't work when debug is set to False, it works locally(both when debug is True and False), but I get a '500 internal server error' when I deploy my app with debug set to false, what is causing this? This is the settings file: import os from datetime import timedelta import dj_database_url import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! if os.environ.get('LOCAL') == 1: DEBUG = True SECURE_SSL_REDIRECT = False else: DEBUG = False SECURE_SSL_REDIRECT = True ALLOWED_HOSTS = ['selamselam.herokuapp.com', 'localhost'] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'api', 'frontend', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'graphene_django', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = 'feel.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Change the things right now # https://docs.djangoproject.com/en/3.0/howto/static-files/ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) WSGI_APPLICATION = 'feel.wsgi.application' … -
Will this QuerySet hit database twice or once?
organizations = Organization.objects().all() for organization in organizations: pass ids = organizations.values_list("id", flat=True) So I assign the QuerySet to a variable then loop over all instances in the QuerySet. Then I call values_list on the same variable. Will values_list cause another database access or will the instances fetched while iterating over them be reused to create the list? -
how to see data of user specified through django-table2?
Hello i want to make a table where one can see only his created rows and not others so i have specified a user for everyrow previously i used it like this - def see(request): as=A.objects.filter(user=request.user) return render(request,'m/see.html',{'as':as}) this was working perfectly fine later i rendered a table through Django table 2 my tables .py is class ATable(tables.Table): class Meta: model = A exclude = ('aid',) per_page = 2 i want to make it user specific so that i can only see data entered from myuserid not all my filter.py code is class AFilter(df.FilterSet): class Meta: model = A exclude = ('aid',) kindly help what and where should i write to specify the user -
Performance issue with Django and Postgres on a single update
I have an intermittent performance issue with Django and Postgres when updating a single line in a small "< 1m" rows table. The APM reports the issue on the update line, which is: Model.objects.filter(id=model_id).update(field=True) The error is raised because the execution takes more than 5s. This code runs in a celery task which receives the id of the model as the argument and executes normally most of the time. I know it's a very open question but any idea or help on what might be happening is appreciated. I'm running out Python 3.7, Django 2.0.13, and Postgres 9.5. -
How to show Data In database (SQL Server) On Django Admin
I have a project working with sqlite3 (default database) and I am trying to use Microsoft SQL Server instead. I need to do get data from my SQL Server database to Django Admin pages. -
Keep selected options after form submit in Django
I have a ModelForm for filter datas. I would like to keep selected options after form submit.There is any Django's solution for this problem? I did find any good solution yet. My model form: class ELearningFilterForm(forms.ModelForm): class Meta: model = ELearning fields = ('e_learning_type', 'e_learning_name', 'specializations') widgets = { 'specializations': forms.CheckboxSelectMultiple(), 'e_learning_type': forms.RadioSelect() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['e_learning_name'].required = False -
Computional complexity of reversed Foreign Key reference [closed]
I got such models in Django: class Artist(models.Model): name = models.CharField(max_length=128) class Sons(models.Model): title = models.CharField(max_length=128) artist = models.ForeignKey(Artist, on_delete=models.DO_NOTHING) Let's say there are 1000 songs in total, while Artist1 has just 10 songs. When I do basic ORM query like Artist.objects.first().songs.all(), does it need to check every of 1000 songs if it is related to the Artist1 or it "knows" which 10 to get? In other words, does the cost of retrieving those 10 songs increase as the next songs get created? -
How to save an image to a customized filepath in django admin?
I am trying to upload images to specific folders I select. the model code is as below: class PhotosTags(models.Model): Tag_name = models.CharField('Tag Name', max_length=100, default='NA', unique=True) Description = models.TextField('Tag Description', max_length=200, blank=True) class Meta: verbose_name = 'Tags' verbose_name_plural = verbose_name ordering = ['Date_created'] def __str__(self): return str(self.Tag_name) class Photos(models.Model): Name = models.TextField('Photo Name', max_length=200, blank=True) Tag = models.ForeignKey(PhotosTags, on_delete=models.CASCADE, default=None) filepath = 'Gallery' Photo = models.ImageField(upload_to=filepath, blank=False) class Meta: verbose_name = 'Photos' verbose_name_plural = verbose_name ordering = ['Date_uploaded'] pre_save.connect(upload_photo, sender=Photos) Here each tag has its own folder. The function I want to realize is, when I upload an image, I can select a specific tag (through selection of "Tag") and then this image can be uploaded to that folder. I tried use: signals to change the filepath but failed. The code i wrote is: def upload_photo(sender, instance, **kwargs): tardir = instance.Tag.Tag_name instance.filepath = 'Gallery'+'/'+tardir