Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django Rest Framework to initiate data processing on the backend
I have a fully functioning Django application and I am now adding an API using Django Rest Framework. I will creating a React front end which will use the API provided via DRF. I have worked out how to use DRF to create endpoints for my models using ModelViewSets and ModelSerializers. These work fine. I now need to create an endpoint that initiates some data processing. The endpoint will need to accept a date as input and then call some code to do the processing. My standard Django application currently does this by accepting a date via a Django form and then initiating a celery task. Here is the view: class GenerateRosterView(LoginRequiredMixin, FormView): """Generate Roster View.""" template_name = "generate_roster.html" form_class = GenerateRosterForm def get_form_kwargs(self): """Pass request to form.""" kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs def get_success_url(self): """Get success URL.""" return reverse("roster_generation_status", args=(self.task_id,)) def form_valid(self, form): """Process generate roster form.""" start_date = form.cleaned_data["start_date"] self.request.session["start_date"] = start_date.date().strftime( "%d-%b-%Y" ) result = generate_roster.delay(start_date=start_date) self.task_id = result.task_id return super().form_valid(form) Here is the form: class GenerateRosterForm(forms.Form): """Generate Roster Form.""" def __init__(self, request, *args, **kwargs): """Get default start date from session.""" super().__init__(*args, **kwargs) if "start_date" in request.session: start_date = datetime.datetime.strptime( request.session["start_date"], "%d-%b-%Y" ) else: start_date = … -
Django - How can I set a Model's field using the existance of a ForeignKey as a condition?
I am trying to create a Django app where there are two main models - Team and Person. A Person can use the app as an User or can belong to a Team, and, in that case, the User will be the Team. class Team(models.Model): name = models.CharField(max_length=50) team_user = models.ForeignKey( User, on_delete = models.CASCADE, null = True, blank = True ) class Person(models.Model): person_user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True) team = models.ForeignKey( Team, on_delete = models.CASCADE, null = True, blank = True ) I am trying to develop a File structure like this: /root /Team_01 /Person_01 (non-User) /files.csv /Person_02 (non-User) /files.csv /Person_03 (User) /files.csv I have read the documentation and I was trying to do something with the comment from Evgeni Shudzel in this post, but my problem is that I don't know how to set the file's path for the Person model so that if the Person is member of a Team, the path is "/team_id/person_id" and if not, the "/team_id" part is excluded. The pseudocode I have in mind: if Person.team exists: files = models.FileField(upload_to="TEAM_ID/PERSON_ID/") else: files = models.FileField(upload_to="PERSON_ID/") How can I implement this pseudocode? Thank you! -
django alternative to prevent header poison
Firstly I don't speak English very well, but anyway... i know I need to use allowed_hosts, but I need to use all "*" and a header attack can cause something like: <script src = "mysite.com/js/script.js"> <script> to <script src = "attacker.com/js/script.js"> <script> or mysite.com/new_password=blabla&token=blabla8b10918gd91d1b0i1 to attacker.com/new_password=blabla&token=blabla8b10918gd91d1b0i1 But all static files are load on a nodejs server "cdn.mysite.com" and all domains are in the database, so I always take the domain from the database to compare with the request header, and use the domain from the database of data to send anything to the client: views.py: def Index(request): url = request.META['HTTP_HOST'] cf = Config.objects.first() if cf.domain == url: form = regForm() return render(request, 'page/site/home.html', {'form': form}) elif cf.user_domain == url: ur = request.user.is_authenticated if ur: config = {'data' : request.user} lojas = 'json.loads(request.user.user_themes)' return render(request, 'app/home.html', {"config":config, "lojas":lojas}) else: forml = loginForm() return render(request, 'page/users/login/login.html', {'form':forml}) else: redirect("//" + cf.domain) Would that still be unsafe to use this way? -
Show product instance in Django UpdateView with Select Boxes
I need to show the product instance in the select boxes. I am very sure I followed the get_object and get_initial method pretty well but the form does not seem to initiate with the product I want to update. Any other way to do this? Model: class Order(models.Model): options = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=options, null=True, max_length=200) def __str__(self): return self.status class Meta: ordering = ['-date_created'] My View: class OrderUpdateView(UpdateView): model = Order form_class = OrderUpdateForm template_name = 'crmapp/update-order.html' context_object_name = 'order' success_url = '/' def get_initial(self): initial = super(OrderUpdateView, self).get_initial() content = self.get_object() initial['customer'] = content.customer initial['product'] = content.product initial['status'] = content.status return initial def get_object(self, *args, **kwargs): product = get_object_or_404(Order, pk=self.kwargs['pk']) return product The Url: path('update-order/<str:pk>/', OrderUpdateView.as_view(), name='update-order') The HTML <div class="container"> <div class="row"> <div class="col-sm-6 offset-3"> <br><br><br><br> <form action="{% url 'update-order' order.pk %}" method="POST"> {% csrf_token %} {{ form.as_p}} <button class="btn btn-primary btn-block" type="submit">Save</button> </form> <br><br><br><br> </div> </div> -
How to get a users lat and long via button press in Django?
I'm in the process of trying to create an app that can grab a users lat and long when a button is press/clicked. I plan on storing the lat and long inside of a model field for each individual press/click. Only to be used later on inside of an interactive map, displaying every lat and long that has been stored. Looking into Leaflet or Google Maps API to implement a map. I've read the Django documentation on GeoIP2 and I think it may be my best option but I'm not sure if there are any better options? As far as implementing GeoIP2 goes, it's really as simple as what I have below, correct? from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() lat,lng = g.lat_lon(user_ip) model_field_example_lat = lat model_field_example_lng = lng -
Django migrate rollback multiple migrations on failure
Django migrations has excellent behavior in terms of single migrations, where, assuming you leave atomic=True, a migration will be all-or-nothing: it will either run to completion or undo everything. Is there a way to get this all-or-nothing behavior for multiple migrations? That is to say, is there a way to either run multiple migrations inside an enclosing transaction (which admittedly could cause other problems) or to rollback all succeeded migrations on failure? For context, I'm looking for a single command or setting to do this so that I can include it in a deploy script. Currently, the only part of my deploy that isn't rolled back in the event of a failure are database changes. I know that this can be manually done by running python manage.py migrate APP_NAME MIGRATION_NUMBER in the event of a failure, but this requires knowledge of the last run migration on each app. -
I want to get an ID from the URL and query my data. Django Rest Framework
I am making a Marvel based API and I want to get the ID from the url and query the fields from that ID. my models.py: class Characther(models.Model): name = models.CharField(max_length=100) comics = models.TextField() events = models.TextField() series = models.TextField() stories = models.TextField() my views.py class CharList(generics.ListCreateAPIView): queryset = Characther.objects.all() serializer_class = CharSerializer def get(self, request, id): id = request.GET.get('id', '') return render(request, self, {'comics': get_object_or_404(comics, pk = id)}) class ComicList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'comics') serializer_class = ComicSerializer class EventsList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'events') serializer_class = EventsSerializer class SeriesList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'series') serializer_class = SeriesSerializer class StoryList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'stories') serializer_class = StorySerializer my url : urlpatterns = [ url(r'^v1/public/characters/(?P<id>[\w-]+)/', views.ComicList.as_view(), name = 'comics') ] -
how to make green color body using using is_grater_priority
`class Todolist(models.Model): title = models.CharField(max_length=255) detail = models.TextField(max_length=255, null=True, blank=True) created = models.CharField(max_length=255) is_grater_priority=models.BooleanField(default=False)` i have done this, but not working Now what should i do to make this workable ` {% if list %} {% for obj in list %} {% if obj == is_grater_priority %} <p class="text-success"><strong>Title:- </strong> {{obj.title}} </p> <p class="text-success"><strong>Details:- </strong> {{obj.detail}} </p> <p class="text-success"><strong>Sheduled:- </strong> {{obj.created}} </p> <a href="{% url 'todolist:edit_todolist' obj.id %}">Edit</a> <a href="{% url 'todolist:delete_todolist' obj.id %}">Delete</a> <hr> {% else %} <p><strong>Title:- </strong> {{obj.title}} </p> <p><strong>Details:- </strong> {{obj.detail}} </p> <p><strong>Sheduled:- </strong> {{obj.created}} </p> <a href="{% url 'todolist:edit_todolist' obj.id %}">Edit</a> <a href="{% url 'todolist:delete_todolist' obj.id %}">Delete</a> <hr> {% endif %} {% endfor %} {% else %} <h2>No list avilable</h2> {% endif %}` -
How to Append in Loop using Selenium
def show(request): driver = webdriver.Chrome('/Users/colegulledge/desktop/chromedriver') driver.get('https://www.horrycounty.org/bookings') sleep(random() + 2) date_form = driver.find_element_by_id('txtBookingDate') ##we are going to loop through the start date-end date in this input box def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) start_date = date(2020, 1, 1) end_date = date(2020, 1, 3) def change_date_format(dt): return re.sub(r'(\d{4})/(\d{1,2})/(\d{1,2})', '\\2-\\3-\\1', dt) ##to change the format to month-day-year for single_date in daterange(start_date, end_date): days = (single_date.strftime(format("%Y/%m/%d"))) days = (change_date_format(days)) date_form.send_keys(days) sleep(2) ##Changing the date format and using send keys we put in in the inputbox for el in days: search = driver.find_element_by_css_selector("span.btn-primary") driver.execute_script("arguments[0].click();", search) sleep(2) inmate_info = driver.find_elements_by_class_name("cellLarge") rs = [] for p in range(len(inmate_info)): rs.append(inmate_info[p].text.strip()) date_form.clear() print(rs) ##the website keeps the previous date in the input box, so we must ##clear the input box and repeat the loop return HttpResponse(rs) So whenever I do this, rs is only returning the last day of records.. I believe my function is not appending to the list, instead it is replacing it. This may be obvious, but I am an inexperienced and working on my first major project. Any ideas/suggestions? Thanks -
Ajax data manipulation when transmitting to Django CBV
I'm using django-autocomplete-light with the select2 "select multiple" widget for a M2M form. I have it set up to enable "Create New" when the input is not found. However, my model has additional required fields beyond the initial input of the "select multiple" widget. I am trying to create a way to prompt the user for the additional fields when trying to create, and then sending that data through ajax to my django view. Right now, if I pre-supply the other required fields within my view, the user can create a new object with the name that they've entered (and clicked "Create New") for, and the other fields will be determined in my view. This shows me that the code is working, but ideally I'd like to prompt the user for the additional data. I have created a prompt, however I cannot the correct syntax for transmitting the data. As an example, pretend I have a model with required fields "Name" and "Location". On the Select2 widget, the user types a "Name" which doesn't exist as an object, and clicks "Create New". Now, I'd like the script to prompt them for the location, then transmit that in as a get_or_create … -
Django Stripe Payment Responds with Invalid Parameter after clicking Submit Payment button
I am working on an e-commerce project that requires stripe payment gateway. It is my first time to work on an application that requires stripe payment. I am a junior programmer. I am working on my localhost machine, I have tried to debug the code but i have failed to see where the problem is. @Hacker86 got the solution but has not shared it can anyone help me with the problem. This is the link of the same problem Stack I tried to solve the problem with the solution in the replies to above the question but all was in veil. So please can anyone help immediately reply me. Below is my relevant Code base.py import os from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = config('SECRET_KEY') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'drf_yasg', 'crispy_forms', 'django_countries', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'perfectfits.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = … -
django-tables2: Change column header link
I have created a table using django-tables2, and it displays correctly with verbose names displaying in the column headers. Each of the column headers is a link to sort the column, but as far as I can tell there is no way to change the link href: <th class="orderable"> <a href="?sort=column_name">Verbose Name</a> </th> I have found ways to edit the attributes of the <th> tag, but I can't find a way to edit the href parameter on the <a> tag wrapping the column header text. I have multiple tables I'd like to display, and I'd like to use different paths for updating each different table. Is there a way to update the Table or Column class to customize the URL used when clicking on the column header text? -
Redirect non ajax requests to DRF endpoint
I want to prohibit direct access to the endpoints. If I was using Django's CBV I'd simply add if not request.is_ajax(): return redirect... to the view. Now how would I achieve the same with DRF, specifically with viewsets and generic mixins? Should I overwrite get methods? If so, are there more elegant ways? -
After creating login and registration page HTML and CSS how to take user input and save to data base?
I'm currently making a website and have created both the HTML and CSS for both the registration and login Pages - I'm wanting to use Django to save the information, I'm just a bit confused on how to take the user input (using my html inputs) and then transferring them to the Django data base. I'm very new to web development as you can tell - I'm just trying to take it one step at a time. /* This is the style sheet for the Registration Page only */ body { background-color: rgba(255,0,0,0.65); } h2 { color: white; font-family: optima; font-size: 300%; font-weight: 500; font-variant: small-caps; line-height: 200px; height: 200px; z-index: 0; margin-top: -50px; } h3 { color: white; font-family: Helvetica; font-size: 250%; font-weight: 400; font-variant: small-caps; margin-top: 50px; } #rectangle{ top: 20px; display: inline-block; width:450px; height:550px; background:rgba(43, 43, 43, 1); transform: translate(-50%,-50%); border-radius: 15px; position: absolute; z-index:-5; top: 550px; } img { opacity: 0.8; display: block; margin-left: auto; margin-right: auto; background-repeat: no-repeat; } div { text-align: center; padding: 0; } label{ color:white; font-family:Helvetica ; display: block; text-align: center; padding-bottom: 10px; } select{ font-family:Helvetica ; background-color: lightgrey; text-align: center; margin: 0 auto; display: block; padding: 50; } span { color:white; … -
certbot and apache domain name trouble
I have deployed a django web application on a linux server using ubuntu 20.10 and apache2. My site was working well before I added certbot. However, after I ran the certbot commands for apache2 and ubuntu 20.04 (because 20.10 was not listed) my site only works for for first time users who put www.my_domain_name.com. When they just put my_domain_name.com in it serves them the default apache ubuntu page which is clearly not what I want. My idea was to use rewrite conditions and rules to send them to the www. version if they try to access it without that but everytime I do that an error occurs. The only rewrite rule I have is below and Server_Name is set to www.my_domain_name.com at the top of the .conf file. Can you help me write a rewrite rule to always send them to the https version and to the www. version or give me advice on how to get the non www. version to serve up the proper page with https? Also it is worth noting that when I try to open the non www. version in my browser it works fine, but when a first time user trys it it does … -
Can't load link postgreSQL to Django
I've created a new Django project in my virtual environment and installed psycopg2. I changed my settings.py file to the following: DB_NAME = "neighborhood" DB_USER = "django" DB_PASSWORD = "password" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } But when I run python manage.py migrate in my virtual enviorment, I get the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. I'm using python v3.9 and postgreSQL v13. I checked other posts on Stack Overflow but none answered my problem. Thanks. -
django-filter according to the logged user
I am using the django_filters to filtering the information. However, it is showing the data of all regitered user of my system. I need show only the data of logged user. Follow the files: filters.py import django_filters from apps.requisitos.models import Requisito class RequisitoFilter(django_filters.FilterSet): class Meta: model = Requisito fields = ['nomeRequisito', 'projeto'] views.py class RequisitoList(ListView): paginate_by = 10 model = Requisito def get_queryset(self): usuarioLogado = self.request.user return Requisito.objects.filter(user=usuarioLogado) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = RequisitoFilter(self.request.GET, queryset=self.queryset) return context the loop for of html page {% for requisito in filter.qs %} thank you very much -
Saving database changes with django channels
I wish to make simple programme in django channels - I open Websocket and then listen for users clicking a button or pressing any key down. If such event occurs JS sends message to Channels where it gets access to db where there is a model of a counter, increment it depends it was click or key, and then send it back to group on layers. Unfortunately, error occurs. Why it calls contex error if I already used database_sync_to_async My consumers.py : from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async from .models import Licznik class MyConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'main_room' self.counter = await database_sync_to_async(self.get_counter)() await (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) await self.accept() def get_counter(self): return Licznik.objects.all()[0] async def receive(self, text_data): if text_data == "klik": self.counter.klik +=1 elif text_data == "klak": self.counter.key += 1 await database_sync_to_async(self.counter.save()) #error here klik = self.counter.klik klak = self.counter.key await (self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'klik': klik, 'klak': klak } ) async def chat_message(self, event): message_klik = event['klik'] message_klak = event['klak'] await self.send(text_data=json.dumps({ 'klik': message_klik, 'klak': message_klak })) async def disconnect(self, close_code): await (self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) await self.close() Error: Exception inside application: You cannot call this from an async context - use … -
python manage.py dumpdata Access is denied
I got the error message - (ECOMME~1) C:\Users\HP\Django Projects\EcommerceProject>python manage.py dumpdata products --format json --indent 4 > products/fixtures Access is denied. I assumed it was because I had changed my databases because the default databases are not sufficient if you want mapping functionality. I read the post Django loaddata returns a permission denied for relation and asked GRANT ALL PRIVILEGES ON DATABASE Blog&Cart for user postgres. -
My very simple Django Form not passing value to another View
I'm new to Django with a background in Database design. I spent most of my IT career developing prototypes in MS Access so this Web stuff is new to me. Now I'm trying to develop prototype reports in Django for a reporting wing of a SAAS offering. I've got a rough report developed, and if I hard-code the values to pass into some raw queries, it renders a report. Now I'm trying to make a simple form to enter a value into and pass it into the view that renders the report. (Pardon me if I'm using the correct lingo.) Here's the form for the data entry: product_batch.py from django import forms class PrdBtchSelect(forms.Form): prd_btch_nbr = forms.CharField(max_length=20) Here is the data entry HTML: prd_btch_select.html {% extends "base.html" %} {% block title %}Product Batch Select{% endblock %} {% block content %} <form action={% url 'prd_btch_dtl' form.prd_btch_nbr %} method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} Here are the views for the data entry form and for rendering the report: view\product_batch.py from django.shortcuts import render from reports.views import sql from reports.models import Accounts from reports.forms import PrdBtchSelect # import datetime def prd_btch_dtl(request, prd_btch_nbr): """View function for … -
Where do I keep ORM in a distributed app?
I am designing a scalable web app. I have APIs (Django Rest Framework) in one container instance, Web App (Django) in another, Database (Postgreql) in another and finally CDN in another (Azurite). I wanted to decouple API since mobile apps will use the same - eventually. Question: Where do I keep ORM in this scenario? If I keep it part of Web apps, then how do the APIs recognize and use the objects? Or, if I keep them part of the API services, how do the front end (web apps) understand the objects? -
Reloading the data automatically in django
im new to this Here in this program when i clicking the refresh button the entire page is being reloaded and then only the data is being updated so i was thinking you could automatically update the data after some time or when clicking the refresh button get the data without loading the page entirely again The link is here for the github issue https://github.com/ALDRIN121/Covid-19_live_tarcker/issues/1 And thanks in advance -
2 pages in URL in python
my question is why i cannot get property.html when the server is run let me explain you how th project go one : the 1st page which is content list of cities one of them choosen then th next page i get it's property_name the 3rd page should give me all it's properties (name,area) i hope u understand me models.py: from django.db import models class location(models.Model): location_name = models.CharField(max_length=500) location_type = models.CharField(max_length=500) def __str__(self): return self.location_name class property(models.Model): location = models.ForeignKey(location, on_delete=models.CASCADE) property_name = models.CharField(max_length=500) property_area = models.CharField(max_length=500) def __str__(self): return self.property_name views.py: from django.shortcuts import render from django.views import generic from .models import location,property class indexview(generic.ListView): template_name = "homsapp/index.html" def get_queryset(self): return location.objects.all() class locationview(generic.DetailView): model = location template_name = "homsapp/location.html" class propertyview(generic.DetailView): model = property template_name = "homsapp/property.html" urls.py: from django.contrib import admin from django.urls import path,include, re_path from homsapp import views app_name = 'homsapp' urlpatterns = [ #path('admin/', admin.site.urls), path(r'', views.indexview.as_view(), name=('index')), re_path(r'(?P<pk>[0-9]+)/$',views.locationview.as_view(),name=('property')), re_path(r'([0-9]+)/(?P<pk>[0-9]+)/$',views.propertyview.as_view(),name=('propertyview')), ] index.html: {% for locat in object_list %} <a href="/homsapp/{{locat.id}}">{{locat.location_name}}</a><br> {% endfor %} location.html: {% for i in location.property_set.all %} <a href="/homsapp/{{locat.id}}/{{i.id}}">{{i.property_name}}</a> {% endfor %} property.html: {{property.property_name}}<br> {{ property.property_area}} -
Using django without models
Is it possible to use Django but without models? Instead of models I want to use raw sql queries with help of mysql cursor. I want to implement Car Rental site to rent a car. There will be three tables: Cars, Users, Orders. Anyone can sign up on the webpage, sign in and make orders. The only limitation is that a have to do this using raw sql queries so I think that I have to avoid using models. Is this even possible? I'm new to Django and this might be dump question but need to know cause this is my academic project. -
Failing django migrate from ProcessedImageField to FilerImageField
I currently have a model for reusable images: class Image(models.Model): class Meta: verbose_name = _('Image') verbose_name_plural = _('Images') name = models.CharField( max_length=200, unique=False, blank=False, null=False, verbose_name=_('Image name') ) full_size = ProcessedImageField( upload_to='images/', processors=[ResizeToFit(height=450, upscale=False)], format='JPEG', options={'quality': 90}, ) thumbnail = ImageSpecField( source='full_size', processors=[Thumbnail(width=200, height=115, crop=True, upscale=False)], format='JPEG', options={'quality': 60} ) def __str__(self): return self.name Now I'm trying to move over to the FilerImageField from django-filer. I have added the field with a different name, here's the relevant code section: image = models.ForeignKey( Image, on_delete=models.SET_NULL, verbose_name=_('Unit image'), null=True, blank=True ) img = FilerImageField( null=True, blank=True, related_name="unit_img", verbose_name=_('Unit image'), on_delete=models.DO_NOTHING, ) I have the following migration: # Generated by Django 3.1.2 on 2020-11-02 20:09 from django.db import migrations from filer.models import Image def migrate_unit_images(apps, schema_editor): Units = apps.get_model('tageler', 'Unit') for unit in Units.objects.all(): if unit.image: img, created = Image.objects.get_or_create( file=unit.image.full_size.file, defaults={ 'name': unit.name, 'description': unit.image.name, } ) unit.img = img unit.save() class Migration(migrations.Migration): dependencies = [ ('tageler', '0008_filer_create'), ] operations = [ migrations.RunPython(migrate_unit_images), ] My problem is that I get the following error: ValueError: Cannot assign "<Image: This is a test image>": "Unit.img" must be a "Image" instance. I thought that I just created or gotten the Image. What am I missing …