Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trigger is not working Django REST API Test Case
I used the Django REST framework to build API and written a Trigger in PostgreSQL. basically trigger function checks the value in the second database and if the value presents then it gives exception and also removes the row from the first table. when I test this in the Django REST framework the data is not inserted and the trigger doesn't work so I end up doing the duplicate entry. so is there any way to insert data in database while testing? -
How to create Article Detail models in Django?
I have problem when i try to create article detail on my web app. Stuff like that: class ArticleDetail(models.Model): title = models.CharField(default='title', max_length=121) image = models.FileField(upload_to='/uploads') content = models.TextField() But i don't know how to render to template. Example: # THIS IS TITLE OF ARTICLE # image_1 # Content # image_2 # continue content # format code (just like markdown) # continue content How i can implement models for this? Thanks for help. -
How To Insert Value in CKEDITOR using AJAX in Django?
I am using AJAX request to send form data back in the views.py but I am not able to save CKEDITOR form. First, I am inserting some value to the CKEDITOR using setData method Here is my AJAX Code function showComnt(){ var getcm ="<blockquote>" + $("#cmntbysuraj").text()+ "</blockquote> <br> <hr> <br> <br>" CKEDITOR.instances['id_content'].setData(getcm); }; function SendComment(){ var currentURL= window.location.href.toString() var value = CKEDITOR.instances['id_content'].getData() var token = '{{ csrf_token }}'; $.ajax({ type: "POST", url: currentURL , data: { csrfmiddlewaretoken: token, content:value, }, dataType:'json', success: function(data){ if(data){ } } }); }; In my views.py. I am trying to save the form but it is not valid. How can I save the form ..... .... .... getCmntfromUser = request.POST.get("comment") form= CommentPage(request.POST or None) if form.is_valid(): print('form is valid') instance = form.save(commit=False) instance.user = user instance.post_id = postId instance.save() ...... ..... .... Note- When I print(form) , I got the whole page in HTML format. I don't understand why this is happening. -
Django wrong username, password for custom user model
I have created custom user model by using 'OneToOneField'. I have created the signup and signin system but only signup is working and I am able to register new user but, when I try to signin using that created user, Django is not allowing me to signin by showing my custom message 'Username or password is wrong'. I have double checked the username, password and it is correct but still Django is not allowing me to signin. Here are my codes. models.py class Vendor(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) phone_number = models.CharField(max_length = 12, blank = True) forms.py class SignInForm(forms.Form): username = forms.CharField(max_length = 20, widget = forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Username'} )) password = forms.CharField(max_length = 15, widget = forms.PasswordInput(attrs = {'class': 'form-control', 'placeholder': 'Password'} )) views.py form = self.form(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username = username, password = password) if user: if user.is_active: login(request, user) return redirect('dashboard') else: messages.error(request, 'Your email address is not verified. Please verify it') else: messages.error(request, 'Username or password is wrong') -
Django: How to add ManyToMany Value in form from other Model
So i have 2 Models. Ingredient and recipe. I want to add like a plus button with a popup that will open a Modal on this page, that will let me create an Ingredient. I don't want that the User has to create ingredients and then the Recipe. My Models: class Recipe(models.Model): name = models.CharField(max_length=100, blank=False) ingredient = models.ManyToManyField('Ingredient',) for_persons = models.IntegerField(null=False) instruction = models.TextField(blank=True) def get_absolute_url(self): return reverse('Rezept-Detail', kwargs={'pk': self.pk}) class Ingredient(models.Model): name = models.CharField(max_length=100, blank=False) quantity = models.IntegerField(null=False, blank=False) UNIT_CHOICES = ( ("ML", "Milliliter"), ("L", "Liter"), ("KG", "Kilogramm"), ("PCK", "Packung"), ("P", "Portion"), ) unit = models.CharField( max_length=20, choices=UNIT_CHOICES ) def __str__(self): return self.name My Form: class RecipeForm(forms.ModelForm): class Meta: model = models.Recipe fields = ['name', 'ingredient', 'for_persons', 'instruction'] Someone know, how to tackle this? -
Excluding some values from raw query
I have made a raw query(for postgresql) that the list the songs required to be played on the requests. However, when I am unable to exclude the songs from this raw query which have been blocked in my SongsBlocked model. initial_query_string = '''select songs.id,songs.albumart,songs."albumartThumbnail", cpr.votes, is_requested from (select id,albumart, "albumartThumbnail" from (select song_id from core_plsongassociation where playlist_id in (%s))'''%pl_ids_tuple songs_request = Song.objects.raw(initial_query_string + ''' as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join (select song_id, bool_or(thirdpartyuser_id=%s) as is_requested from (select * from core_priorityrequests where client_id=%s and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, ) as cpr on songs.id=cpr.song_id where songs.name ilike %s or songs.artist ilike %s limit %s offset %s''', [request.anon_user.id, restaurant.client.id,search_string,search_string,limit,offset,]) The SongsBlocked Model is as follows: class BlockedSongs(models.Model): client = models.ForeignKey('Client') user= models.ForeignKey(settings.AUTH_USER_MODEL) song = models.ManyToManyField('Song') playlists = models.ManyToManyField('Playlist', blank=True) Can anyone suggest the except query that I am missing here? -
Django rest framework different permissions on different projects for a user
In a project management application, a user is assigned multiple projects and can have different permissions on different projects. We tried implementing it using groups and permissions. The problem is that we didn't find a way to associate permissions with projects. We tried by extending groups model and assigning different groups to the user but in this case, when checking for permissions all the permission from all the groups is appended so no luck there as well. What is the better way to handle this? -
Unable to upload picture to s3 using boto on production
i have an endpoint from which I upload images to s3. Now the problem is that the code is not working on production server while upload from a local machine and the testing server is working fine. This is the error i get on production: Exception Type: HTTPClientError at /v3/file/ Exception Value: An HTTP Client raised and unhandled exception: 'module' object has no attribute 'wait_for_read' Api code: import boto3 from hireapp.settings import AWS_S3 from django.shortcuts import render from django.utils.crypto import get_random_string from .serializers import AdCategorySerializer class FileUpload(APIView): permission_classes = (IsAuthenticated, ) def post(self, request, format=None): img = request.data["file"] session = boto3.Session( aws_access_key_id=AWS_S3["AWS_ACCESS_KEY_ID"], aws_secret_access_key=AWS_S3["AWS_SECRET_ACCESS_KEY"], ) s3 = session.resource('s3') image_name = get_random_string(25) + img.name s3.Bucket(AWS_S3["AWS_STORAGE_BUCKET_NAME"]).put_object(Key='media/%s'%image_name, Body=img, ACL='public-read') #url to image image_url = "https://mobile.testapp.net/media/{image}".format(image=image_name) return Response(image_url,status=status.HTTP_200_OK) And this is part of stacktrace: *File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 477. response = self.handle_exception(exc) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 437. self.raise_uncaught_exception(exc) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 474. response = handler(request, *args, **kwargs) File "/home/irongate-server/irongate-server/hireapp/v3/views.py" in post 29. s3.Bucket(AWS_S3["AWS_STORAGE_BUCKET_NAME"]).put_object(Key='media/%s'%image_name, Body=img, ACL='public-read') File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/boto3/resources/factory.py" in do_action 520. response = action(self, *args, **kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/boto3/resources/action.py" … -
Django websockets image upload binary get extension
I am trying to send image via javascript websockets as binary data var ws = new WebSocket('ws://127.0.0.1:8000/ws/message/'); var file = document.getElementById('ImageUpload').files[0]; console.log(file) ws.binaryType = "blob"; ws.send(file) Using Django channels I am receiving the binary data from channels.generic.websocket import WebsocketConsumer class Consumer(WebsocketConsumer): def connect(self): ..... ..... self.accept() def receive(self, text_data=None, bytes_data=None): if bytes_data: # doing some stuffs How can get the extension(.jpg/.png) of the image file form the binary data which I receive via websocket, can you pleas guide me some suggestion for this, it will be very helpful for me. Thanks in advance. -
multiple html form from a single form model in django
i need your assistance im building a school president vote tallying system the vote results are saved in the polls table as candidate id | pollingstationid | result | when capturing the results the html page will render the form for each candidate. for example if there are 3 candidates the html form will have 3 forms: candidate 1: result _______ candidate id 1001 pollingstationid 301 candidate 2: result _______ candidate id 1002 pollingstationid 301 candidate 3: result _______ candidate id 1003 pollingstationid 301 [submit button] the problem: when i click submit, its only saving the last form(i.e candidate 3) how do i get all three entries into the database each as a new row. views.py class candidatesview(AjaxFormMixin, View): form_class = pollsForm model = Polls template_name = 'app/candidates.html' def get(self, request): form = self.form_class() candidatesls = Candidates.objects.all() context = {'title':'polls','form' : form, 'candidates': candidatesls } #print(context) return render(request, self.template_name, context ) def post(self, request): form = pollsForm(request.POST) candidatesls = Candidates.objects.all() if form.is_valid(): print(form.cleaned_data['Result']) print(form.cleaned_data['Candidateid']) print(form.cleaned_data['PollingstationID']) form.save() messages.success(request,('Form submitted successfuly')) else: messages.warning(request,('nah!')) print(messages) context = {'title':'polls','form' : form, 'candidates': candidatesls, 'message':messages} return render(request, self.template_name, context) forms.py class pollsForm(forms.ModelForm): class Meta: model = Polls fields = ['Result', 'Candidateid','PollingstationID'] html (candidates.html) {% extends … -
Django Rest Framework unit testing for PUT request
"test_put_method_success" is showing AssertionError: 404 != 200. But the "test_post_method_success" working fine. How to solve for PUT request? class BasicTest(APITestCase): def setUp(self): self.client = Client() self.user = User(username="admin", email="admin@gmail.com") self.user.is_staff = True self.user.set_password('admin') self.user.save() def test_post_method_success(self): url = "http://127.0.0.1:8000/settings/modules/" data = { 'modulename': "Module test", 'activation_status': "Active" } self.assertTrue(self.client.login(username="admin", password="admin")) response = self.client.post(url, data, format='json') print(response.status_code) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_put_method_success(self): url = "http://127.0.0.1:8000/settings/modules/1/" data = { 'modulename': "Module test update", 'activation_status': "Active" } self.assertTrue(self.client.login(username="admin", password="admin")) response = self.client.put(url, data, format='json') print(response.status_code) self.assertEqual(response.status_code, status.HTTP_200_OK) -
Graphene-Django - how to pass an argument from Query to class DjangoObjectType
First of all, thanks ! it has been 1 year without asking question as I always found an answer. You're a tremendous help. Today, I do have a question I cannot sort out myself. Please, I hope you would be kind enough to help me on the matter. Context: I work on a project with Django framework, and I have some dynamic pages made with react.js. The API I'm using in between is graphQL based. Apollo for the client, graphene-django for the back end. I want to do a dynamic pages made from a GraphQL query having a set (a declared field in the class DjangoObjectType made from a Django query), and I want to be able to filter dynamically the parent with a argument A, and the set with argument B. My problem is how to find a way to pass the argument B to the set to filter it. The graphQL I would achieved based on graphQL documentation query DistributionHisto ( $id:ID, $limit:Int ) { distributionHisto(id:$id) { id, historical(limit:$limit) { id, date, histo } } } But I don't understand how to pass (limit:$limit) to my set in the back end. Here my schema.py import graphene from graphene_django.types … -
How can I add two different integer fields of the same model in Django
class Score(models.Model): Score_A=models.IntegerField() Score_B=models.IntegerField() how can I add Score_A and Score_B put the store the total in a new field -
Clear each view cache
I have a few views each has cache table. And deleting cache when pre_save callback. For now I delete every cache, everytime. Is there any way to delete each tables one by one??? class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() @method_decorator(cache_page(None)) @method_decorator(vary_on_cookie) def list(self,request,*args,**kwargs): class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() @method_decorator(cache_page(None)) @method_decorator(vary_on_cookie) def list(self,request,*args,**kwargs): @receiver(pre_save, sender=Article) def cache_delete_callback(sender, **kwargs): print("cache delete") from django.core.cache import cache;cache.clear()// want to delete only Article cache @receiver(pre_save, sender=Item) def cache_delete_tweet_callback(sender, **kwargs): print("clear tweet cache") from django.core.cache import cache;cache.clear() // wan to delete only Item Cache -
TemplateDoesNotExist error when extending an app template
I am having trouble setting up a template (under app directory) to extend a base.html that is in the root/templates/jinja2 directory settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [ os.path.join(BASE_DIR, 'templates/jinja2') ], 'APP_DIRS': True, ... }, } ] folder structure: apps |---app1 |---templates |---jinja2 |---listing.html |---templates |---jinja2 |---base.html listing.html {% extends "base.html" %} ... The error I am getting when I pull listing.html: TemplateDoesNotExist at ... base.html Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /webapps/pickup/env/lib/python3.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /webapps/pickup/env/lib/python3.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /webapps/pickup/src/apps/listing/templates/base.html (Source does not exist) What is the right way to extend to a base template in the root template folder? I am using Django 3.0.5 -
Session Create Error object is not subscriptable
I'm very new in Python and Django and I have one question. I'm developing a small page to display information from Cisco ACI datacenter infrastructure API. I use the library provided by Cisco from cobra.mit.session. To avoid to recreate session for each page, I want to initiate the session on the index page and use this session with request.session from Django. I did the following: request.session['session'] = LoginSession(login_details.srv, login_details.usr_id, login_details.usr_pw) health = func_health(request.session.get['session']) But it generate an error, I receive: 'method' object is not subscriptable If I do the following it works. session = LoginSession(login_details.srv, login_details.usr_id, login_details.usr_pw) health = func_health(session) Do I use request.session in the wrong way? Thanks for your help. -
bad operand type for abs(): 'str'
I am following form Beginning Django E-commerce Book . I am in lesson 4. Adding Shopping Cart but I got an template_tag error for the following code : from django import template import locale register = template.Library() @register.filter(name='currency') def currency(value): try: locale.setlocale(locale.LC_ALL,'en_US.UTF-8') except : locale.setlocale(locale.LC_ALL,'') loc = locale.localeconv() # value = int(value) return locale.currency(value,loc['currency_symbol'],grouping=True) The error is at {{sub_total|currency}} -
Celery with Rabbit MQ Virtual Host not accepting tasks from app.tasks.py in Django
Help needed! PS: I have already created Virtual Hosts using this link Celery and Vhosts settings.py CELERY_BROKER_URL = 'amqp://flash:flash_education@localhost:5672/flash' celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery( 'flash_education', namespace='CELERY', ) app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app1.tasks.py import datetime import json from celery import shared_task @shared_task(name="ping") def ping(): print("pong") Attaching images from my terminal, one of of the worker instance other is of the shell from which I am firing the tasks. Note: I started both after settings and all but it does not seem to work Worker terminal Screenshot shell instance firing the request RabbitMQ, Celery==4.4.2 Django==3.0.4 Please help! -
Django filter records depending on associations
I am building a Django site and I want to filter the records depending on what option the user chooses. For example, if the user picked python then all subjects related to python (Pandas, Django) should be displayed. At the moment it shows all the records in the subject database irrelevant of what option I pick. If the user picks python it will show pandas, Django, Angular, Sprint etc. I have added my views, models and URLs page to this git gist https://gist.github.com/gentaro87/f49983178c7f01648f1f457eaf749678 Additionally, I have also tried to change subject_menu @login_required def subject_menu(request, topic): topics_ids = Profile.objects.all().values_list('topic', flat=True).distinct() topics = Subject.objects.filter(topic__id__in=topics_ids) return render(request, "skills/subject_menu.html", { 'topics': topics }) to this topics = Subject.objects.filter(profiles__topic_set__name__slug=topic) but also no luck -
Deleting Objects with Django Delete
I have an issue deleting just a single object from my database, I have a code that gets a list of RDS hostnames from AWS and then compares the rds hostnames stored in my Database to that returned by AWS, if the rds hostname is stored in my DB and not returned by AWS it should be removed from my database, but my code eventually ends up removing all the RDS hostnames stored in my DB Here is my models class AwsAssets(BaseModel): aws_access_token = models.CharField(max_length=512, blank=True, null=True) aws_secret_token = models.CharField(max_length=512, blank=True, null=True) rds_count = models.IntegerField(blank=True, null=True) def __str__(self): return '{} - {}'.format( self.client_aws_access_token, self.client_aws_secret_token ) class Meta: verbose_name_plural = "Aws Assets" class AwsRdsNames(BaseModel): host = models.CharField(max_length=300, null=True, blank=True) port = models.IntegerField(null=True, blank=True) asset_link = models.ForeignKey(AwsAssets, null=True, blank=True, related_name="rds_endpoints", on_delete=models.CASCADE ) region = models.CharField(max_length=56, null=True, blank=True) scan_status = models.NullBooleanField(default=None) last_scan = models.DateTimeField(null=True, blank=True) def __str__(self): return "{}:{}".format(self.host, self.port) class Meta: db_table = 'aws_rds_names' ordering = ['-id'] and then here is the block of code responsible for deleting the rds hostnames all_stored_rds = AwsRdsNames.objects.all() stored_rds = all_stored_rds.filter(asset_link=self.asset) #This returns all the stored rds hosts in db aws_rds = get_rds() #This returns a list of rds hostname from aws for rds in stored_rds: … -
Cannot Redirect to other page
I am writing a view that retrieve an answer from game2.html, if the answer is correct, the view will redirect user to correct.html, if the answer is incorrect, then user will be redirected to incorrect.html. The problem now is after clicking the submit button, user won't be redirected. How do I solve it? morse_logs/views.py @login_required() def game2(request): """The Game2 page""" if request.user and not request.user.is_anonymous: user = request.user user_score, created = userScore.objects.get_or_create(user=user) ans1 = request.GET.get('ans1', '') if ans1 == '': ans1 = 0 if ans1 == 4: #user's score declared in model increase 5points #display correct and 5 points added to user user_score.score += 5 user_score.save() return redirect('morse_logs:correct.html') else: #user's score declared in model has no point #display incorrect and 0 point added to user return redirect('morse_logs:incorrect.html') return render(request, 'morse_logs/game2.html') @login_required() def correct(request): """The answer correct page""" return render(request, 'morse_logs/correct.html') @login_required() def incorrect(request): """The answer incorrect page""" return render(request, 'morse_logs/incorrect.html') game2.html {% extends "morse_logs/base.html" %} {% block content %} <title>GAME 2</title> <div> <h1>GAME 2</h1> <h2>2 + 2 = ?</h2> <form action="" method="get" > <input type="number" id="ans1" name="ans1"/><br><br> <input type="submit" name="game1Answer"/> </form> </div> {% endblock content %} -
I want to reverse these items in the context
I want my items to be displayed in the reverse order in the template here is my views.py @login_required(login_url='/customer/login/') def myorders(request): orders = OrderModel.objects.filter(cid = request.user.id) items = {} i = 0 for item in OrderModel.objects.filter(cid = request.user.id): items[item.id] = { "ordered_items" : item.items, "price":item.price, "address":AddressModel.objects.filter(userid = request.user.id)[i].address, "approval_status":item.approval_status } i = i + 1; context = {'items' : items} return render(request,"gupsupapp/myorders.html",context) -
Nested Loops in Django
I have in my models Projects and Tasks. I'd like to display on the template: Project 1 Task 1:1 Task 1:2 Task 1:n Project 2 Task 2:1 Task 2:n Project n Here's the model class Projects(models.Model): slug_project = models.CharField(max_length=200) project_name = models.CharField(max_length=200) project_due_date = models.DateTimeField() project_lead_time = models.IntegerField() project_assignee = models.CharField(max_length=200) project_status = models.CharField(max_length=200) def __str__(self): return self.project_name class Tasks(models.Model): slug_task = models.CharField(max_length=200) task_name = models.CharField(max_length=200) task_desc = models.TextField(null=True) task_channel = models.CharField(max_length=200) task_id = models.ForeignKey(Projects, on_delete=models.CASCADE) task_due_date = models.DateTimeField('Due Date') task_lead_time = models.IntegerField() task_assignee = models.CharField(max_length=200) def __str__(self): return self.task_name I'm not sure how to construct the view properly but here's my code: class mainPage(generic.ListView): template_name = 'dashboard/index.html' context_object_name = 'project_object' def get_queryset(self): """Return the last five published Coupons.""" return Projects.objects.order_by('project_name') def get_context_data(self, **kwargs): context = super(somePage, self).get_context_data(**kwargs) # context['tasks'] = Tasks.objects.order_by('task_name') #this would display ALL tasks context.update({ 'all_project': Projects.objects.all(), 'all_tasks': Tasks.objects.filter(task__id=self.object), }) return context And I'm also not confident how construct the template: {% if project_object %} {% for project_name in project_object %} <div class="card_row_h1"> <a href="{% url 'dashboard:task_list' project_name.id %}"> {{ project_name }} </a> </div> {% if all_tasks %} {% for task_name in tasks %} <div class="card_row_h2" style="width: 100%; padding-left: 30px;"> <small>{{ task_name }}</small> </div> {% endfor %} … -
Django admin page autocomplete doesn't work
I have models like this: Models class Customer(models.Model): customer_ref = models.CharField(unique=True, max_length=50) name = models.CharField(null=False, max_length=80) country = models.CharField(null=True, max_length=50) class Assortment(models.Model): name = models.CharField(null=False, max_length=50) customers = models.ManyToManyField(Customer, related_name='assortments', blank=True) products = models.ManyToManyField(Product, related_name='assortments', blank=True) class Subsidiary(models.Model): subsidiary_ref = models.CharField(unique=True, max_length=50) name = models.CharField(null=False, max_length=80) address = models.TextField(null=True) city = models.CharField(null=True, max_length=50) coordinates_x = models.DecimalField(null=True, decimal_places=2, max_digits=6) coordinates_y = models.DecimalField(null=True, decimal_places=2, max_digits=6) phone_number = models.CharField(null=True, max_length=50) frequency = models.ForeignKey(Frequency, on_delete=models.SET_NULL, null=True) channel = models.CharField(null=True, blank=True, max_length=50) subchannel = models.CharField(null=True, blank=True, max_length=50) user = models.ForeignKey(User, related_name='subsidiaries', on_delete=models.SET_NULL, null=True) day_planned = models.BooleanField(default=False) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='subsidiaries') class Asset(models.Model): identification = models.CharField(unique=True, max_length=50) serial = models.CharField(max_length=50) name = models.CharField(null=True, max_length=50) subsidiary = models.ForeignKey(Subsidiary, related_name='assets', null=True, blank=True, on_delete=models.DO_NOTHING) Admin @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): list_display = ['customer_ref', 'name', 'country'] list_filter = ['country'] autocomplete_fields = ['assortments'] @admin.register(Subsidiary) class SubsidiaryAdmin(admin.ModelAdmin): exclude = ['day_planned'] list_display = ['subsidiary_ref', 'customer', 'name', 'address', 'phone_number', 'frequency', 'user'] list_editable = ['frequency', 'user'] list_filter = ['frequency', 'user'] search_fields = ['subsidiary_ref', 'customer__name', 'name'] autocomplete_fields = ['assets'] CustomerAdmin is 'working' without error but field 'assortments' is not visible. SubsidiaryAdmin throws error : <class 'mobileapp.admin.SubsidiaryAdmin'>: (admin.E038) The value of 'autocomplete_fields[0]' must be a foreign key or a many-to-many field. witch is weird because I don't see … -
List of operation model is storing empty
enter image description here model.py enter image description hereack.imgur.com/rG6eW.png serlizer.py view.py postman respose