Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Query "not in" M2M
I got these three models: class Crcheck(models.Model): crlist = models.ForeignKey("crlists.Crlist", on_delete=models.CASCADE) persons = models.ForeignKey("persons.Person", on_delete=models.CASCADE) ... | id | crlist_id | persons_id | | 41 | 2 | 64 | | 42 | 3 | 64 | class Cuslistprofile(models.Model): customer= models.ForeignKey("customers.Customer",on_delete=models.CASCADE) crlist = models.ManyToManyField("crlists.Crlist") ... class Crlist(models.Model): dbname=models.CharField(max_length=200) ... as a result of the M2M Django generates this table "cuslistprofiles_cuslistprofile_crlist" | id | cuslistprofile_id | crlist_id | | 9 | 4 | 2 | | 13 | 4 | 3 | | 14 | 4 | 5 | | 19 | 4 | 7 | what I want to achieve is to get all the crlist values that are in "cuslistprofiles_cuslistprofile_crlist" but missing in "crcheck". In this particular example I want to retrieve 5 and 7. How can I achieve that in Django ORM? Thanks in advanced -
Pip cannot install anything on ubuntu server
I had deleted an existing virtual environment. I created a new one and activated it. Now I am trying to install site packages using pip install -r requirements.txt But I keep getting the error Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement BeautifulSoup==3.2.1 (from -r requirements.txt (line 1)) Now I know that the packages are really old but this is running on python 2.7.6. I am also not able to install anything through pip. I have tried pip install numpy But it shows the same errors. As per the similar questions answered before the suggestion is to use https://pypi.python.org which I have already done but still facing these errors. Would love to hear your suggestions. -
What is the use of -r in the pip install command? [duplicate]
What is the use of -r in this install command? pip install -r requirments.txt -
'QuerySet' object has no attribute 'price'
I am a student learning Django. I write code like this 'QuerySet' object has no attribute 'price' This is the situation in which this error occurs. I am attaching the code I wrote. Any help would be greatly appreciated. I want to write an if statement to save when the price in Designated is equal to the sum of Value.extra cost and Designated(Rep_price='True'), but it doesn't work as I thought. What is the problem? Models.py class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.join_code) class Meta: ordering = ['join_code'] Views.py def join_create(request, id): current_category = None designated = Designated.objects.all() element = Element.objects.all() value_object = Value.objects.all() categories … -
Retrieve Similar Objects by Tags in Django
In the book Django 3 by Example (Chapter 2), the author suggests the following to retrieve posts similar to 'current post' based on tags (via the taggit module). post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] I understand the flow: Get a list of all the IDs for the tags in the current post. Filter all posts basis the list derived above, and exclude the current post. Add a calculated field to the posts derived above that specify the number of tags they have in 'common' with current post. For example, if current post has tags 'one' and 'two', and another post has 'two' and 'three', the calculated field should be same_tags = 1 (i.e. 'two') Here's where I am confused: In point 2 above, will I get a QuerySet that has duplicate posts. For example, if a post has 2 tags in common with the current post, will the resulting QuerySet have 2 instances of the post? I tried this in shell, and this is what it seems to return. For example, if post has two tags in common with current post, it will be included twice. But I am not sure why this should be the … -
question_on_approve() missing 1 required positional argument: 'created'
I am trying to add points once the question is posted on the models. But it is showing question_on_approve() missing 1 required positional argument: 'created'. @receiver(pre_save, sender=question) def question_on_approve(sender, instance, created, **kwargs): if not created: oldQuestionObj = question.object.get(pk=instance.pk) questionObj = instance if oldQuestionObj.status != 1 and questionObj.status == 1: Points.objects.create(point=somepointfromPointsTableForQuestionAsked) -
I have a model form in django, whenever i submit the form i am getting both the custom success message and the default one how to suppress the default
obj.save() messages.success(request,'{} is successfully updated'.format(obj.template_name)) here the obj.save() saves all the changes in database. and then I am printing my custom message after it. -
Add packages outside of pip to elastic beanstalk
I am trying to install django-betterforms on elastic beanstalk using the setup.py. The git repo is located at : github.com/jpic/django-git.betterforms On the local machine,its fine,but I cant seem to get elastic beanstalk to install it. I have added this line in the requirements.txt: -e git://github.com/jpic/django-git.betterforms I get this in the logs: Extracting django_betterforms-1.2.2-py3.8.egg to /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages django-betterforms 1.2.2 is already the active version in easy-install.pth Which states that django-betterforms is installed. Also, on doing cat easy-install.pth I get : ./django_betterforms-1.2.2-py3.8.egg But,later in the logs AWS throws : ModuleNotFoundError: No module named 'betterforms' Also, if I try to ssh into the environment and try to import betterforms,python can't find it. -
How to save image in django database?
I have a newclaim form which allows user to upload a picture The current problem I faced is whenever I try to upload a new picture, it is not stored on my database (which is my models.py) How do I solve this? This is my views.py # Submit a new Claim def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins = SaveClaimForm(receipt=receipt) ins.save() print("The Data has been written") return render(request, 'Login/newclaim.html/', {'user':user}) This is my newclaim.html <form action="/newclaim/" method="post" enctype="multipart/form-data"> <div> <input id="receipt" type="file" name="receipt_field" style="display: none; visibility: none;"> </div> </form> This is my saveclaimform models class SaveClaimForm(models.Model): receipt = models.FileField(upload_to='receipts/%Y/%m/%D', validators=[FileExtensionValidator(allowed_extensions=['jpg','png'])]) -
`python manage.py runserver` shows an old webapp page I developed
I am learning Django so I've created many Django webapps under one directory. For example, \webapps \polls \polls \api \manage.py ... \ponynote \ponynote \frontend \manage.py ... I didn't use a virtualenv for developing django apps. I don't know whether it's the reason that causes the problem as below. App 1 python manage.py runserver works all fine. (default port 8000) App 2 python manage.py runserver still shows the App 1 page. Method I tried: change the port python manage.py runserver 8001, it shows App 2 page. try to find the process ID PID, and kill it. No sign of port 8000. However, this isn't the best solution since I can't change the port everytime when developing a new django app. Does anyone have a clue why this happens? Kudos. -
ERROR: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
Settings.py file contains # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['project-crm.herokuapp.com', '127.0.0.1'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' #SMTP Configurations EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = 'True' EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') #S3 Bucket CONFIG AWS_ACCESS_KEY_ID= os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY= os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME= '******' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_HOST = 's3.ap-south-1.amazonaws.com' AWS_S3_REGION_NAME="ap-south-1" I got stuck on this error someone please help. I have added AmazonS3FullAccess under user permission. Also edited Block public access in S3 bucket. I also set environment variables in Heroku but this error still comes. -
Django Rest Framework (DRF) sets JSON field to Empty in the to_internal_value function
So I am trying to upload file AND Post JSON data to my API following this solution. I have created the Parser, placed it in my viewset. I even receive the image and the JSON data in the to_internal_value function, which i think runs AFTER the parser parses the data. How ever, as soon as the to_internal_value function is run, the location field is set to empty. I overrided the function to see whats happening, and it seems the field.get_value function is returning the empty value. Here's the parser: class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # for case1 with nested serializers # parse each field with json for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value else: data[key] = value qdict = QueryDict('', mutable=True) print(data) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) Here's the Serializer: class AssetSerializer(serializers.ModelSerializer): """ Serializes data recieved/retrieved to/from endpoints concerning Assets. """ asset_location = LocationSerializer(required=False,allow_null=True) asset_devices = serializers.PrimaryKeyRelatedField(many=True,queryset=Device.objects.all(),required=False) parent = serializers.PrimaryKeyRelatedField(queryset=Asset.objects.all(),required=False) busy_ranges = serializers.CharField(required=False) time = serializers.ReadOnlyField( source='datetime') status = serializers.CharField(source="current_status",required=False) class Meta: model = Asset fields … -
how to run a html template on the project's base path 127.0.0.1:8000/ on python-django
I am learning Python-Django I want to run a html template on the project's very base site 127.0.0.1:8000/ I don't want to run it in 127.0.0.1:8000/polls or something like that. My myproject/urls.py file looks like this urlpatterns = [ path('', include('?????')), path('admin/', admin.site.urls), path('polls/', include('polls.urls')) ] I don't know what to include in place of '?????' to run a html template on 127.0.0.1:8000/ -
! [remote rejected] master -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/immense-anchorage-56196.git
i am trying to push my code to heroku but i am getting error when i am running push command command i am runnin g--> git push heroku master:main -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 1b461938974e19dafd44baf4db9e9a43f4db7f2e remote: ! remote: ! We have detected that you have triggered a build from source code with version 1b461938974e19dafd44baf4db9e9a43f4db7f2e remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... -
How to get csv file in request in django?
I want to get csv file in post(request) in djnago. file = request.FILES['file'] #is this way is correct to get csv file I have tried code given but getting error this :- UnsupportedMediaType: Unsupported media type "text/csv" in request. pl help I have stuck two days. def post(self, request, version_id): """ upload csv file to s3 params: request (csv file) """ response = {"success": True, "data": {}, "message": ""} file = request.FILES['file'] #is this way is correct to get csv file is_valid, message = self.validate_file(file) #this function for check file is csv or not if is_valid: ImageUpload = ImageUploader() try: response = ImageUpload.upload_file(file) except Exception as e: response.update({"success": False, "message": e}) else: response.update({"message": message, "success": False}) return Response(response, 200) -
Django: How to ask user to select an option on website homepage and use that value in all website pages
I am working on a website, I am confused with following. I need to ask user on homepage to select an value from a dropdown and use that value in other pages of website. I have an Navbar on base.html which is common on all other view files via - {% extends '..base/html' %}, so nav bar will be common and below it all other pages render. So I am thinking to have a dropdown on navbar and every page I open should be able to keep the selected dropdown value at start, unless it is changed. Eg: ecommerce sites asks for PINCODE and uses that to show available products. (Similar to this). How should I solve this, I am really confused and not able to find anything. Thanks. -
Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to profenity, there after logging there after pages are not rendering properly. I've followed the examples in my lessons and checked the code a hundred times but obviously there is something I'm missing i'm having some issues on revercenotFound when i logging there i getting this error everthing working properly before when i pushed code into server i getting this error. NoReverseMatch at /user_dashboard Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/user_dashboard Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name. Exception Location: /usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py, line 694, in _reverse_with_prefix Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/eunagi/Project/image_processing', '/usr/local/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Tue, 27 Jul 2021 10:38:54 +0000 Error during template rendering In template /home/eunagi/Project/image_processing/templates/user_base.html, error at line 33 Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name. 23 <span class="icon-bar"></span> 24 </button> 25 </div> 26 27 <div class="navbar-collapse collapse navbar-pad"> 28 <ul class="nav navbar-nav mynav" … -
How to remove last comma after objects in Array []?
I have a array like this: Array [ Object { "id": 1, "item": "Hair service", }, Object { "id": 2, "item": "Face service", }, ] How can i covert this Array To Array like this without last comma? Array [ Object { "id": 1, "item": "Hair service", }, Object { "id": 2, "item": "Face service", } ] Because when i try axios.post method foreign key values not adding to my model. Via postman when i try post method, everything is work done. Convert to string in my case not a good variant. Because i need post Array to my relation model. Thank you -
How to pull and run dockerized django application from docker hub
I have dockerized a django application and it is working fine as a container. I used docker-compose. Then I pushed it to hub repo. How I can pull the image and run it and what are the commands to do that? -
how can i create Db table using ForiegnKey relationship in DRF
Halo i'm working on creating multiple DB table using foreignKey but i'm having some error hoping anyone can help out, below is my code & the error msg ###models.py file class SchoolVideo(models.Model): school = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='school_video') intro_video = models.FileField( upload_to='assets/videos', blank=True, null=True) ###serializer file class VideoSerializer(serializers.ModelSerializer): class Meta: model = SchoolVideo fields = ('intro_video',) def create(self, validated_data, *args, **kwargs): if 'user' in validated_data: user = validated_data.pop('user') else: user = Profile.objects.create(**validated_data) school_video = SchoolVideo.objects.update_or_create( user=user, defaults=validated_data ) return school_video API VIEW class SchoolVideoAPi(generics.CreateAPIView): serializer_class = VideoSerializer queryset = SchoolVideo.objects.all() permission_class = [permissions.IsAuthenticated] parser_classes = (MultiPartParser, FormParser) def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data, instance=request.user.profile.school_video ) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.data, message='Video successfully Uploaded', status=status.HTTPS_201_CREATED, headers=headers, ) def perform_create(self, serializer): print(self.request.user.profile) serializer.save(user=self.request.user.profile) -
Django exclude field from '__all__' in DjangoFilterBackend for ModelViewSet
I have multiple API classes (ModelViewSets) that are inheriting from one common ViewSet. So there are different kinds of models with their own fields but all share the same features that are defined in the common viewset. One of those features - is filtering. It looks like this: class CommonViewSet(viewsets.ModelViewSet): filter_backends = (DjangoFilterBackend,) filter_fields = '__all__' class FirstViewSet(CommonViewSet): model = FirstModel class SecondViewSet(CommonViewSet): model = SecondModel # etc... Each model has a different set of fields, except that each model has a common field user. I don't want this field to be exposed in any way. I have excluded this field from the serializers: class CommonSerializer(serializers.ModelSerializer): class Meta: exclude = ('user',) class SecondSerializer(CommonSerializer): class Meta: model = FirstModel # etc... What I want to achieve is to exclude the field user from filter_fields of CommonViewSet as well. I.e.: filter_fields = '__all__' # except 'user' Is there a standard way to do that? -
How to display one set of data between two models?
I have Model Question and Answer. What I want to accomplish is to be able to display it in the template in a way that shows like this. I would like to know a way to accomplish this. I'm trying my best to not let it loop the whole data in a model but rather one data at a time. I'm trying to make a qna data and make it display on a template. so having all the Questio data displayed before Answer data is not what I want. It has to be one by one for these two models. I'm getting kinda close...but I stil can't figure out how to accomplish this. Any help or advice would be greatly appreciated. Thank you in advance. Q.title Q.body A.body Q.title Q.body A.body Q.title Q.body A.body modesl.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Question(models.Model): title= models.CharField(max_length= 100) body= models.TextField() date_posted= models.DateTimeField(default=timezone.now) author= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.title class Answer(models.Model): body= models.TextField() question= models.ForeignKey(Question, on_delete= models.CASCADE) date_posted= models.DateTimeField(default=timezone.now) author= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.body qna.html template {% extends "info/base.html" %} {% block content %} {% for question in questions %} <h1> Q</h1> … -
How to send push notification to the user using firebase and django
I want to send a push notification to the user when the admin enter status field and saves it. Ex I am developing an e commerce website so, I have an model called orders where I have status which can contain some text it will be initially blank when the admin fills it and saves it, the user of the respective order should get notified. Please help me ... How to send push notification using firebase and django iam a beginner. I couldn't understand the documents they provided . Please help me with an simple example. -
Django How to filter all objects foreign key field
table : event_rewards table : rewards serializer : EventRewardSerializer serializer : RewardSerializer models.py class Reward(models.Model): id = models.BigAutoField(primary_key=True) category = models.IntegerField(blank=True, null=True) count = models.IntegerField(blank=True, null=True) image = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255) price = models.IntegerField(blank=True, null=True) class Meta: db_table = 'reward' class EventRewards(models.Model): event = models.ForeignKey(Event, models.DO_NOTHING) rewards = models.OneToOneField('Reward', related_name='event_id', on_delete=models.CASCADE) class Meta: db_table = 'event_rewards' serializers.py class EventRewardSerializer(serializers.ModelSerializer): class Meta: model = EventRewards fields = ['event', 'rewards'] class RewardSerializer(serializers.ModelSerializer): event_id = serializers.SlugRelatedField( read_only=True, slug_field='event_id' ) class Meta: model = Reward fields = ['id', 'category', 'count', 'image', 'name', 'price', 'event_id'] views.py class JoinRewardView(APIView): def get(self, request, pk_event, pk_post, pk_user, formant=None): reward_list = Reward.objects.all().filter(event_id=pk_event) print(reward_list) reward_list_serializer = RewardSerializer(data=reward_list, many=True) reward_list_serializer.is_valid() print(reward_list_serializer.data) return Response(reward_list_serializer.data, status=status.HTTP_400_BAD_REQUEST) postman -> all().filter(event_id=1) [ { "id": 1, "category": 1, "count": 100, "image": "img3", "name": "coke", "price": 1000, "event_id": 1 } ] postman -> all() [ { "id": 1, "category": 1, "count": 100, "image": "img3", "name": "coke", "price": 1000, "event_id": 1 }, { "id": 2, "category": 1, "count": 10, "image": "img4", "name": "coffee", "price": 2500, "event_id": 1 } ] all() -> 2 data -> ok! all().filter(category=1) -> 2 data -> ok! all().filter(event_id=1) -> 1 data -> why??? -
Django Admin: Subtotal of each TabularInline entry and set into a model field
I have SupplierBill & SupplierBillList model. I'd like to total up all of my TabularInline SupplierBillList model class attribute net_price, and save that value to my SupplierBill's sub_total attribute. I pick some code, that does not work properly. When I submit the form, sub_total does not update in SupplierBill view page. If I enter SupplierBill detail View page, then it store into db & update in SupplierBill view page. How can I solve this? Image Model.py class SupplierBill(models.Model): supplier = models.ForeignKey(Supplier,on_delete=CASCADE,null=True,blank=True) payment_method = models.ForeignKey(PaymentMethod,on_delete=DO_NOTHING,null=True,blank=True) account = models.ForeignKey( Account, on_delete=DO_NOTHING, null=True, blank=True) sub_total = models.DecimalField( max_digits=20, decimal_places=2, null=True, blank=True) class SupplierBillList(models.Model): supplier_bill = models.ForeignKey( SupplierBill, on_delete=CASCADE, null=True, blank=True) product_name = models.CharField(max_length=300,null=True,blank=True) product_code = models.CharField(max_length=300,null=True,blank=True) quantity = models.BigIntegerField(null=True,blank=True) unit = models.ForeignKey(Unit,on_delete=DO_NOTHING, null=True, blank=True) price = models.DecimalField( max_digits=20, decimal_places=2, null=True, blank=True) net_price = models.DecimalField( max_digits=20, decimal_places=2, editable=False) Admin.py class SupplierBillListInline(admin.TabularInline): model = models.SupplierBillList insert_after = 'account' readonly_fields = ['get_net_price'] exclude = ['net_price'] def get_net_price(self, obj): entry = SupplierBillList.objects.get(id=obj.id) entry_subtotal = obj.quantity * obj.price if entry.net_price != entry_subtotal: try: entry.net_price = entry_subtotal entry.save() except DecimalException as e: print(e) return "Taka:" + str(entry_subtotal) get_net_price.short_description = 'net_price' class SupplierBillAdmin(admin.ModelAdmin): list_display = ('id','supplier', 'payment_method','account', 'sub_total', ......) fieldsets = ( (None, {'fields': ( 'supplier', 'payment_method','account', 'sub_total', .....)} ), …