Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Share data between base class and Meta class
I have the following django model: class Article(models.Model): filename = models.CharField(max_length=255) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) keys = ['filename', 'collection'] class Meta: constraints = [ models.UniqueConstraint( fields=['filename', 'collection'], name='article_key') ] As you can see I've defined the same list ['filename', 'collection'] in both the base class and the Meta class. I would like to define it once. I can't define it in Meta because then I get 'Meta got an unrecognised attribute 'keys'. So I must define it in the base class and access it from Meta. I don't know how to share data between the two. I've tried doing: self.keys in Meta but that gives 'self is not defined'. I've also tried with just 'keys' but that's also not defined. Any tips? Thanks. -
Invalid Registration in PyFCM
I have following code in django but getting {'error': 'InvalidRegistration'} from pyfcm import FCMNotification apikey ="apikey" push_service = FCMNotification(api_key=apikey) registration_id = "device token" message_title = "Uber update" message_body = "Hope you're having fun this weekend, don't forget to check today's news" result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) print (result) -
primary number from excel sheet is not valid, the validation is not happening for secondary number. I have 5 fields in excel sheet
I am uploading a excel sheet which has 5 fields( name, primary phone number, secondary phone number, primary email, secondary email). If the primary phone number is not valid, then the secondary phone number is not getting validated. Please find the below code: ''' if form.is_valid(): if str(upload_csv.check_phone_number(request.POST.get( 'primary_phone_number').lstrip())) not in contact_list.contacts.all().values_list( 'primary_phone_number'): primary_phone_n = upload_csv.check_phone_number(request.POST.get('primary_phone_number')) user_contact = Contact.objects.create(name=request.POST.get('name'), primary_phone_number=primary_phone_n) upload_csv.merge_attribute(user_contact, 'secondary_phone_number', upload_csv.check_phone_number( request.POST.get('secondary_phone_number')), 'primary_phone_number') upload_csv.merge_attribute(user_contact, 'primary_email', upload_csv.check_email(request.POST.get('primary_email')), 'secondary_email') upload_csv.merge_attribute(user_contact, 'secondary_email', upload_csv.check_email(request.POST.get('secondary_email')), 'primary_email') user_contact.save() contact_list.contacts.add(user_contact) What am I doing wrong? -
select_related in custom manager not working in django admin?
I'm trying to implement select_related in a custom manager in order to optimize the number of database queries in django admin. managers.py: class TargetShapeColorManager(models.Manager): def get_queryset(self): return TargetShapeColorQuerySet(self.model, using=self._db) def add_base_target_shape_data(self): return self.get_queryset().select_related('base_target_shape').add_base_target_shape_data() admin.py: class TargetShapeColorAdmin(admin.ModelAdmin): model = TargetShapeColor def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.add_base_target_shape_data() When I run it as such, I have 7 queries (including 3 similar corresponding to the 3 of 'base_target_shape' that should have been avoided by the select_related) If the select_related is located in the admin (see below), everything is fine and I have only 4 queries as expected. managers.py: class TargetShapeColorManager(models.Manager): def get_queryset(self): return TargetShapeColorQuerySet(self.model, using=self._db) def add_base_target_shape_data(self): return self.get_queryset().add_base_target_shape_data() admin.py: class TargetShapeColorAdmin(admin.ModelAdmin): model = TargetShapeColor def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.select_related('base_target_shape').add_base_target_shape_data() Could anyone tell me if it is a normal behavior ? and explain me why it does not work when the select_related('base_target_shape') is located within the custom manager ? Thanks in advance -
Osticket ORM - join table dynamically
OsTicket uses custom PHP ORM based on Django. Is there a way I can join tables with variable as constraint? Use case: Few years ago I wrote a "Read/unread mod". It highlights tickets agent did not read after last change. Simply it highlights tickets after update until you open and read it. Now I am porting this mod to version 1.14 and use the new ORM. When agent reads ticket page, this datetime is stored into my custom ost_ticket_stafflastvisit table (definition bellow). When searching tickets I want to extend result with time, when actual agent had seen the ticket (stafflastvisit). If this time is lower or NULL than ticket.updated time, I can tell that there a was a ticket change after last agent visit and mark it as unread. The point is I have to join tables on constraint $thisstaff->getId() => 'TicketStaffLastVisit.staff_id' (see bellow), what obviously does not work. Is there a way I can create this JOIN or simmilar behaviour? My custom table: CREATE TABLE `ost_ticket_stafflastvisit` ( `ticket_id` int(11) unsigned NOT NULL, `staff_id` int(11) unsigned NOT NULL, `lastvisit_date` datetime NOT NULL DEFAULT '2015-01-01 12:00:00', PRIMARY KEY (`ticket_id`,`staff_id`), KEY `FK_staff_id` (`staff_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 class.search.php class UnreadChoiceField extends ChoiceField … -
How to get list instead of QuerySet class list in Django 2.2.6 version?
Currently I have migrated my py2 project in py3 django project & I am facing problem because of QuerySet word in new project. Py2 code & output Contact.objects.filter(is_default = False).values_list('name', flat= True)[:2] [u'town', u'country'] Py3 code & output Contact.objects.filter(is_default = False).values_list('name', flat= True)[:2] <QuerySet ['town', 'country']> I want to have same output as I am getting in py2 without QuerySet & does anyone have idea how should I do it? Why does this extra QuerySet included in Django new version. Thanks. -
IntegrityError at /home/create/ (1048, "Column 'country_id' cannot be null")
I'm trying to create news directly on the webpage using Django 2.7, but have a problem with adding categories and countries IntegrityError at /home/create/ (1048, "Column 'country_id' cannot be null") Here is my code: home/models.py class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Country(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class News(models.Model): pub_date = models.DateTimeField('Date: ') article = models.CharField(max_length=200) content = models.TextField(default="") country = models.ForeignKey(Country, on_delete=models.CASCADE) likes = models.IntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.article def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) home/views.py def create(request): if request.method == "POST": adding = News() adding.likes = 0 adding.pub_date = timezone.now() adding.article = request.POST.get("Article") adding.content = request.POST.get("Content") adding.category = request.POST.get("Category") adding.country = request.POST.get("Country") adding.save() return HttpResponseRedirect("/home/") home/urls.py from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('<int:news_id>/', views.detail, name='detail'), path('create/', views.create), path('<int:news_id>/delete/', views.delete_news, name='delete'), ] index.html (I add my posts from my home page) <body> <form method="POST" action="create/" class="post_form"> {% csrf_token %} <p> <label>Article</label><br> <input type="text" name="Article" /> </p> <p> <label>Content</label><br> <input type="text" name="Content" /> </p> <p> <label>Category</label><br> <select> {% if category %} {% for el in category %} <option name="Category">{{ el.name }}</option> {% endfor %} {% endif %} … -
getting first record from a group using django-haystack from ElasticSearch
Here is my models. class RestaurantModel(models.Model): name = models.CharField(max_length=300, db_index=True) address = models.TextField(null=True, blank=True) contact = PhoneNumberField(null=True, blank=True) chain = models.ForeignKey(Chain, related_name="restaurant_chain", on_delete=models.DO_NOTHING, null=True, blank=True) publish = models.BooleanField('Publish Status', default=False) latitude = models.DecimalField(max_digits=10, decimal_places=7, default=40.7128) longitude = models.DecimalField(max_digits=10, decimal_places=7, default=74.0060) location = GisModels.PointField(geography=True, srid=4326, default=Point(-73.935242, 40.7306)) I am using django-haystack to create document and search from elastic search. Now problem is, I need all restaurant order by distance and one restaurant from a chain, if chain is null then all restaurant. -
change the parameters on httpd.conf file by using docker
I use docker. I try to change the parameter Timeout on httpd.conf file: TypesConfig '/etc/mime.types' HostnameLookups Off MaxMemFree 64 Timeout 60 ListenBacklog 500 The problem is that it need restart the docker for save the changes by the docker down and docker-compose up -d commands and the file is recreated. How can I change the Timeout parameter before the upload docker? -
Error running WSGI application django Error on pythonanywhere
I'm bit in hurry but stuck on this problem for a long time. I don't know what should I do. My error throws an error about WSGI. When I saw Error Log, 2019-12-16 08:53:45,120: Error running WSGI application 2019-12-16 08:53:45,121: File "/var/www/lej970526_pythonanywhere_com_wsgi.py", line 3 2019-12-16 08:53:45,122: SyntaxError: invalid character in identifier 2019-12-16 08:54:12,944: Error running WSGI application 2019-12-16 08:54:12,946: File "/var/www/lej970526_pythonanywhere_com_wsgi.py", line 3 2019-12-16 08:54:12,947: SyntaxError: invalid character in identifier 2 2019-12-16 08:54:14,487: Error running WSGI application 2019-12-16 08:54:14,487: File "/var/www/lej970526_pythonanywhere_com_wsgi.py", line 3 2 2019-12-16 10:40:06,493: ^ 2019-12-16 10:40:06,493: This is what I saw. /var/www/lej970526_pythonanywhere_com_wsgi.py also includes import os import sys path = 'home/lej970526/koo' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(get_wsgi_application()) -
How to display date from database in Django form without day
I was looking for a solution but nowhere to find the right answer. Maybe the answer I am looking for does not exist, so I decided to ask a question here just in case. I try to show a date without a day. But the problem is that the date is displayed as one of form fields that I create from the model in the database. I explained this because I am not trying to show only the date separately in the temple but the whole form. I'm showing the form in the template using {{form.as_p}}. My date always shows dd.mm.YYYY, but I want to display a date without a day. The form is used to update existing data in the database. Is there a solution, to define certain parameters in the form class I created in the forms.py file or I must do something else? -
How to make log-in with Django rest api
hello i learning about Django rest api, I am learning through someone else's code, but I don't know how to make Login. my code : model: class User(models.Model): class Meta: db_table = "users" created_at = models.DateTimeField(default = timezone.now) updated_ay = models.DateTimeField(auto_now= True) email = models.CharField(max_length = 128, unique= True) password = models.CharField(max_length = 255) active = models.BooleanField(default=False) token = models.CharField(max_length= 255, null = True) nickname = models.CharField(max_length = 255, null = True) serializer: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField() class Meta: model = User fields = '__all__' def to_internal_value(self, data): ret = super(UserSerializer, self).to_internal_value(data) # cipher = AESSipher() # ret['password'] = cipher.encrypt_str(ret['password']) return ret def to_representation(self, obj): ret = super(UserSerializer, self).to_representation(obj) print(ret) return ret def validate_email(self, value): if User.objects.filter(email=value).exists(): raise serializers.ValidationError("Email already exists") return value def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError("The password must be at least %s characters long. " % 8) return value def create(self, validate_data): user = User.objects.create( email = validate_data['email'], password = validate_data['password'], ) user.active = False user.save() message = render_to_string('user/account_activate_email.html', { 'user': user, 'domain' : 'localhost:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) mail_subject = 'sign up mail.' to_email = 'mymail@gmail.com' email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return validate_data views: class SignUp(APIView): def post(self, request): serializer … -
Django change the order of pre_save post_save signals being called when using inlines?
I have an Order (1) and OrderLine (n) model, here order can have multiple order-lines. I registered for the pre_save and post_save on on both models. Django calls these signals in the following order: Order | pre_save Order | post_save OrderLine 1 | pre_save OrderLine 1 | post_save OrderLine 2 | pre_save OrderLine 2 | post_save OrderLine n | pre_save OrderLine n | post_save The issue I'm having is that I would like to change the order of the signals called, as follows: Order | pre_save OrderLine 1 | pre_save OrderLine 1 | post_save OrderLine 2 | pre_save OrderLine 2 | post_save OrderLine n | pre_save OrderLine n | post_save Order | post_save Since I need to do a few calculations in each OrderLine, and those results needs to be used in the Order post. But the post signal is already been called. The only solution I see is to call my code on each OrderLine post signal, which is a bit redundant, especially when you have many order-lines. What would be the best / better way to tackle this? -
How send Firebase Push notification in django
I have followed the steps. pip install fcm-django Edit your settings.py file INSTALLED_APPS = ("fcm_django") FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "[your api key]" } and then manage.py migrate How do I send push messages on tokens ?? I didn't understand the following method from fcm_django.models import FCMDevice device = FCMDevice.objects.all().first() device.send_message("Title", "Message") device.send_message(data={"test": "test"}) device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) -
Unresolved function or method carousel() in django project
Can Somebody explain to me, why when i implement this set of codes in django it doesnt function properly, beside that, the css file does not respond at all despite that the static file is registered in the settings file. When i try it as a separate file outside the project it works fine, though not inside the django prject, either in pycharm or vscode. Thank You. for further information i may upload everything seperately (HTML/CSS/JS) {% load static %} <html lang=""> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="/Main/static/functionality/imageslider.js"></script> <link rel="stylesheet" href="/Main/static/blog/imageslider.css" /> <title></title> </head> <body> <div class="carousel"> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt="" /> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> </div> <script> $(document).ready(function() { $(".carousel").carousel(); })(django.jQuery); </script> </body> </html> -
Unread list returning NoneType after switching from sqlite3 to PostgreSQL 12 in Django-notifcations
I have changed my project db from sqlite3 to PostgreSQL 12 and now I can't seem to find my notifications on /api/unread_list/?max=20 Can you tell me what exactly am I missing here. The Error is following, File "/usr/local/lib/python3.7/site-packages/notifications/views.py", line 173, in live_unread_notification_list struct['actor'] = str(notification.actor) TypeError: str returned non-string (type NoneType) -
Cards inside the carousel are displayed vertically instead of horizontal display
<!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="container"> <div id="demo" class="carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> <li data-target="#demo" data-slide-to="1" ></li> <li data-target="#demo" data-slide-to="2" ></li> </ul> <!--Slideshow starts here --> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='{% static "shop/test.jpg" %}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" … -
How do I upload an image with Django with an ImageField?
guys. I have a problem where I want to change the thumbnail on my website of a Model (talking about 3D printing here but also Django ones) but Django does not change it. models.py class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) description = models.TextField(max_length=800, blank=True) thumbnail = models.ImageField(upload_to='models/thumbnails', null=True) I tried two different forms.py Version 1 class ImageUploadForm(forms.Form): """Image upload form.""" image = forms.ImageField() Version 2 (ignore the following name, it was just a fast test) class ModelCreateForm(forms.ModelForm): class Meta: model = Model3D fields = ['name', 'thumbnail'] help_texts = { 'thumbnail': ("Gebe hier den Namen des Modelles ein.") } views.py def save_settings(request, pk): model = get_object_or_404(Model3D, pk=pk) if request.method == 'POST': # print("request.method == 'POST'" + str(dir(saveModel))) model.name = request.POST.get('name', model.name) model.description = request.POST.get('description', model.description) form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): model.thumbnail = form.cleaned_data['image'] model.save() return HttpResponse('image upload success') model.save() return redirect('settings_model', pk=model.pk) return redirect('settings_model', pk=model.pk) I do have enctype="multipart/form-data in my template. Please help! -
how do i get choices value of django forms in templates
class RegisterForm(forms.ModelForm): gender = forms.ChoiceField(label='gender', choices=GENDER_CHOICES) GENDER_CHOICES = ( (0,'Male'), (1,'Female'), (2,'Not to disclose'), ) how do i use choices values in templates like following codes in django templates {% for field in form %} {% ifequal field.name 'gender' %} <select id="{{ field.label_for_id }}" name="{{ field.name }}" class='form-control'> {% for choice in field.choices %} <option value="{{ choice.0 }}">{{ choice.1 }]</option> {% endfor %} </select> {% endifequal %} and is there any recommanded sites which arrange variable names for django templates? it is so difficult to find correct name or built in function which are rendered in templates -
Django Choices Tuple
I'm not sure if this has been answered before but here goes I have this code ITEM = [ ('Fruits', ( ('a', 'Apple'), ('g', 'Grape'), ('m', 'Mango') ) ), ('Vegetables', ( ('b', 'Broccoli'), ('p', 'Peanut'), ('t', 'Tomato') ) ), ] With that I'm trying to access the human-readable version of the tuples in my model like this item = models.CharField(max_length=50, choices=ITEM) However when I submitted this field from django admin page, it submits let's say 'a' instead of 'Apple' How can I make sure that I submitted 'Apple' into the database to be displayed in HTML later on? -
Django how to make automatically fill up function
how to in own registration form, make an automatically fill up function to 2 different users, I found like this code and use to User it is work here code class UserCreate(CreateView, metaclass=ExcludeMeta): model = User exclude = ['username', 'is_staff', 'groups', 'permissions', 'last_login', 'is_staff', 'is_superuser', 'is_active', 'user_class', 'date_joined'] user_class = USER #min_class = MODERATOR extra_context = { 'title': 'Регистрация пользователя' } username_prefix = 'uz' success_url = 'user-edit' def form_valid(self, form): form.instance.user_class = self.user_class form.instance.set_password(form.cleaned_data['password']) form.instance.username = '{}{}'.format(self.username_prefix, random.randint(1000000, 9999999)) self.object = form.save() return redirect(self.success_url, self.object.pk) But I try to make a function, where moderatior's username fill up atumatically to, but it not work here code moder_class = MODERATOR extra_context = { 'title': 'Регистрация модератора' } username_prefix = 'mod' success_url = 'moder-edit' def form_valid(self, form): form.instance.min_class = self.min_class form.instance.set_password(form.cleaned_data['password']) form.instance.username = '{}{}'.format(self.username_prefix, random.randint(1000000, 9999999)) self.object = form.save() return redirect(self.success_url, self.object.pk) I am not check this function very well yet, but want to ask it will work or not and where I have to correct it to work? -
Building Django modules (app) without a project
Following the django tutorial on modularizing my django code, I have been able to seprate out some applications. I have made packages for these application, which we successfully use across multiple projects. Our boilerplate project directory looks somewhat like this (very much like in the tutorial): boilerplate/ boilerplate/boilerplate/settings.py boilerplate/boilerplate/.... boilerplate/user_profile/admin.py, models.py, etc. Ideally, we just pip install the user_profile app and include in the projects settings and we are good to go. However, anytime I have to update the application user_profile, I have to run it within a project and do the development. Is there a possible workflow that I can follow so that I can roughly do the development only on the user_profile app/module without having to set up the entire project. I know that the pain point in setting up a project is barely a line or two, but in my case we use custom database settings (using MongoDB) and setting those things quickly means I've to change the settings on my machine (or environment) everytime I've to work on this project. -
Customise Django makemigrations
I am trying to create a management command which will create two migrations, one for adding models, fields etc, and the other for deleting, so that I can apply one of the migrations before deploying the app and the other after deployment has been on all the servers. Is there any simple way of achieving this without human intervention? -
I want to store data from html page to database in django using dynamic form
I have made dynamic form using JavaScript in HTML but now I want to submit that form and store the data into database.I have researched and found about form factory and form set but I didn't get that quite in this website I am using two forms -
How to save a copy of image in other model django?
I'm trying to create a AddToHomeScreen object from Collections object using following code:- namer=get_object_or_404(Collection,CollectionName=collectionview) if AddToHomeScreen.objects.filter(Profile=request.user.profile,name=namer.CollectionName,url="Collection").exists(): obje=AddToHomeScreen.objects.get(Profile=request.user.profile,name=namer.CollectionName,url="Collection") obje.delete() return JsonResponse({'info':'Deleted'}) else: objec= AddToHomeScreen(Profile=request.user.profile,name=namer.CollectionName,url="Collection",profilepic=namer.ProfilePic) objec.save() print(objec.profilepic) return JsonResponse({'info':'Added'}) But there's a problem in this code:- Suppose if a user deletes AddToHomScreen object, ProfilePic attribute of Collection also get deleted as both shares same file. In order to create a copy of image, i modified my AddToHomeScreen model's save method:- from django.core.files.base import ContentFile def save(self): ima=Image.open(self.profilepic) name=self.profilepic.name.split("/")[-1] content=ContentFile(self.profilepic.read()) self.profilepic.save(name,content) super(AddToHomeScreen,self).save() but it produces following error:- maximum recursion depth exceeded while calling a Python object How can i achieve it??