Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Intermittent failure: Django Rest Framework Authentication
I have a Django Rest Framework back-end, which works well but I have been experiencing an intermittent error below: { "detail": "Invalid token." } In my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } I only secure some of my end-points, such as the below:- class ViewOrder(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderDetailSerializer authentication_classes = (TokenAuthentication,) def get_queryset(self): user= self.request.user queryset = Order.objects.filter(user=user) return queryset permission_classes = (IsAuthenticated,) This works fine, but on one of my views where I don't secure it, I get the first error 'detail: Invalid Token' class Verify(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): phone = request.data['phone'] response = { 'status': 'failed' } code = random.randint(1000,9999) validator = Verify(email=email,code=code) validator.save() return JsonResponse(response,safe=False) I don't know where this Invalid Token 401 response is coming from. Any help would be greatly appreciated -
Django unable to access exact Amazone S3 bucket file location
I have Django project with storage in S3, I am able to POST images to S3 but unable to GET/Delete. For example, If I go to AWS bucket and check for specific image urls it shows as below and its globally accessible for any person, https://mystoragename.s3.us-east-2.amazonaws.com/pics/myimagename.jpg However when I try to retrieve in Django the image is not showing , the image path as below, https://mystoragename.s3.amazonaws.com/pics/amazone.JPG?AWSAccessKeyId=mystorageID&Signature=mystorageSIGN&Expires=A_NUMBER How come Django unable to locate exact path to image ? I have installed boto and storage app in Django and my settings are as below, AWS_ACCESS_KEY_ID = 'mykey' AWS_SECRET_ACCESS_KEY = 'mykey' AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
ModuleNotFoundError: No module named 'django' on Elastic Beanstalk
I'm following AWS's Django documentation on EB, but I still get the same error in the logs: ModuleNotFoundError: No module named 'django' The documentation is already wrong on where to point your WSGIPath in .ebextensions/django.config, but I fixed it to point to my wsgi.py file. The deploy works, but the site 500s. What do I do? -
Alternate model, which PK is used as default value for OneToOneRelation
I've run into a problem with Django migrations. I have following models: class ModelA(models.Model): field_x = models.OneToOneField( 'app_label.ModelB', default=ModelB.get_fresh, ) class ModelB(model.Model): field_y = models.TextField() @classmethod def get_fresh(): return cls.objects.create().id What I want to do is to add another field to ModelB. So I've added the field and then runned makemigrations command. class ModelB(model.Model): field_y = models.TextField() field_z = models.BooleanField(default=False) @classmethod def get_fresh(): return cls.objects.create().id Unfortunately, while running the tests, when django makes full migration for my project it says that there is no such column for default object. django.db.utils.ProgrammingError: column "field_z" of relation "model_a_modelb" does not exist Which is technically true, because default was added on previous migration and it don't know yet it new schema. What I can do, to solve this problem and be able to extend ModelB in this case? -
Django serializers: Why source argument in does not work?
I have the following Serializer in my Django project: class MySerializer(serializers.Serializer): CheckList1 = serializers.CharField(source='source_field', default="pass") I use it for data validation, like this: input_serializer = MySerializer(data=request.data) input_serializer.is_valid(raise_exception=True) The source argument seems to be not working. I pass there the request data that looks like this: request.data = { source_field = "Failed" } when I print input_serializer.data the value of CheckList1 is pass. Does anybody know why? -
How to get list of objects shown in the current admin page at the beginning of page load
I have a list of entities showing up on the admin page, and a "DocuSign envelope status" column computed by a function. Now I need to add more details to the status column, but those details are stored in another microservice (existing architecture, so I need to make an HTTP call with the status.id to the other microservice to get those details. But doing that call in the method would mean a call for each row e.g. 20 calls per page, which I want to avoid. I've figured out that using get_changelist or get_queryset to run the function once per page load gives me an acceptable starting point. There I'd get the details for all entities shown in the current page in one go, and then I'd get the needed data from that output, in each row. However, I couldn't find any way of getting the list of currently listed entities at the beginning e.g. in get_queryset or anywhere similar in my research, so I cannot make that query in the first place. def get_queryset(self, request): qs = super().get_queryset(request) self.list_of_statuses_for_this_page = self.get_statuses_list(list_of_entities_here) return qs Have gone through all docs and online searches but got stuck here. Thought of querying everything … -
Django pre_delete signal raises "TypeError: metric_pre_delete() missing 1 required positional argument: 'usings'"
I'm trying to define a pre_delete signal handler for Django models delete() method. Prototype of signals.py is defined as def metric_pre_delete(sender, instance, usings, **kwargs): print(f"Hello from metric_pre_delete") This seems coherent with Django pre_delete signal documentation. However, when doing so, I got following error: TypeError: metric_pre_delete() missing 1 required positional argument: 'usings' ../../.virtualenvs/tsango/lib/python3.6/site-packages/django/dispatch/dispatcher.py:175: TypeError I have two questions about this Error: Do you have a clue of what I'm doing wrong? Do you know what 'usings' parameter is supposed to do? I don't think that I need to set it (despite the error is about it...). But I'm curious of its usage. I wasn't able to find an example despite some googling... The connection to the handler is defined as follows in apps.py: from django.apps import AppConfig from django.db.models.signals import pre_delete from django.utils.translation import gettext_lazy as _ from .signals import metric_pre_delete class TsangodConfig(AppConfig): name = 'tsangod' verbose_name = _('Tsango data management') def ready(self): from .models.metrics import Metric pre_delete.connect(receiver=metric_pre_delete, sender=Metric, dispatch_uid='metric-pre-delete') Thanks in anticipation for your support! -
Specific number of access/query for a specific access level for Users
My client wants me to make an exclusive site where there are many levels of access privileges for every user. For example, a user with level 1 get to access certain endpoint (let's say a POST request with an image url to invoke similar clothes) only three times a month, a level 3 user gets to access ten times a month, and a user with level 5 get to access it as many as she/he wants. When I read through the Django documentation regarding login_required decorator, it doesn't seem like it can classify the users based on my custom user settings. Let me show you the part of the model in question. account/models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) level = models.IntegerField(default=1) objects = UserManager() USERNAME_FIELD = 'email' I also read through the section where it mentions certain permissions for certain groups, but it only tells me about the preliminary method of authorizing, like either letting a level 3 user have an unlimited number of accesses to an endpoint or not. Here, the key question is that I am looking for a method through which I can restrict the number of … -
Django runserver failing during admin site checks
When running runserver command, we are getting the error below which makes breaks the runserver command: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 55, in check_admin_app for site in all_sites: File "/usr/local/lib/python3.7/_weakrefset.py", line 60, in __iter__ for itemref in self.data: RuntimeError: Set changed size during iteration It doesn't happen every time though. Has anyone seen this kind of error before? -
How to save use model attributes for calculations in Django
I am trying to build a simple application that takes accounting info from the user and calculates the Weighted Average Cost of Capital (WACC). I have some confusion as to how to apply this in Django. Should I do the calculations within the models, views or just the templates themselves? So far, I did it in the models, this is the code I have: from django.db import models class TaxRateEstimation(models.Model): income_before_tax = models.IntegerField() income_tax_expenses = models.IntegerField() @property def calculate_tax_rate(self): result = (self.income_tax_expenses / self.income_before_tax) if result < 0: return result * -1 return result class CostOfDebtEstimation(models.Model): interest_expenses = models.IntegerField() short_current_lt_debt = models.IntegerField() lt_debt = models.IntegerField() @property def calculate_cost_of_debt(self): result = self.interest_expenses / (self.short_current_lt_debt + self.lt_debt) if result < 0: return result return result class CostOfEquityEstimation(models.Model): rf_rate = models.FloatField(default=0.01) beta = models.FloatField(default=1) market_return = models.FloatField(default=0.1) @property def calculate_capm(self): return self.rf_rate + self.beta * (self.market_return - self.rf_rate) class Weights(models.Model): total_debt = models.IntegerField() market_cap = models.IntegerField() @property def debt_weight(self): return self.total_debt / (self.total_debt + self.market_cap) @property def equity_weight(self): return self.market_cap / (self.total_debt + self.market_cap) class WACC(TaxRateEstimation, CostOfDebtEstimation, CostOfEquityEstimation, Weights): def calculate_wacc(self): return self.equity_weight * self.calculate_capm + self.debt_weight * self.calculate_cost_of_debt * (1 - self.calculate_tax_rate) Up until the WACC class is called, the calculations work … -
Django Ckeditor File Upload - Error With Path?
I'm trying to use ckeditor_uploader and receiving the following error when attempting to upload an image from the admin dashboard. img-5485.JPG:1 GET https://fixmybike-staging.herokuapp.com/media/uploads/2020/06/23/img-5485.JPG 404 (Not Found) I have no issues uploading a file when I run the server locally, so I'm assuming this is related to how Heroku handles media paths and how I've configured it. base.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bikemech', 'ckeditor', 'ckeditor_uploader', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' CKEDITOR_UPLOAD_PATH = "uploads/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') I'm also already using 'whitenoise.middleware.WhiteNoiseMiddleware', urls.py from django.contrib import admin from django.urls import path, include from bikemech import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor', include("ckeditor_uploader.urls")), path('', include('bikemech.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've attempted a variety of configurations in base.py from other stack overflow posts with no luck. Also, Heroku is succeeding at running collectstatic so I don't believe that's the issue. -
How can i show django-filter results in another view, assuming i have a search box in my home page and a results page to display the results?
I have been using django-filters in many of my projects where the search form is on the same page as the list of results and that works just fine, but now im faced by a scenario where i have a search box in my home page and a results page somewhere else, how can i pass the filtered results to the view of my results page? -
How to split a string and form an array in javascript?
I have a string which is like this: str = "['fvfvf "fvs vfs" fsvsfv'g dfbd', "vbvv'f fdfvd", 'dfbdfbgd dgbdbdb', 'kjhjkj'd jiijui "ddddd"']" I am trying to split the above string and the result I'm looking for is: fvfvf "fvs vfs" fsvsfv'g dfbd vbvv'f fdfvd dfbdfbgd dgbdbdb kjhjkj'd jiijui "ddddd" -
Daphne on Elastic beanstalk - WebSocket handshake: Unexpected response code: 500
Following this guide https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 to set up a django app that uses websockets. 01_env.config option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: dashboard.settings PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elasticbeanstalk:container:python: WSGIPath: dashboard/wsgi.py aws:elbv2:listener:80: ListenerEnabled: 'true' Protocol: HTTP aws:elbv2:listener:5000: ListenerEnabled: 'true' Protocol: HTTP 02_setup.config container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' 04_celery_tasks: command: "cat .ebextensions/celery_configuration.txt > /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 05_celery_tasks_run: command: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 03_proxy.config files: "/etc/httpd/conf.d/proxy.conf": mode: "000644" owner: root group: root content: | ProxyPass /websockets/ ws://127.0.0.1:5000/websockets/ ProxyPassReverse /websockets/ ws://127.0.0.1:5000/websockets/ ProxyPass / http://127.0.0.1:5000/ ProxyPassReverse / http://127.0.0.1:5000/ When opening the websocket I get the message on chrome's console: WebSocket connection to 'ws://xx.xx.xx.elasticbeanstalk.com/websockets/' failed: Error during WebSocket handshake: Unexpected response code: 500 Logs indicate: AH01144: No protocol handler was valid for the URL /websockets/ (scheme 'ws'). If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule. Loaded apache modules listed on the EC2 instance by running sudo apachectl -M: Loaded Modules: core_module (static) so_module (static) http_module (static) access_compat_module (shared) actions_module (shared) alias_module (shared) allowmethods_module (shared) auth_basic_module (shared) auth_digest_module (shared) authn_anon_module (shared) authn_core_module (shared) … -
can templates only use callable in django?
is it neccesary to use callable functions in templates {{ startup.get_success_url }} instead of using function with parenthesis '()' {{ startup.get_success_url() }} I tried {{ startup.name }} but getting an error -
connect postgres fron docker
I have postgres installed in my ubuntu18.04, and running on port 5432. I have django application and its in docker. my database connection in settings.py file is like below. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': 5432, } } when i run command sudo docker-compose run it gives me below error. -
i have some issue with django pagination
i have get some mess with to many of page numbers with pagination. i want to slice these numbers like this. anybody know how can i show it some adorable look? views.py def Latest(request): obj = Article.status_objects.all() paginator = Paginator(obj, 1) page = request.GET.get('page') obj = paginator.get_page(page) context = { 'object': obj, } return render(request, 'core/template.html', context) template.html {% if object.paginator.num_pages > 1 %} <!-- pagination --> {% if object.has_other_pages %} <ul class="pagination"> {% if object.has_previous %} <li><a href="?page={{ object.previous_page_number }}"><span><i class="ti-angle-left"></i></span></a></li> {% else %} <li class="disabled"><span><i class="ti-angle-left"></i></span></li> {% endif %} {% for i in object.paginator.page_range %} {% if object.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if object.has_next %} <li><a href="?page={{ object.next_page_number }}"><span class="ti-angle-right"></span></a></li> {% else %} <li class="disabled"><span class="ti-angle-right"></span></li> {% endif %} </ul> {% endif %} <!-- pagination --> {% endif %} -
ForeignKey returning None after create request
im new at django rest , i am trying to create an order_item request that have the order id ,but after the create request i get None in the id_order ForeignKey Field , Views.py: class OrderItemsCreate(mixins.CreateModelMixin,generics.GenericAPIView): lookup_field = 'pk' serializer_class = OrderItemsSerializer def get_queryset(self): return OrderItems.objects.all() def post(self,request,*args,**kwargs): createOrder = Order.objects.create() orderId = Order.objects.latest('id') data = request.data data._mutable = True data['id_order'] = orderId data._mutable = False p = request.data['id_order'] print(p) print(data) res = self.create(request,*args,**kwargs) print(res.data) if res.status_code == 201 : return res Serialziers.py: class OrderItemsSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) id_order = serializers.SlugRelatedField( many=False, required=False, read_only=True, slug_field='id_ticket' ) class Meta: model = OrderItems fields = ['url','id','id_order','id_food','quantity'] def get_url(self,obj): request = self.context.get("request") return obj.get_api_url(request=request) models.py: class OrderItems(models.Model): id_order = models.ForeignKey(Order, on_delete = models.CASCADE, null=True, blank=True) id_food = models.ForeignKey(Food, on_delete=models.CASCADE) quantity = models.IntegerField() -
How to restore sqlite3 database file programmatically in django
The user wishes to have a database backup and restore functionality through the application. They want to be able to download the database file and upload it to restore the database whenever needed. The problem is that django is already running the current DB file. I wrote the following logic to restore the database. folder ='./' if request.method == 'POST': myfile = request.FILES['file'] fs = FileSystemStorage(location=folder) if myfile.name.split(".")[1] != "sqlite3": return JsonResponse({"res":"Please upload a database file."}) if os.path.isfile(os.path.join(folder, "db.sqlite3")): os.remove(os.path.join(folder, "db.sqlite3")) filename = fs.save("db.sqlite3", myfile) file_url = fs.url(filename) return JsonResponse({"res":file_url}) I get the following error which is rightly justified: [WinError 32] The process cannot access the file because it is being used by another process So, is there a way I can achieve this functionality through my application? -
How to call javascript function from HTML loop ( django html template render object iteration) ...Django template html
{% for research in orders %} <script > var data1 = {{ research.pressReleases}}; </script> {% endfor %} <script> function Members1(data) { var keys = []; document.write("<table style='text-transform:uppercase' border==\"0\"><tr>"); for (key in data[0]) { if (key != 'id') { document.write('<td style="background-color: #bde9ba;">' + key + '</td>'); } } document.write("</tr>"); for (var i = 0; i < data.length; i++) { document.write('<tr>'); for (key in data[i]) { if (key != 'id') { if (key == 'url') { document.write('<td><a href="' + data[i][key] + '">' + data[i][key] + '</a></td>'); } else if (key == 'headline') { document.write('<td>' + data[i][key].text + '</td>'); } else { document.write('<td>' + data[i][key] + '</td>'); } } } document.write('</tr>'); } document.write("</table>"); } </script> <script>Members1(data1);</script> It is Django framework where trying to call from html to javascript function , in that function trying to pass parameter from html... how this can be done? iteration is just one iteration for a row or a value. -
django + mod_wsgi + apache + cpanel doesn't work
I have Centos7 with cPanel installed + Apache and mod_wsgi. I'm trying to deploy to the server right now. The issue is everything seems to be configured properly, except my URL show the list of files instead of runs the Django application. I'm not sure what is wrong. Here is my configuration: Apache config: ServerName mytool.domain.me ServerAlias www.mytool.domain.me DocumentRoot "/home/username/public_html/ctltoolbox/smtool" WSGIDaemonProcess mytool.domain.me python-home=/home/username/public_html/ctltoolbox/ctltoolbox-venv/ python-path=/home/username/public_html/ctltoolbox/smtool WSGIProcessGroup mytool.domain.me Alias /media/ /home/username/public_html/ctltoolbox/smtool/media/ Alias /static/ /home/username/public_html/ctltoolbox/smtool/static/ <Directory /home/username/public_html/ctltoolbox/smtool/static/> Allow from all </Directory> <Directory /home/username/public_html/ctltoolbox/smtool/media/> Allow from all </Directory> WSGIScriptAlias / /home/username/public_html/ctltoolbox/smtool/smtool/wsgi.py <Directory /home/username/public_html/ctltoolbox/smtool/> <Files wsgi.py> Allow from all </Files> </Directory> My wsgi.py file: import os from django.core.wsgi import get_wsgi_application sys.path.append('/home/username/public_html/ctltoolbox/smtool') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smtool.settings') application = get_wsgi_application() And here is my project structure of the folder /home/username/public_html/ctltoolbox/ |-- ctltoolbox | `-- smtool | |-- api.py | |-- get_data.py | |-- mainapp | | |-- __init__.py | | |-- admin.py | | |-- apps.py | | |-- forms.py | | |-- managers.py | | |-- middleware.py | | |-- models.py | | |-- settings.py | | |-- tests.py | | |-- urls.py | | `-- views.py | |-- manage.py | |-- requirements.txt | |-- smtool | | |-- __init__.py | | |-- asgi.py | | |-- settings.py … -
Saving .xlsx files from request
I want to save excel file from request.FILE to temporary file. Do I have to iterate over columns and rows and rewrite each cell? Can I do it direct? What about .zip files? I want to obtain path to those files. Can I do it without saving the files? Thanks in advance :) -
django - AttributeError: 'AnonymousUser' object has no attribute 'todo'
Im trying to get all the todos that belongs to the user, here is my todo model from django.db import models from django.contrib.auth.models import User class Todo(models.Model): _id = models.AutoField(primary_key = True) title = models.CharField(max_length = 250) content = models.TextField() created_at = models.DateField() complete = models.BooleanField(default = False) owner = models.ForeignKey(User, related_name = 'todo', on_delete = models.CASCADE, null = True) and here is my todo view set from rest_framework import viewsets, permissions from .models import Todo from .serializers import TodoSerializer class TodoViewSet(viewsets.ModelViewSet): permissions_classes = [ permissions.IsAuthenticated ] serializer_class = TodoSerializer def query(self): return self.request.user.todo.all() def create(self, serializer): serializer.save(owner = self.request.user) and when Im sending a req to /api/todo/ (the todos rest api) Im getting this error: AttributeError: 'AnonymousUser' object has no attribute 'todo' what could be the problem? and should I create user model? at the moment I'm using django user. -
TypeError at /members/ Object of type 'Europe/Budapest' is not JSON serializable
class Member(models.Model): mid = models.CharField(max_length=12) real_name = models.CharField(max_length=60) tz = TimeZoneField(default='Europe/London') class Period(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() Here, the timezone is not JSON serializable. How do I make it serializable? -
Add item in Product model in django
I have two models. Product and AddAmount I want a script like this: Adding a value with Amount -> amount Let this value be the product_amount value in my product model. Increase or decrease when I update. Consider the standard inventory model. I translated with Google. Sorry. Models.py class Product(models.Model): product_code = models.CharField(max_length=50) product_name = models.CharField(max_length=100) product_price = models.DecimalField(decimal_places=2, max_digits=10) product_tax = models.PositiveIntegerField() product_category = models.ForeignKey('ProductCategory', verbose_name='Product category', on_delete=models.CASCADE) product_brand = models.ForeignKey('ProductBrand', verbose_name='Product brand', on_delete=models.CASCADE) product_description = models.TextField() product_create_date = models.DateTimeField(auto_now_add=True) product_update_date = models.DateTimeField(auto_now=True) product_amount = models.IntegerField() class Meta: verbose_name_plural = "Product" def __str__(self): return self.product_name def get_absolute_url(self): return "/products/{}".format(self.id) class AddAmount(models.Model): product = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE) amount = models.IntegerField()