Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF - Different Request and Response Serialization
I;ve an API endpoint that requests data in the below format:- { "platform": "value", "username": "value", "login_type": "value" } Now, I've a model :- class ModelA(models.Model): field1 = models.IntegerField() The request variables are not the part of the model, hence I create the following serializer:- class GenerateOTPSerializer(serializers.ModelSerializer): """Serializer to generate OTP.""" username = serializers.CharField() login_type = serializers.IntegerField() platform = serializers.ChoiceField(choices=User.PLATFORM_CHOICES) def create(self, data): """Over-riding create method.""" platform, username = data.get('platform'), data.get('username') login_type = data.get('login_type') ###### some processing based on above input instance = Model.objects.create(field1=11111) return instance class Meta: """OTPSerializer Meta.""" model = OTP fields = ('username', 'login_type', 'platform') read_only_fields = ('field1', ) When I POST the data, the error returned back is The serializer field might be named incorrectly and not match any attribute or key on the `ModelA` instance. Original exception text was: 'ModelA' object has no attribute 'username'. I understand that it tries to get_attr the fields from the instance object. How do I send back the response where INPUT request is different(ie unrelated to the model fields) and response is different(ie related to the model fields)? -
Install python packages in Django [duplicate]
This question already has an answer here: No module named 'polls.apps.PollsConfigdjango'; Django project tutorial 2 5 answers I'm creating a blog in Django, but I've had some troubles trying to import thrid party modules, for instance, I just tried to import the django_markdown module to add a MarkDown field in my post model for the post body, I followed the instructions in the reddit package page, but when I try to run my django server it returns: ... ImportError: No module named 'django_markdownraulchirinos' Due to "raulchirinos" is my django app, I suppouse it's a problem with my project structure or with my config paths. Here's my models.py file: from django.db import models from django_markdown.models import MarkdownField class Post(models.Model): title = models.CharField(max_length=255) body = MarkdownField() tags = models.ManyToManyField(Tag) author = models.CharField(max_length=255, default='Raúl Chirinos') date = models.DateTimeField(auto_now_add=True, blank=True) Thanks in advance! -
Django performance good in view but big TTFB
I'm trying to optimize a Django app. I count the time needed by the DB query and context variable creation in the views.py and it only takes 0.10s. However, the loading time is quite long. Using Chrome Network tool I have a waiting TTFB of 6.54s. Apart from caching what can I try to lower the TTFB? -
Trying HttpResponse to return a template in my update function
I'm trying to update an entry in table with the help of form. I was told to use HttpResponse instead of HttpResponseRedirect so i did this: return HttpResponse(template.render({}, request), id) The url is changing in address bar but a blank table is being displayed. I don't what is causing this error. This is my view for update row. def updaterow(request, id): item = get_object_or_404(Studentapp, id=id) if request.method == "POST": form = EntryForm(request.POST, instance=item) template = loader.get_template('studentapp/index.html') if form.is_valid(): post = form.save(commit=False) post.save() return HttpResponse(template.render({}, request), id) else: form = EntryForm() return HttpResponseRedirect(reverse('studentapp:index'), id) return render(request, 'index.html',{'form':form}) I'm using a different form for updating the entry. It's name is "_edit_student.html" -
Querying django migrations table
How can one query the django_migrations table from a view? For instance(What I have tried and of course not working) from django.db import migrations latest_migration = migrations.objects.all().order_by('-applied')[0] If possible, how should one proceed? -
Django rest framework M2M serializer returning nested objects in original sequence
I have two models: Task and Scenario. Tasks are created beforehand and Scenarios are created afterwards by including few of the existing tasks. Important thing is in a scenario, tasks must be arranged in a specific sequence and not according to their ids. class Task(models.Model): stakeholder = models.ForeignKey(User, related_name='tasks', blank=True, ) project = models.ForeignKey(Project, related_name='project_tasks' ) title = models.CharField(max_length=50, blank=True, null = True, ) ... class Scenario(models.Model): stakeholder = models.ForeignKey(User, related_name='scenarios', blank=True,) tasks = models.ManyToManyField(Task, blank=True) Serializers: class TaskSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Task fields = '__all__' class ScenarioSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True, required=False) class Meta: model = Scenario fields = '__all__' def get_or_create_task(self, data): qs = Task.objects.filter(pk=data.get('id')) if qs.exists(): return qs.first() task = Task.objects.create(**data) return task def add_tasks(self, instance, tasks): for task_data in tasks: task = self.get_or_create_task(task_data) instance.tasks.add(task) def create(self, validated_data): tasks = validated_data.pop('tasks') instance = Scenario.objects.create(**validated_data) self.add_tasks(instance, tasks) return instance def update(self, instance, validated_data): tasks = validated_data.pop('tasks', []) instance = super().update(instance, alidated_data) self.add_tasks(instance, tasks) return instance Few requirements I had: While retrieving a scenario/s I wanted to retrieve corresponding task objects and not just their ids, that's why line id = serializers.IntegerField() exists in TaskSerializer. With this code a new Task is successfully created, but Task … -
Django issue: TypeError: 'NoneType' object is not callable
I'm working on a Django framework and I get this error every time I successfully log in to my site. So yes incorrect login doesn't trigger it. It doesn't effect the site or my tests, but the stacktrace is just really annoying with every test. I'm using python 3 and django 2 with django-adminlte-cruds and django-guardian. This is the full stacktrace and I have absolutely no idea what code of mine could cause this and I have looked at other posts about the same error but can't find anything that applies to my code. Traceback (most recent call last): File "/usr/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable Traceback (most recent call last): File "/usr/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/home/ellen/.virtualenvs/purple_box/lib/python3.5/site-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) … -
Retrieve data from textfield elements created dynamically with Django templates
I have a Django view like this: def viewA(request): if request.GET.get('Go'): # Get all fields all = {} for key, values in request.POST.lists(): all[key]=values print (all) With this html: <label>Numero de telefono</label> <input type="text" name="phone" autocomplete="off"/> <input type="submit" name="Go" value="Send"> When i click 'Go' button, i get "all" dict with the phone value inside. Ok. My problem is that i have another view where i create input elements with a template like this: <div> {% for table, campos in tables.items %} <div class="taable"> <label>{{table}}</label> {% for campo in campos %} <div class="caampo"> <input type="text" value="{{campo}}" disabled name="{{table}}:{{campo}}"/> <select> <option>Varchar</option> <option>Int</option> ... In this case, when i click 'Go' button don't retrieve the data for this elements created dynamically with django template. How can I get this? Thanks! -
Buildout not using pinned versions
When I try to run buildout for a existing project, which used to work perfectly fine, it now installs the incorrect version of Django, even though the version is pinned. For some reason, it's installing Django 1.10 even though I've got 1.6 pinned. (I know that's an old version, but client doesn't want me to upgrade just yet.) Here is a very trucated version of the the buildout config file. [buildout] index = https://pypi.python.org/simple versions = versions include-site-packages = false extensions = mr.developer unzip = true newest = false parts = ... auto-checkout = * eggs = <... Many eggs here ...> Django <... Many more eggs ...> [base-versions] ... Django = 1.6.1 ... [versions] <= base-versions The only other thing that I can think of that could possibly make an impact is that I recently reinstalled my system to Kubuntu 18.04 (Was previously Ubuntu 17.10) -
Django: validate by field excluded from ModelForm
Can you validate a model form field by comparing it to an excluded field? How should the excluded field be set on init? class MyModel(models.Model): amount = models.DecimalField() balance = models.DecimalField() class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs) self.balance = ?? super(MyForm, self).__init__(*args, **kwargs) class Meta: model = MyModel fields = ['amount'] def clean_amount(self): amount = self.cleaned_data['amount'] if not (self.balance > 0 and amount > 0) or (self.balance < 0 and amount < 0) raise forms.ValidationError( 'Cannot apply a negative amount to a positive balance and vice versa.') return amount -
Django compare two querysets and create a list based on these values with additional data added for each item
I have a UserProfile Model and a Friends Model. I display a list of profiles on a the page in a template and I want to mark whether a UserProfile is a Friend of the current user as each is displayed. I would ideally like to avoid a nested loop on the template where I have to compare the Friend Queryset with the UserProfile Queryset to see if there is a match. I have models as such( with additional fields not shown): class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) friends = models.ManyToManyField("self", through='relationship.Friend', symmetrical= False, related_name= 'friend_to+' ) class Friend(models.Model): from_userprofile = models.ForeignKey("profile.UserProfile", related_name='from_profile', on_delete=models.CASCADE) to_userprofile = models.ForeignKey("profile.UserProfile", related_name='to_profile', on_delete=models.CASCADE) status = models.IntegerField(choices=RELATIONSHIP_STATUSES) date_connected = models.DateTimeField(auto_now=False, auto_now_add=True) In the views I first get all the UserProfiles and then the current users Friends like this: profile_query = UserProfile.objects.all().exclude(Q(user_id=request.user.id)). select_related('user') current_user_friends = Friend.objects.filter(Q(from_userprofile__user_id=request.user.id) & Q(status__exact=1)) Now from here I want to efficiently work out which of the Users in the "profile_query" set are also in the "current_user_friends" set and combine this info if possible into one single list or dictionary or Queryset that I can use in the template. I'd like to loop through and create a new field or value called "isFriend" … -
how get a csv file and excel formats (xls xlsx,..)with django rest framework
I need to limit the syllabus that I've written to get only certain format files. I also need to send my response to Jason. I will send my code and i guess my problem is in serializing.py but i can not Understand where is it when i send csv file or xls or xlsx return ' "Wrong file type: text/plain"' and now my code : my model : from django.db import models class File(models.Model): file = models.FileField(blank=False, null=False) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) my viwe: # Create your views here. from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) and my serializer : class FileSerializer(serializers.ModelSerializer): ALLOWED_TYPES = [ 'text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/json', ] class Meta(): model = File fields = '__all__' def validate_file(self, value): mime = magic.Magic(mime=True) ftype = mime.from_buffer(value.file.read(1024)) if ftype not in self.ALLOWED_TYPES: msg = 'Wrong file type: {}'.format(ftype) raise serializers.ValidationError(msg) value.file.seek() return value and i will thank you if you help me that fix it my python version = 3 and … -
Get many to many objects selected in django admin panel
I would like to retrieve objects selected in my many to many relationship, in the Django admin panel. Is it possible and how can I do that? For now I'm just able to retrieve all objects, like that: views.py def get_feature_score(request, name): if request.method == 'OPTIONS': return HttpResponse() provider_name = name providers = list( FeatureInfo.objects.all() .filter(providerComment=provider_name) .values()) return providers -
Why does this OneToOneField reverse relationship not persist to the database?
Relevant frameworks: Django, Django REST Framework On POST everything seems fine: a 201 Created response is returned and the JSON representation of what should have been persisted to the database in the response body is correct. In reality, the reverse relationship between Flag and Product has not been established (see relevant models, serializer, and view below) and Product.flag is actually null. Relevant models: class Product(models.Model): ... flag = models.OneToOneField('Flag', null=True, blank=True, related_name='product') class Flag(models.Model): ... reasons = ManyToManyField('FlagReason') severity = models.CharField(...) notes = models.TextField(...) ... Relevant DRF serializer: class FlagSerializer(serializers.ModelSerializer): class Meta: model = models.Flag fields = ('id', 'reasons', 'notes', 'created_timestamp', 'modified_timestamp', 'severity', 'product',) Relevant DRF view: class FlagListCreate(generics.ListCreateAPIView): queryset = Flag.objects.all() serializer_class = FlagSerializer filter_fields = ('severity',) POST request JSON body: { "product": 1328, "severity": "mid", "reasons": [1, 2], "notes": "Test note", } 201 Created response to the above POST request (note product pk): { "id": 31, "reasons": [ 1, 2 ], "notes": "Test note", "created_timestamp": "2018-04-30T11:54:50.762054+01:00", "modified_timestamp": "2018-04-30T11:54:50.762084+01:00", "severity": "mid", "product": 1328 } Response to GET request for above Flag (note product value is null): { "id": 31, "reasons": [ 1, 2 ], "notes": "Test note", "created_timestamp": "2018-04-30T11:54:50.762054+01:00", "modified_timestamp": "2018-04-30T11:54:50.762084+01:00", "severity": "mid", "product": null } -
Django password encryption
I'm not sure I'm asking this in the right place and please suggest a different Stack if it should sit elsewhere. I understand that by default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST [docs]. According to Wikipedia, The PBKDF2 key derivation function has five input parameters: DK = PBKDF2(PRF, Password, Salt, c, dkLen) Is the Salt used SECRET_KEY? If not, what Salt is used? -
In Django load a CSS file depending on a variable name and only if it exists
In Django I wish to load a CSS file only if it exists. The name should be created by a variable name. Something like this kind of works: <link rel="stylesheet" href="/static/core/css/{{ site.id }}.css" /> But the problem is of curse, that it always tries to laod the file, wether it exists or not. Also I would like to use the "static" template tag, but this does not work: <link rel="stylesheet" href="{% static "core/css/{{ site.id }}.css" %}" /> Can someone help? -
Infinitly running backgruond task django
So Here is my problem. I have a Django website, that connects users with some telegram bots. The bots need to be running at all time in the django backend to listen for updates and respond to them. Currently I just start a thread for all these bots, but I don't think this is the correct way(also since users can spawn new bots, and the gil slowing everything down). Which library's are good for handling this issue? -
How to use custom UseChangeForm in django admin or exculde fields in user change form
i wanted to exclude fields like password and permissions from user change form tried writing a custom UserForm inheriting from UserChangeForm class UserForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User exclude = ('password', 'user__permissions',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] and added it in UserAdmin class UserModelAdmin(UserAdmin): list_display = ('username', 'email', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups', 'gender') form = UserForm add_form = AdminUserCreationForm fieldsets = UserAdmin.fieldsets + ( (_('Profile'), {'fields': ( 'state', 'education', 'geographical_location', 'health_style', 'gender', 'social_style', \ 'chronic_conditions', 'profession', 'is_profile_complete')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username',), }), ) but no effect on admin -
Login permissible even though email address not verified
I am using Django rest-auth and allauth for registration functionality. After a user registers, an email should be sent that a user is required to click on before they become an active user. Currently, the user is marked as is_active in the api_user table as soon as they register (no email verification was required and I was also able to login). I noticed the verified column in the account_emailaddress table is being updated correctly (set to 0 before email verification and 1 afterwards). However this is does not seem to have any bearing on the is_active column in the api_user table. These are my current Django settings: AUTH_USER_MODEL = 'api.User' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION='mandatory' Would anyone know what I might not be doing? Any explanations as to how this should work is greatly appreciated. Thanks for your help! -
Django filter users by is_active and has_usable_password() method
I have a user manager which has a method to create users without password. Now, I need to get all unactivated users which is user.is_active=False and user.has_usable_password()=False. Django doc link for has_usable_password(). I wan't to do something like below. User.objects.filter(is_active=False, password__has_usable_password=False) -
Why function size always increase when refreshing it using memory profiler python?
I am using a python memory profiler and at top of every function, I am using @profile on top of function to analyze the memory consumption of the function.But every time I refresh the same page the size of my function always increases.Why is it so I don't know. I tried using python garbage collector but that has no impact.An example of this i am pasting here. Line # Mem usage Increment Line Contents ================================================ 27 83.2 MiB 83.2 MiB @login_required 28 @profile 29 def app_user_detail(request, slug=None): 30 83.3 MiB 0.1 MiB university_obj = Universities.objects.using('cms').filter(deleted=0, status=1, verified=1) 31 83.3 MiB 0.0 MiB ids = [4, 5] 32 83.3 MiB 0.0 MiB master_user_types = MasterUserTypes.objects.using("cms").filter(~Q(id__in=ids)).all() 33 83.3 MiB 0.0 MiB gc.isenabled() 34 83.3 MiB 0.0 MiB gc.collect() 35 83.3 MiB 0.0 MiB return render(request, 'templates/news_managment/news_dashboard_detail.html', 36 89.0 MiB 5.7 MiB {'slug': slug, 'university_obj': university_obj, 'master_user_types': master_user_types}) Suppose,i have 89.0 Mib right now for this function but when i refresh it the size will increase.I am running the django project on localhost -
Redirect to specific url instead of 404 in Django
Instead of doing a raise Http404 in the following code, I would like to send the user to a specific URL ('/risking/notyours/'). I have tried to use HttpResponseRedirect and reverse, but I can't seem to get anything to work. Suggestions? Code: class ProspectDelete(LoginRequiredMixin, DeleteView): login_url = '/accounts/login/' model = Prospect template_name = 'risking/prospect_delete.html' success_url = reverse_lazy('index') def get_object(self, queryset=None): """ Hook to ensure object is owned by request.user. """ obj = super(ProspectDelete, self).get_object() if not obj.owner == self.request.user: raise Http404 ###This is what I need to change### return obj -
Django Syntax Error while Attempting SubURL's
I'm not only new to Django but also Python.I'm following a video tutorial in my native language; however while applying instructions, I got following error: > Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f6b2477eae8> Traceback (most recent call last): File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/stockfish/Masaüstü/DjangoOne/myvenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File … -
Django queryset with variable value
I am writing dynamic filters in django for my database where I am using the below code where I have 2 variables(p_type,s_type): p_type=[] s_type=[] query = request.GET.get("q") p_type =request.GET.get("p_type") s_type = request.GET.get("s_type") #messages.add_message(request, messages.INFO, p_type) #messages.add_message(request, messages.INFO, s_type) if query: queryset_find = queryset_list.filter( Q(FP_Item__contains=query)) context = {'object_list': queryset_find} return render(request, 'index.html', context) elif p_type: queryset_find = queryset_list.filter( Q(p_type__contains=s_type)) context = {'object_list': queryset_find} return render(request, 'index.html', context) else: context = {'object_list': queryset} return render(request, 'index.html', context) but django returns error at below line Q(p_type__contains=s_type)) I have dynamic radio button where the value of p_type matches with my database but even though I am receiving the following error: Exception Type: FieldError Exception Value: Cannot resolve keyword 'p_type' into field. Choices are: ... (same choices which I am using with my database). Isn't it doable with variable query ? Any other methods ? -
AttributeError: 'File' object has no attribute 'model'
I a having following setup in which my Model classes look like following from django.db import models from User.models import UserProfile class Advertisement(models.Model): owner = models.ForeignKey(UserProfile, related_name='advertisements', on_delete=models.CASCADE) title = models.CharField(max_length=500, blank=False, default='') location = models.CharField(max_length=300, blank=False, default='') rent = models.IntegerField(blank=False) status = models.CharField(max_length=100, blank=False) no_of_bedrooms = models.IntegerField(blank=False) no_of_bathrooms = models.IntegerField(blank=False) posted_by = models.CharField(max_length=100, blank=True) date_ad_posted = models.DateTimeField(null=True, blank=True) contact = models.CharField(max_length=13, blank=False) description = models.CharField(max_length=1000, blank=False) security_deposit = models.IntegerField(default=0, blank=False) def save(self, *args, **kwargs): super(Advertisement, self).save(*args, **kwargs) class File(models.Model): Ad = models.ForeignKey(Advertisement, related_name='ad-photo', on_delete=models.CASCADE) file = models.FileField(blank=False, null=False) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) and my serializers look like following class AdvertisementSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.email') class Meta: model = Advertisement fields = ('id', 'owner', 'title', 'location', 'rent', 'status', 'no_of_bedrooms', 'no_of_bathrooms', 'date_ad_posted', 'posted_by', 'contact', 'description') kwargs = { 'url': {'view_name': 'advertisement-detail'} } class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ('Ad', 'file', 'remark', 'timestamp') i am registering my model in admin.py in following way from django.contrib import admin from .models import Advertisement, AdContract, File class FileInline(admin.TabularInline): model = File class PropertyAdmin(admin.ModelAdmin): inlines = [FileInline, ] admin.site.register(Advertisement, File) admin.site.register(AdContract) but upon making migrations i am getting following error i have tried a few solutions i got after googling but the …