Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Send Email from Django
I am taking a tutorial for Django, but stuck at sending email from Django. I am working on Django's built in django.contrib.auth password reset views, it works fine, but doesn;t actually sends any email. For Testing purpose, I am using below code example to send email, but it gives error which I don't know where to resolve. (env1) C:\Users\crm>python manage.py shell Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.mail import send_mail >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'email1@gmail.com', ... ['email2@gmail.com'], ... fail_silently=False, ... ) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 51, in send_mail connection = connection or get_connection( File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 34, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Program Files (x86)\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line … -
NOT NULL constraint failed: users_usermodel.password
I have created a Custom User Model(I am new to this Curtom thing) And I got this error at login. NOT NULL constraint failed: users_usermodel.password. I don't understand what to do. Here is my models.py and views.py I changes the login to mylogin because I thought the function might contrdict the django login funtion. but nothing changed. Please help me solve my problem Models.py # Custom User Model Code from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email,first_name, last_name, password=None): """ Creates and saves a User with the given email, favorite color and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,first_name, last_name, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class UserModel(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=20, default='') last_name = models.CharField(max_length=20, default='') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] def __str__(self): return … -
data in serializer is always empty
I have following serializer: class AdminSerializer(serializers.Serializer): def validate(self, data): user = data.get("user_pk") total_licenses = data.get("total_licenses") #here i do some validation with the vars But my data is always empty. This is part of my view serializer_class = self.get_serializer_class() serializer = serializer_class( data=self.request.data, ) serializer.is_valid(raise_exception=True) This is my unit test request: response = self.client.patch( url, data={"user_pk": self.user.pk, "total_licenses": 3}, ) Why is my 'data' always empty? -
How to route to switch from HTTP to HTTPS
I have a Django website running behind Nginx. I have this issue where Nginx won't switch routes from http://www.example.org/uploads to https://www.example.org.uploads. So I am getting a 404 error. Here is my Nginx configuration: upstream gunicorn{ server unix:/home/ubuntu/website/project.sock fail_timeout=0; } server { listen 443 ssl http2; server_name *.example.org; ssl_certificate /etc/ssl/private/example.org.crt; ssl_certificate_key /etc/ssl/private/domain.key; # path for static files root /home/ubuntu/website/project/project; location /uploads { alias /home/ubuntu/uploads; } location ^~ /dashboard { alias /var/www/name/dashboard_app/build; try_files $uri $uri/ /dashboard/index.html; } location ^~ /shop { alias /var/www/name/user_app/build; try_files $uri $uri/ /user_app/index.html; } location ^~ / { proxy_pass http://gunicorn; proxy_set_header Host $host; } location /static { } } server { if ($host = example.org) { return 301 https://www.$host$request_uri; } if ($host = www.example.org) { return 301 https://$host$request_uri; } listen 80; server_name domain.org; return 404; } 'dashboard' and 'shop' lead to React applications. '/' leads to my Django application. 'http(s)://example.org/uploads' and 'https://www.example.org/uploads' work fine . 'http://www.example.org/uploads' is the only combination I can find that does NOT work. How can I get calls to 'http://www.example.org/uploads' to route correctly? -
Categories and Subcategories Django
Im doing a ecommerce website with django and I have a problem with categories and subcategories. This are my models: Model Category Model Product And this is my view: View Okay so what I want to do is if I click the parent category I want to show all the products that their children have and If I click a Children I want to show only the products that he has. So i don't know how to do that:( -
Two related models but error: using variable before assignment
I have 2 models that are closely related but I keep getting the error: Using variable 'Bid' before assignment The problem is if I move Bid before Listing, I will still get the same error of course because I will have mentioned Listing before assignment. I did just add the highest_bid field to my Listing model so maybe there is a better way of structuring my models. Essentially, I want all the bid_inputs for a listing to be stored in Listing.highest_bid but I want the highest_bid to only every display the max value. I am wondering if this is maybe something I could work out in my views.py rather than having a separate field for it? models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) highest_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, max_digits=9, decimal_places=2, default=None, null=True) status = models.CharField(max_length=10, choices=options, default="active") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"{self.title} ({self.pk}, £{self.start_price}, {self.lister})" class Bid(models.Model): bidder_user = models.ForeignKey(User, … -
How to get the difference of 2 different django models fields?
I have here 2 django database table class ProductName(models.Model): name = models.CharField(max_length=100) class Inventory(models.Model): product = models.ForeignKey(ProductName, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() class Sold(models.Model): product = models.ForeignKey(ProductName, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() I would like to have an inventory table page wherein I can see the total qty left in Inventory (for example: Inventory.qty - Sold.qty) . how to do this in Django ? -
Django - Initial form field values not showing
I am trying to set the initial value of a form field. I have approached it the following ways: forms.py: class FilterGigsForm(forms.Form): field = forms.IntegerField(label="", required=False, initial=5) def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) kwargs.update(initial={ 'field': 5, }) super().__init__(*args, **kwargs) self.fields['field'].initial = 5 views.py class HomePage(FormMixin, TemplateView): template_name = 'index.html' model = MyModel form_class = MyForm def get(self, request, *args, **kwargs): form = MyForm(self.request.GET, initial={'field': 5,}) ... return render(request, 'index.html', {"form": form, }) However, none of these approaches are working and the initial value is not showing when I load/reload the page. -
request from client side comes in array, how to handle it with Django rest framework filter
As I mentioned in heading, client side filter request comes in this pattern from tabulator data table to rest framework back end. /?page=1&size=10&filters[0][field]=q&filters[0][type]=like&filters[0][value]=something i have tried this way but it is not working class MemberListApiView(TemplateView): template_name = 'api/member_list_api.html' def get_context_data(self, **kwargs): context = super(MemberListApiView, self).get_context_data(**kwargs) return context class MemberListSerializerView(generics.ListAPIView): model = Membership serializer_class = MemberSerializer pagination_class = CustomPagination def get_queryset(self): queryset = Membership.objects.members() query = self.request.query_params.get('filters[value][0]', None) if query is not None: queryset = queryset.filter( Q(user__username__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ) return queryset -
Troubles with making migrations on django x docker x postgres project
Im having troubles running migrations in my django docker project. Here is my current project structure: Main Project Directory ├── Backend │ ├── main_app_folder (settings.py is here) │ └── sub_app_1_folder │ └── sub_app_2_folder ├── _Frontend │ ├── Frontend folder │ └── standard create_react_app folder structure │ └── Dockerfile(to build frontend image) ├── nginx │ ├── Dockerfile │ ├── nginx-proxy.conf │ └── uwsgi params ├── scripts │ └── entrypoint.sh ├── .dockerignore ├── .env ├── Dockerfile ├── docker-compose.yml ├── requirements.txt └── .gitignore Here is the main Dockerfile thats in the root directory responsible for booting up the backend folder: # Pull base image FROM python:3.8-alpine # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH="/scripts:${PATH}" RUN apk update #Copy our backend folder and place it inside the image RUN mkdir /dockerbackend COPY ./requirements.txt /dockerbackend COPY ./backend /dockerbackend COPY ./scripts /dockerbackend WORKDIR /dockerbackend #Installing dependencies, remove those that are not needed after the installation RUN \ apk add libpq &&\ apk add --no-cache --virtual .build-deps gcc postgresql-dev libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev gcc musl-dev && \ apk add jpeg-dev zlib-dev libjpeg &&\ pip install -r requirements.txt &&\ apk del .build-deps #Create media and static directories RUN mkdir -p … -
Django Form Is Valid not producing any errors but returning False
I'm trying to update an existing model row (add choices to an existing ManyToMany field with previous entries) with a form but when I use the is_valid() it returns false, I have checked for errors in a few ways but no errors are being displayed I have used in my template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="errorlogin"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="errorlogin"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} and, in my views, after the is_valid and before the is_valid function is called: print(form.errors) My code is below: views.py def lessonRecord(request,id): if request.method == "POST": id = Lessons.objects.get(id=id) form = forms.LessonAddForm(request.POST,instance=id) if form.is_valid(): form.save() return redirect('lessons:lessonsView') else: print(form.errors) else: id = Lessons.objects.get(id=id) form = forms.LessonAddForm(instance=id , user=request.user) return render(request,'lessons/lesson_record.html',{'id':id,'form':form}) forms.py class LessonAddForm(forms.ModelForm): def __init__(self, user,*args, **kwargs): super(LessonAddForm, self).__init__(*args, **kwargs) self.fields['attendees'].queryset = CustomUser.objects.filter( Q(username=user) | Q(customuser__username=user) ) class Meta: model = models.Lessons fields = ['attendees'] -
Html submit button don't work after add jquery
Html submit button did work finely before add jquery script. But when i add jquery script in User Academic Information html submit button doesn't work. This template did work in django. i added jquery in id="form_set" And when i also add style="display:none" in id="empty_form" submit button don't work Here is html code: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="/" method="post"> {% csrf_token %} <div class="card-header"> <strong class="icon-user"> User Basic Information</strong> <hr class="divider" /> </div> <div class="card-body"> <div class="form-horizontal"> {% for field in employ_basic_forms %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> {% endfor %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>Select Employ Designation:</h6></label> {% for field in user_role %} <div class="col-md-9">{{ field }}</div> {% endfor %} </div> </div> </div> <div class="card-header"> <strong class="icon-book"> User Academic Information</strong> <hr class="divider" /> </div> <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form }} <div id="form_set"> {% for form in employAcademicFormSet %} {% for field in form.visible_fields %} <table class="no_error"> <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> </table> {% endfor %} {% endfor %} </div> <input type="button" value="Add More" id="add_more" /> … -
Django, link a model field with an admin model field with ForeignKey
I'm trying to link a "normal" model field with an admin model field, for example I have a table "Post" and I want to add the admin username as a ForeignKey to the field "Author" of the table Post. I mean : class Post(models.Model): title = models.CharField(max_length=50) body = RichTextField(blank=True, null=True) date = models.DateTimeField('date_posted') username = models.ForeignKey(admin.username, on_delete=models.CASCADE) Where admin.username refers the username of auth_user admin model Thanks for your help -
How to pass multiple kwargs parameter to Django Class Based View (ListView) at HTML page?
Views.py class CalendarWeekView(LoginRequiredMixin, generic.ListView): login_url = 'signup' model = Event template_name = 'calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) w = int(self.request.GET.get('week', None)) cal = Calendar(d.year, d.month, w) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) context['current_month'] = current_month(d) context['next_week'] = next_week(w) return context urls.py app_name = 'calendarapp' urlpatterns = [ path('week/', views.CalendarWeekView.as_view(), name='calendarWeek'), ] calendar.html href="{% url 'calendarapp:calendarWeek' %}?{{ next_week}}/?{{ current_month }}" How to pass multiple kwargs parameter to Django Class Based View (ListView) at HTML page using URL Path at HTML page ? -
My function is missing 1 required positional argument: 'request'
I am currently working on my first website, and I'm experiencing some trouble in views.py. Specifically this def: def translated_view(self, request): text = request.POST.get('text') translate = self.translator context = { 'translated': translate(text) } return render(request, context, 'main/translated.html') As you can see I have the request argument. However I'm still seeing this error. -
Nginx somtimes said "Forbidden – You don’t have permission to access / on this server"
I have deployed my Django application with the Nginx web server on Linode and my site is running correctly but sometimes, I don' know why, when I try to access my site I have the error: Forbidden You don't have permission to access / on this server my domain name is: dontrepeatyourself.org try to access it and see the error. Note that this error does not appear all the time, sometimes I can access my site normally. Here is my configuration for Nginx: /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 1024; } http { sendfile on; tcp_nopush on; tcp_nodelay on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; add_header X-Content-Type-Options nosniff; add_header X-Frame-Options SAMEORIGIN; add_header X-XSS-Protection "1; mode=block"; server_tokens off; keepalive_timeout 75; } /etc/nginx/conf.d/dontrepeatyourself.conf server { if ($host = www.dontrepeatyourself.org) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = dontrepeatyourself.org) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name dontrepeatyourself.org www.dontrepeatyourself.org; return 301 https://dontrepeatyourself.org$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; # ssl stuff server_name dontrepeatyourself.org www.dontrepeatyourself.org; … -
How to get a YAML file containing api keys to work in django?
I'm new to django and I am trying to make an API call to ebay when a user clicks a button, using ebay python SDK. There is a YAML file inside my project which contains the api keys. In my app, I have a python file that contains a function that makes the api call. When I run the function that python file separately, it works fine and finds the YAML file no problem. But when I try to run that same function from views.py, it gives me an error that says - config file 'ebay.yaml' not found. Can anyone please help me with this as I have no idea what's wrong... Do I have to do anything special when running the API call through django, besides just having a YAML file in the same direcotry? -
Using Apache Ignite with Django
We have an existing Apache Ignite in-memory DB with lots of stored data. I want to connect my existing Django web application to the Ignite DB in order to query the existing data. Are there any examples of how to connect a Django application to an Apache Ignite DB and how to query the DB using the Django ORM? -
How to set default value for a ManyToManyField in Django
models.py: from django.db import models class Department(models.Model): departmentName = models.CharField(max_length=100) def __str__(self): return self.departmentName class Designation(models.Model): designationName = models.CharField(max_length=100) def __str__(self): return self.designationName class Employee(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True, blank=False) department = models.ManyToManyField(Department, blank=True) designation = models.ForeignKey(Designation, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name My query/requirement: Employee and Department are linked by M2M. I set blank=True to overcome the form validation of no department being chosen. (null=True doesn't seem to be working with M2M) Let's say, scenario 1: while creating a new Emp, if there is no department provided then it should set to RP(Resource pool) by default. scenario 2: An existing Emp is from the HR department; assuming for some reason the HR dept is being deleted or Emp is being kicked out, now that Emp has no department linked to it, it should move to RP(Resource pool) by default!! How to arrange the default department- RP in Django such that both the scenarios are passing!? Thanks in advance :) Dueces -
Django - Updating a value of a field every 24 hour automatically
I have the following model in my django project: class Player(models.Model): creation_time = models.DateTimeField(auto_now_add=True) player_name = models.CharField(max_length=100, blank=False) ... player_lifetime = models.IntegerField(default=100) class Meta: ordering = ['creation_time'] So, the Player instance gets the lifetime value 100 during its creation. Now, I want to update the value of this field every 24 hour by subtracting it with -10. After 1 day, this value should be 90, after the second day it should be 80 and so on. How, can I let Django update this value for me automatically/periodically ? -
Field 'id' expected a number but got 'xyz'
In Models.py class Post(models.Model): user = models.CharField(max_length=100) likes = models.IntegerField(default=0) content = models.TextField() date = models.DateTimeField(auto_now_add=True) class Profile(models.Model): following = models.ForeignKey('User',on_delete=models.CASCADE,related_name='following') user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.user In views.py def viewProfile(request,username): posts = Post.objects.filter(user=username).order_by('id').reverse() profile = Profile.objects.filter(user=username) no_of_followers = profile.following.count() return render(request, "network/profile.html",{ "posts":posts, "username":username, "no_of_followers":no_of_followers }) In profile.html {% extends "network/layout.html" %} {% block body %} <h2 style="margin-left: 20px;">Posts of {{username}}</h2> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Profile Details</h5> <p class="card-text">Followers:{{no_of_followers}}</p> <p class="card-text">Followings:0</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% for post in posts %} <div class="card" style="width:70%;margin-left: 10%;margin-right: 20%;"> <div class="card-body"> <a href="{% url 'viewprofile' post.user %}"><h5 class="card-title">{{post.user}}</h5></a> <div class="form-group"> <p>{{post.date}}<br>{{post.content}}</p> </div> <p>{{post.likes}}</p> </div> </div> {% endfor %} {% endblock %} Facing an error of Field 'id' expected a number but got 'xyz'. xyz is the username If I replace profile = Profile.objects.filter(user=username)with profile = Profile.objects.filter(user__user=username) then I am getting the error django.core.exceptions.FieldError: Related Field got invalid lookup: user -
summation two similar objects based on the name django
i try to make a system for a storage , sometimes it happen two similar objects are entry in two different time , i have summation the quantity of both and looks like one object instead of two different object for example i've entry this data one week ago name=mouse , qnt=20 , price=20 and today i add a new collection of mouse (the same mouse as before) name=mouse , qnt=10 , price=15 i have to whenever i face similar problem it automatically summation quantities =(30) and price = ((20+15)/2) instead of creating a new object to the second mouse object this is my model class Products(models.Model): name = models.CharField(max_length=20,unique=True) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) def __str__(self): return self.name class Collections(models.Model): name = models.ForeignKey(Products, on_delete=models.CASCADE) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) i dont need to create new object to the same product as exist in collection , i have to just summation the quantities ?! is it possible ?thanks -
insert django tag in react gatbsy helmet
I have to put a django tag inside the head, so the template will render the dynamic metatags server side. what I want to do is: {% block metatags %} <meta name="description" content="{{ metatags.description }}" /> <meta name="keywords" content="{{ metatags.keywords }}" /> <meta property="og:url" content="{{ metatags.og_url }}" /> <meta property="og:title" content="{{ metatags.og_title }}" /> <meta property="og:description" content="{{ metatags.og_description }}" /> <meta property="og:image" content="{{ metatags.og_image }}" /> <meta property="og:image:url" content="{{ metatags.og_image_url }}" /> <meta property="og:image:type" content="{{ metatags.og_image_type }}" /> {% endblock %} Now, no problems for the meta tags inside helmet, since it's a accepted element for helmet. The problem is for the {% block metatags %} and {% endblock %}. The compiled page won't have those two, probably because helmet ignores them. I tried also to put manually {% block metatags %} and {% endblock %} in the compilated page and it works. I think I cannot achieve this with just helmet, since it will ignore every tag I put inside which are not recognised (script,meta,noscript,..). How could I do that? The only solution maybe it's call a script after gatsby build and add those manually.. any better solutions? -
Getting the difference of quantity between 2 different django model fields?
I have here 2 django database table class Inventory(models.Model): product_name = models.CharField(max_length = 100) qty = models.PositiveIntegerField() class Order(models.Model): product = models.ForeignKey(Inventory, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() I would like to have an inventory table page wherein I can see the total qty left in Inventory (for example: Inventory.qty - Order.qty) . how to do this in Django ? -
set default image to ImageField for existing objects in django
I have a model which has an ImageField. class A(model.Model): blah = CharField(max_length=10) profile = ImageField(upload_to='uploads/', null=True, blank=True) I want to set a default image for existing data, so I tried saving the file in shell like the following: >>> myapp.models import A >>> from django.core.files import File >>> for a in A.objects.all(): >>> a.profile.save('default.jpg', File(open('/Users/myusername/Pictures/default.jpg', 'rb'))) I was quite happy, until I found out that in myprojectroot/media/uploads/ there are as many defaultblablah.jpg files as the number of A objects. I'd like to know if there's any way to set the same image file with all objects as you do with update() method. Could someone can shed some light on it? Thank you in advance.