Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
attribute error: 'int' object has no attribute 'get'
i am trying to make this request for a checkout id in a payment process and this is my code so far. the code below works fine and i get a response from it, but as soon as I add some of the commented parts to the data dictionary it gives me an attribute error saying that int has no object get. basically, i seem to only be able to add keys and string or number values to my data dict, but whenever i add a dict as a value it starts giving me the error. i have no idea why this is happening, can anyone help? thanks in advance! def request_checkout_id(request): user = request.user url = "https://xxxxxx" entity_id = 'xxxxx' auth_header = 'xxxxx' currency = 'USD' try: ref_code = request.session['ref_code'] order = Order.objects.get(ref_code=ref_code) except: ref_code = None return redirect(reverse('shop:cart')) amount = float(order.final_total) base_con_tarifa = order.cart.total valor_iva = order.cart.tax_total #total_con_iva = order.sub_total base_sin_tarifa = order.shipping_price custom_param = '0081004012'+ str(valor_iva).replace(".", "").zfill(12) + '052012' + str(base_sin_tarifa).replace(".", "").zfill(12) + '003007010391005100817913101053012' + str(base_con_tarifa).replace(".", "").zfill(12) print(custom_param) data = {} # cart = {} # items = [] # i = 0 # for item in order.cart.cartitem_set.all(): # items.append({}) # items[i]['name'] = item.product.name # items[i]['description'] = … -
Django Crispy Forms: Set rows for Text Area
When creating a Form with FormHelper(), the text areas of my form (for TextFields) are too big: They are set to 10 rows. I'd like to set the number of rows. How can I do that? My code: models.py: from django.db import models class Spam(models.Model). ham = models.CharField(max_length=10, blank=True, null=False, default='Some ham') eggs = models.TextField(blank=True, null=False, default='', verbose_name="Lots of eggs") forms.py: from django import forms from crispy_forms.helper import FormHelper from crispyy_forms.layout import (Layout, Row, Column) from .models import Spam class SpamForm(forms.ModelForm): class Meta(): model = Spam fields = ('ham', 'eggs') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout( Row(Column('ham', css_class='form-group col-12')), Row(Column('eggs', css_class='form-group col-12')), # HERE: How can I set the rows for the text area widget? ) Resulting HTML: <!-- (ommited for brevity) --> <div class="form-row " > <div class="form_group col-12" rows="2"> <div id="div_id_eggs" class="form-group"> <label for="eggs" class="">Lots of eggs</label> <div class=""> <textarea name="eggs" cols="40" rows="10" class="textarea form-control" id="eggs"></textarea> <!-- ^^^^^^^^ <!-- THIS is what I'd like to change to "2" --> </div> </div> </div> </div> <!-- (ommited for brevity) --> -
Django template does not exist include or extends tags
I am creating a Django project. My question is simple I believe but I am having a tough time trying to figure it out. I have an index.html in which I want to render certain things. I decided that I don't want to have a html header for every one of my html pages which to me is insane. I created a base.html file to contain a html header and I want to reuse this for my other html files but how do I do this exactly, that is if it's possible. So what I am mostly not sure about is which tag to use {% include "base.html" %} or {% extends "base.html"%}. Intuition is telling me I should use {% include "base.html" %} because I don't believe I should be inheriting. And then my second question which relates close to this is how do I even include or extends. I just created a base.html file and an index.html file and have a index view in my views file which renders the index.html with context. Everything works fine if I were to just use the index.html file but when I do {% include "base.html" %} in my index.html file it … -
Cannot set django user password
email or username is captured and stored in userinput userinput = request.POST['usrmail'] if(re.search(regex,userinput)): # username = userinput.split("@")[0] try: userdelta = get_object_or_404(MyUser, email=userinput) except MyUser.DoesNotExist: pass else: try: userdelta = get_object_or_404(MyUser, username=userinput) except MyUser.DoesNotExist: context = {'error': 'Kindly get registered'} return render(request, 'am/forgotpassword.html', context) userpassword = MyUser.objects.make_random_password(length=8) <This line doesn't works> userdelta.set_password(userpassword) -
Deleted a folder, get ModuleNotFoundError: No module named "api"
I am using Django and trying to use Django Rest Framework as well. Since I had never used Django Rest Framework, I did a kind of tutorial by following an article. To do this, I created a new app by entering python manage.py startapp app. After I finished the tutorial, I deleted this app in order to work on my project. However, when I try to make the server run I got this error. (venv) (base) MacBook-Air-4:extra_exchange user$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/user/Desktop/my_project/extra_exchange/venv/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ … -
how to make print first page have a diffrent margin, django
how can i make the first print page have a different margin? i use xhtml2pdf to convert html to pdf i already try to use @page { size: A4; margin-top: 2.54cm; margin-bottom:2.54cm ; } @page :first{ margin-top: 10cm; } but i getting error page = page + '_' + pseudopage TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' so how i can make a different margin in first print page? -
Django - how to delete a user/profile with a delete button
Hey I have a delete button on my profile page views.py def list_all(request): context = { 'users': User.objects.all } return render(request, 'users/list_all.html', context) signals.py @receiver(post_save, sender=User) def delete_profile(sender, instance, created, **kwargs): if created: Profile.objects.delete(user=instance) models.py def __delete__(self, instance): super().delete() forms.py class ProfileDeleteForm(forms.ModelForm): class Meta: list_all.html {% extends "myfarm/base.html" %} {% load static %} {% block content %} {% for user in user %} <p>Username: {{ user.username }}</p> {% endfor %} {% endblock content %} Right now I only get a message that I usually get for when I press the "update" button. What do I need to add in order to delete the user from the data base ? -
Django check Windows ID in user_passes_test
I am trying to check to see if a user is in a particular user group in my Django application. Here is my current code that works perfectly fine: def user_check_group(user): return user.groups.filter(name='group').exists() @user_passes_test(user_check_group) def myview(request): # renders my view However, this requires users to be logged into the application, which I really don't want them to have to do. I want to be able to verify by the Windows username rather than the user logged into the Django application. I understand there are security concerns doing this method, but lets put those aside for now. What I tried to do: def user_check_group(user): username = os.environ.get('USERNAME') return username.groups.filter(name='group').exists() This properly fetches the Windows username, but I get an error 'str' object has no attribute 'groups'. I know why this is happening, but don't know how to access the groups to check for a windows username instead of the Django username. Any ideas? -
I added a 'name' field to my django custom user, It is requested on creation but gets saved as a default 'objects' for all created users
I added a field 'name' to my custom Django user model, it is requested when I run createsuperuser and even when I create a normal user from the shell with create_user(), but when I query all my User objects, they all have a default value of 'objects' stored in user.name and that is what is displayed on the admin site too. I have tried to modify the manager by adding user.name = name before the save() method but I still get the same result. my models.py: from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class User(AbstractUser): email = models.EmailField(_('email address'), unique=True, blank=False) name = models.CharField( _('full name'), max_length=100, blank=False, null=False) username = None USERNAME_FIELD = 'email' NAME_FIELD = 'name' def get_full_name(self): return self.name.strip().title() def get_short_name(self): return self.name.title().split()[0] def __str__(self): return self.get_full_name() REQUIRED_FIELDS = ['name', ] objects = CustomUserManager() my managers.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, name, password, **extra_fields): """ Create and save a User with the given email, name and password. """ if … -
How to send images in email through django
This is in my views.py : subject='Thank you for your order from cottgin.in' message=f'Your order id is {a}' from_email=settings.EMAIL_HOST_USER to_list=[order.customer.user.email] send_mail(subject,message,from_email,to_list,fail_silently=True) I am sending the order info to the user after he places the order but I also want to send some images like the item images as well as the logo . how do i do that.Can I send a html template in mail? I havent found any proper solution to this on internet so any help would be appreciated. -
Filter Django model based on its JSON field
I have the following model: class SavedVariant(models.Model): variant_id = models.TextField(db_index=True) saved_variant_json = JSONField(default=dict) saved_variant_json has a field called transcripts and what I want is to introduce a query Q2() to add it to exiting query Q1() to filter for the content of the transcripts field. Basically what I am trying to avoid is the conversion of the QuerySet into list, parsing json, doing comparisons, etc. Is it possible to do at all? I have initial filtering done with SavedVariant.objects.filter(Q1) and I want to do smth like SavedVariant.objects.filter(Q1).filter(Q2) (or combine both queries: Q3 = Q1 & Q2 using just one filter). If I get a list of SavedVariantmodels, then I would face the issue of rewriting many functions downstream which I don't want to do. -
Why would Submit button stop working by changing from {{ form|crispy }} to listing fields using |as_crispy_field?
I am creating a django app and using crispy forms. The app was working fine and I decided I wanted to change the layout of certain pages. For example, instead of the page listing city, state, and zip on separate lines, I wanted them horizontally side-by-side. I read about how to do this using |as_crispy_field. The only change I made was in my template. I replaced... {{ form|crispy }} with {{ form.company|as_crispy_field }} {{ form.address|as_crispy_field }} {{ form.address2|as_crispy_field }} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.city|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.state|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.zip|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.metro_area|as_crispy_field }} </div> <div class="form-group col-md-5 mb-0 ml-5"> {{ form.phone|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.candidate_pros_and_cons|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.benefits|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-3 mb-0"> {{ form.fee_percentage|as_crispy_field }} </div> <div class="form-group col-md-9 mb-0"> {{ form.fee_structure|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.website|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.linkedin|as_crispy_field }} </div> </div> {{ form.industry|as_crispy_field }} {{ form.notes|as_crispy_field }} This, including my submit button to Post, is contained within the … -
Django filter: different results in filtering between SQLite and PostgreSQL
I have a relatively simple query running on a database table; the filter checks the value of 2 date fields and returns a queryset. The fields checked are authored_report_received and subbed_complete. If authored_report_received has a date set AND subbed_complete has no date set, then a result will be returned. If both these fields have a date set then no results are returned. (A simple calculation for the 'days outstanding' between any result returned and the current date is then made.) This works absolutely fine running locally on a SQLite database but when I upload to heroku to be used with a PostgreSQL database, the filter does not seem to work in that it seems to ignore any date value in the subbed_complete field. I do not understand why not. Is there a difference between the way SQLite and PostgreSQL handles the filters? I can't find any docs which indicate this. # views.py class EpgReportSubeditListView(LoginRequiredMixin, EpgUserPassesTestMixin, ListView): """EPG-only: create a list view of reports currently being subedited """ model = Report template_name = 'tracker/epg_report_subedit.html' context_object_name = 'report_subedit' ordering = ['subeditor'] def get_queryset(self): today = datetime.now().date() out = [] for obj in (self.model.objects.filter(subbed_complete__isnull=True) and self.model.objects.filter(authored_report_received__isnull=False)): setattr(obj, 'days_diff', (today - obj.authored_report_received).days) out.append(obj) return … -
Django loaddata error with oracle CLOB fields/
I have a django project with an oracle backend where I am trying to migrate existing data to a new server. I normally use Postgresql and have limited knowledge of oracle quirks. I've exported the data using python manage.py dumpdata > allmydata.json without a problem. When I go to load the data using python manage.py loaddata allmydata.json I get the following error. ORA-24816: Expanded non LONG bind data supplied after actual LONG or LOB column About half of data loads before I hit this error. My understanding is that all of my LOB columns should be the end of the sql query. My question is how do I make this happen both for loadingdata and for normal operations? Is there a way to force the Django ORM to construct a query in a specific manner? If I change the order of field definitions in the model will that do? The database I am loading into is clean, so I can drop everything if needed. -
Why Django from in Invalid?
I create a django form. I am also inserting the valid values in the form field but still getting form not valid error. I used the same code yesterday and it was working fine, but I don't know why its giving the not valid error, What might be the reason for this? Here is My Code: View.py from django.shortcuts import render,redirect from django.views.generic import View,TemplateView from .forms import Registration_Form from .models import User_Registration from django.contrib import messages # Create your views here. class MainPageView(TemplateView): template_name='main.html' class LoginView(TemplateView): template_name='login.html' def RegistrationView(request): form=Registration_Form() if request.method=='POST': print(request.POST) if form.is_valid(): form.save() print("Valid") return redirect('login_view') else: print("Not Valid") # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) # template_name='registration.html' forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } registration.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="form-group"> <br><br><br> <h2 style="padding-left: 480px;">Registration Form</h2> <br> <form method="POST" action=""> {{form.as_p}} {% csrf_token %} <input type="submit" value="Submit"> </form> </div> </body> </html> -
"Can't find camera" on local machine triggered from OpenCV
[ WARN:0] global /tmp/pip-req-build-6179nsls/opencv/modules/videoio/src/cap_v4l.cpp (880) open VIDEOIO(V4L2): can't find camera device I'am getting this error while trying to access my webcam I've also tried parameters 0 and -1 in the method cv2.VideoCapture() method as they seem to work in some cases. Is there any way to access the webcam? -
How to import django template library globally?
I have a main template main.html from which I extend from, I want to load the i18m library on it or globally to evade using {% load i18n %} everywhere. How i could do that? -
Can I get AdminEmailHandler to give me a traceback for logging.error level?
I have my Django instance configured with "mail_admins": { "level": "ERROR", "class": "django.utils.log.AdminEmailHandler", }, When I get logging.error() messages, I don't know where they were generated and would like to in order to possibly change their level to squelch noise. Adding include_html=True did not add a stack trace. I've looked through AdminEmailHandler and I haven't found an obvious way to hook this capability in. -
How to run Django FSM first project
I have below django-program--- walk.py from django.db import models from django_fsm import transition, FSMIntegerField from django_fsm import FSMField, transition import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command class Order(models.Model): STATUS_GO = 0 STATUS_COME =1 STATUS_CHOICES = ( (STATUS_GO, 'GO'), (STATUS_COME,'come') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices=STATUS_CHOICES, default=STATUS_GO, protected=True) @transition(field=status, source=[STATUS_GO], target=STATUS_COME) def walk(self): print("Target moved") Above code is available in c:\Hello folder. I have referred few blogs & link for creating new django project. so in cmd window, dragged to above folder by "cd c:\Hello" & executed: django-admin startproject mysite And moved walk.py into mysite folder And the directory as : Hello/ mysite/ manage.py walk.py mysite/ __init__.py settings.py urls.py wsgi.py And Later executed: python manage.py migrate python manage.py runserver Post which i have been stuck now & confused above two steps is required for my project. Do python manage.py startapp polls is mandate to run now ? If so, what to edit in polls/models.py file ?? Later what do i need to mention in INSTALLED_APPS = [] ??? And keep moving further, where do i place my project walk.py in above directory ? Now when i run the walk.py , i could see below issue now: … -
DRF How to retrieve auth user info?
Now I can just get info by id. -> user/{id} I want to retrieve self auth user and get his information by default like user My view class UserInfoViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.UserFollowersSerializer def get_queryset(self): return User.objects.filter(privacy__is_public=True) -
view User model under Teacher model in admin page which has one to one relation with User in Django
Here is models.py file. here Teacher has a foreign key relation with User. from django.db import models from django.contrib.auth.models import User from django.db import models from django.conf import settings from django.utils.text import slugify from django.urls import reverse # Create your models here. import misaka from departments.models import Department teacher_rank = [ ("Lecturer", "Lecturer"), ("Assistant professor", "Assistant professor"), ("Associate professor", "Associate professor"), ("Professor", "Professor"), ("Professor emeritus", "Professor emeritus"), ] class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey(Department,blank=False, related_name="teachers", on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='teachers/profile_pics', blank=True) Teacher_ID = models.CharField(max_length=20, unique=True, blank=False) portfolio_site = models.URLField(blank=True) academic_rank = models.CharField(blank=False, max_length=100, choices=teacher_rank) teacher_slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): self.teacher_slug = slugify(self.user.username) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("teachers:teacher_detail", kwargs={"department_slug":self.department.department_slug, "teacher_slug":self.teacher_slug}) class Meta: ordering = ["Teacher_ID"] unique_together = ["Teacher_ID", "department"] Here the details of teacher model is viewed under User model in admin page of django. admin.py file from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User # Register your models here. from .models import Teacher class TeacherInline(admin.StackedInline): model = Teacher can_delete = False verbose_name_plural = "teacher" fk_name = 'user' class TeacherAdmin(UserAdmin): inlines = (TeacherInline, ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(TeacherAdmin, self).get_inline_instances(request, obj) … -
how to use google login link to my login page using django-allauth?
I have created a project which is working nicely. I have a login page, signup page and profile page as myspace. I just want to add an additional funtionality to my login page which is a user can login using google, fb, or instagram. but when i added the django-allauth to my project. it overwrite the existing login page. I just want to add an icon of google login. and not the whole page how i can do so. -
New line not rendering from template tag in HTML
I have a set of information to be rendered on my webpage using django template tags. {% for product in sales %} <div> <span>Customer:{{product.to_user}}</span><br> <span>{{product.time}}</span><br> <p class="message">{{product.message}}</p> </div> {% endfor %} The {{product.message}} template tag contains information separated by new line('\n'). But, newlines are not rendered in HTML, the information is displayed in a single line omitting to obey '\n'. I tried capturing the information from the <p> tag and replacing \n, with <br>, and again setting the text in the same <p> tag. But it doesn't seem to work. This was my approach, as stated above. $(document).ready(function(){ let renderedText = $(".message").text() //alert(renderedText) final_txt = renderedText.replace(/\n/g,"<br>") $(".message").val(final_txt) }) What changes or addition should I make, in order to get this working? Thanks in advance. -
DRF Set base case for RecursiveSerializer
Currently i'm trying to understand how to make a tree representation of a self referentiated model, but im failing to grasp how this recursion works. Currently I have 5 users and my output is as follows: { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ { "user": "user_5", "sponsor": 4, "reply_set": [] } ] } ] } ] } ] }, ... But I would like to set a limit to the recursion, giving me a tree with with the relations between the user_1 and user_4 only (between only 4 users). { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ ] } ] } ] } ] }, In the case above, the user_5 still exists and have the user_4 as it's parent, but I do not want to show him in the user_1 tree. Only the relationships between 4 users. My model # models.py class SponsorTree(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) sponsor = models.ForeignKey('self', related_name='reply_set', null=True, on_delete=models.SET_NULL) points = models.DecimalField(default=0, max_digits=900, … -
Creating a folder automatically in Django
So I am trying to create a folder automatically for each user in Django, once they sign up. What I tried: #Creating a folder automatically for each user def folder_path(instance, filename): return "user_{0}/MyFolder/{1}".format(instance.user.id, filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I also tried: #Creating a folder automatically for each user def folder_path(instance, filename): user = instance.user.username basename, file_extension = filename.split(".") new_filename = "%s-%s.%s" %(user, instance.id, file_extension) return "MyFolder/%s/%s" %(user, new_filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I want to know why its not working. Thanks.