Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django testing model instance setup
Why when creating instance as a class attribute: class ModelTestsProducts(TestCase): # Create example objects in the database product_category = models.Product_category.objects.create( name='Spring' ) product_segment = models.Product_segment.objects.create( name='PS1', product_category=self.product_category ) product_group = models.Product_group.objects.create( name='PG1', product_segment=self.product_segment ) def test_product_category(self): self.assertEqual(str(self.product_category), self.product_category.name) def test_product_segment(self): self.assertEqual(str(self.product_segment), self.product_segment.name) def test_product_group(self): self.assertEqual(str(self.product_group), self.product_group.name) I am getting following error when running test for the 2nd time? django.db.utils.IntegrityError: duplicate key value violates unique constraint "products_product_category_name_key" DETAIL: Key (name)=(dadsad) already exists. When I use setUp method and then create objects insite this setUp method it works fine, but I cant understand why the above method somehow creates every object multiple times and thus fails the unique constraint set in the model. Is it because django test suite somehow calls this class everytime every test function is run, thus every attribute is assigned multiple times? But then if I move the object assignment outside the class (in the test file) then I also get this duplicate error, so that would mean whole test file is being called multiple times every time test is being run. One more thing I use docker to run this Django app and and run django test from docker-compose command. -
Is there any attribute or something like placeholder in django, where I can write the permanent text
I am making a simple form. i am searching any term in django like placeholder, but 'placeholder text' vanishes as user type something in text box. I want something like 'permanent text' in django-text-field, where as user opens the form, they have to start writing something after 'permanent text' which i have entered while coding. The permanent text should remain there user input and not fade-away like placeholder text does. -
not able to start the start the server djano
I am getting this error for no reason, not knowing where the problem lies, it's not allowing me to run migrations as well, I am posted by trace below, need help with this Traceback (most recent call last): File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\atif\PycharmProjects\my_proj_basic\food_deliveryapp\orders\models.py", line 9, in <module> class PlacedOrder(models.Model): File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\fields\__init__.py", line 788, in contribute_to_class if not getattr(cls, self.attname, … -
Pass and receive object pk to fix foreign key field in CreateView in Django
I'm trying to build a django app to mantain a class called "Actuacion". Depending on the values of the field "tipo" additional info is required, so I have created a main class "Actuacion" with the common fields, and a different class for each "tipo" with specific fields for each type linked with the main class "Actuacion" through a foreign key. The model is something like this: models.py class TipoActuacion(models.Model): # Values for "tipo" by the moment are "DEPURACION", "CONSERVACION", "PLANEAMIENTO" tipo = models.CharField(max_length=50) def __str__(self): return self.tipo class Actuacion(models.Model): titulo = models.CharField(max_length=200) tipo = models.ForeignKey('TipoActuacion', on_delete=models.SET_NULL, null=True) # Other common fields class ActuacionPlaneamiento(models.Model): actuacion = models.ForeignKey('Actuacion', on_delete=models.SET_NULL, null=True) info = models.CharField(max_length=100) # Other fields class ActuacionDepuracion(models.Model): actuacion = models.ForeignKey('Actuacion', on_delete=models.SET_NULL, null=True) habitantes = models.IntegerField(null=True, blank=True) # Other fields class ActuacionConservacion(models.Model): actuacion = models.ForeignKey('Actuacion', on_delete=models.SET_NULL, null=True) fecha = models.DateField(null=True, blank=True) # Other fields So, I pretend to create "Actuacion" objects through django class-based views and after creating the main object, depending on the value registered on "tipo" field redirect to the corresponding create view to complete the info. The main class "Actuacion" is created but I haven't found the way to link it with the child entity (based on field "tipo", … -
How to get count in Django for a model two foreign keys away
I have three modles in my Django app as follows: class City(models.Model): city_name = models.CharField(length=50) class Area(models.Model): city = models.ForeignKey(City) area_name = models.CharField(length=50) class Person(models.Model): area = models.ForeignKey(Area) person_name = models.CharField(length=50) I require cities in order of their population (i.e. Person basis). How is it possible with Django? -
django form.errors showing "This field is required!" after running modelform validation with form.isvalid
So I'm trying to get a django model form to only accept alphanumeric input via REGEX, as shown here: class AddDeadCoin(forms.ModelForm): class Meta: model = DeadCoin fields = ( 'category', 'is_coin', 'name', 'ticker', 'founder', 'total_coins_or_tokens', 'no_exchanges', 'project_start_date', 'project_end_date', 'social_end_date', 'logo', 'screenshot', 'notes', 'links', ) def clean_name(self): name = self.cleaned_data.get('name') if bool(re.match(r'^[A-Za-z0-9_-]+$', str(name))): return name else: raise forms.ValidationError("Sorry , you can only have alphanumeric, _ or - in username") def save(self): instance = super(AddDeadCoin, self).save(commit=False) instance.slug = orig = slugify(instance.name) for x in itertools.count(1): if not DeadCoin.objects.filter(slug=instance.slug).exists(): break instance.slug = '%s-%d' % (orig, x) instance.save() return instance However, on trying to submit any input(both valid and invalid) I get a "This field is required!" forms.error message. I get the message twice to be precise. It should be noted that 'name' and 'ticker' fields are required. This is what my models look like: class DeadCoin(models.Model): name = models.CharField(max_length=70, default=None) summary = models.TextField(blank=True, null=True, default="Dead Coin Summary") ticker = models.CharField(max_length=20, default=None) founder = models.CharField(blank=True, null=True, max_length=50) is_coin = models.BooleanField(blank=True, null=True, default=True) notes = models.TextField(blank=True, null=True, default='') links = models.TextField(blank=True, null=True, default='') total_coins_or_tokens = models.CharField(blank=True, null=True, max_length=50, default='Unknown') no_exchanges = models.BooleanField(blank=True, null=True, default=True) project_start_date = models.CharField(blank=True, null=True, max_length=10, default='2018') project_end_date = models.CharField(blank=True, null=True, max_length=10, … -
Django - inline formset save multiple rows
I'm following this tutorial to create an inline formset where you can add & remove rows. The visual aspect is working fine, adding & removing rows works fine but when I click the create button to save it only one row is saved despite me adding multiple rows. Why does the inline formset only save one row & not all of them? CreateView (Views.py) def get_context_data(self, **kwargs): SubprogramBudgetFormSet = inlineformset_factory( Subprogram, SubBudget, fields=('subprogram', 'budgetYear', 'budgetCost'), can_delete=False, extra=1, ) data = super().get_context_data(**kwargs) if self.request.POST: data['subbudget'] = SubprogramBudgetFormSet(self.request.POST) else: data['subbudget'] = SubprogramBudgetFormSet() return data def form_valid(self, form): context = self.get_context_data() budget = context["subbudget"] if budget.is_valid(): self.object = form.save() budget.instance = self.object budget.save() return super().form_valid(form) Template.html <table class="table table-light"> {{ subbudget.management_form }} {% for form in subbudget.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th scope="col">{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tbody> <tr class="{% cycle row1 row2 %} budget_formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% … -
gunicorn + django + telegram + mqtt client
We use gunicorn with django and django-telegrambot. We also have a MQTT client in an own app. When some MQTT messages arrive we send Telegram messages and the other way around. The Problem is now that when we use gunicorn with multiple workers, we have multiple MQTT Clients, so that when a MQTT message arrives we will send multiple times the same Telegram message. When we use gunicorns preload with workers, we only have one MQTT client, but then all processes share the same Telegram TCP connection and we get wired SSL errors. As an alternative we could use only use on process and multiple threads, but then sometimes MQTT and Telegram messages gets not processed (idk why). Is there a way to get this running? Instead of using webhooks one could use botpolling, but django-telegrambot says: Polling mode by management command (an easy to way to run bot in local machine, not recommended in production!) -
How do I group a list of repeating elements?
I have a list from many-to-many relationship: INPUT: channels_list = [channelscategory_1: channel_1; channelscategory_1: channel_2; channelscategory_1: channel_3; channelscategory_2: channel_4; channelscategory_2: channel_5] How can you do it to get it? OUTPUT: channels_list = [channelscategory_1: channel_1, channel_2, channel_3; channelscategory_2: channel_4, channel_5] -
Django Factory Boy and Faker always return same value
I'm trying to generate dummy data and I have a selectable field among several options but the same sector is always generated models.py: SECTOR = (("1", _("Administración y gestión")), ("2", _("Agricultura y ganadería")), ("3", _("Industria alimentaria")), ("4", _("Grandes almacenes")), ("5", _("Comercio")), ("6", _("Construcción e industrias extractivas")), ("7", _("Actividades físico-deportivas"))) class Company(TimeEntity): ... sector = models.CharField(verbose_name=_("Sector"), max_length=20, choices=SECTOR, default=1) factories.py: SECTOR_FACTORY = list(map(lambda x: x[0], app_models.SECTOR)) class CompanyFactory(DjangoModelFactory): class Meta: model = app_models.Company sector = fake.random_choices(elements=SECTOR_FACTORY, length=1) -
I want to input multiple quantity as per my order item
admin panelstrong text if i select multiple item order quantity also increases according to my selected item -
Import csv encoding error in admin Django
admin.py @admin.register(Country) class CountryAdmin(ImportExportModelAdmin): pass It shows the following error: Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x81 in position 1233: character maps to The csv file contains arabic characters also. How to resolve it? -
Inner Join relationship filter in Django REST framework
I have models like these relationship I access these models via Django REST framework api class User(models.Model): name = models.CharField(max_length=128,unique=True) class Mix(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) pub_date = models.DateTimeField('date published',default=timezone.now) class AccessToken(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name="%(app_label)s_%(class)s", ) token = models.CharField(max_length=128,unique=True) and here is the viewset class MixViewSet(viewsets.ModelViewSet): queryset = Mix.objects.all() serializer_class = MixSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ["id","user"] // how can I Set?? token class MixSerializer(serializers.ModelSerializer): class Meta: model = Mix fields = ('id','pub_date','user') then I want to get the mixes by token with this procedure Select from AccessToken table and find one user select * from Mix where user = user(selected at 1) I guess it is something like inner join??? How can I make it in django filter??? -
Does models.ForeignKey accept instances of itself as default value?
I have a model that has a many-to-one relationship with itself: class Foo(models.Model): b = models.CharField(max_length=10) parent = models.ForeignKey('self', on_delete=models.CASCADE) This Foo.parent default value should be the same instance. I mean if the user didn't specify parent field, it needs to refer to the object that is being created. How can i implement this? -
I am new in Django. can you help me with this error
this is my index.html file.i am getting error at line 11.is this syntax is right? this is my output TemplateSyntaxError at / Invalid block tag on line 11: 'static'https://fonts.googleapis.com/css?family=Roboto:50,150,200,250,350''. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.5 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 11: 'static'https://fonts.googleapis.com/css?family=Roboto:50,150,200,250,350''. Did you forget to register or load this tag? Exception Location: C:\python39\lib\site-packages\django\template\base.py, line 531, in invalid_block_tag Python Executable: C:\python39\python.exe Python Version: 3.9.1 Python Path: ['F:\Home', 'C:\python39\python39.zip', 'C:\python39\DLLs', 'C:\python39\lib', 'C:\python39', 'C:\python39\lib\site-packages'] Server time: Wed, 28 Jul 2021 10:18:22 +0000 -
Django - Data is not submitted to my database, but no error
i'm making a system that tracks the owners of different phone companies, by letting a user add the owners' names. i'd like for the user to be able to add several owners at one time, and, hoping to avoid a lot of RegEx, Ajax and Node, i made 5 'Owner' tables in my database (the epitome of spaghetti code, i know). The last 4 Owner tables have null=True and blank=True, so that they are optional. When displaying this in the UI, i put each form field representation of the Owners in its own div and hide the last 4 divs. the user can choose to 'add another owner' by clicking a button, up to 4 extra owners. Rarely all five divs are filled out, so some of them always remain hidden by basic javascript. I then proceed to save all of them using .save() like any other model. when the user has filled out all the desired fields and hit "submit", everything runs fine, however... the data never gets sent to the database. i get no errors anywhere, which leads me to guesstimate that the form i'm passing in when i save the data isn't valid. I know it's the … -
My django project doesn't want to be deployed on heroku
I want to push my django project on heroku, I did all the steps from the tutorial, and I got an error ModuleNotFoundError: there is no module called 'ckeditor' I tried to solve this problem by doing all the steps in this stackoverflow post - ModuleNotFoundError: No module named 'ckeditor_uploader' in django but that didn't work for me. This is mine settings.py - > https://codeshare.io/Jb786X This is my Traceback (venvecosite) (base) cristian@FInch:~/Desktop/GreatEcology my project/ecosite/ecowebsite$ git push heroku master Enumerating objects: 1716, done. Counting objects: 100% (1716/1716), done. Delta compression using up to 4 threads Compressing objects: 100% (1685/1685), done. Writing objects: 100% (1716/1716), 46.84 MiB | 6.84 MiB/s, done. Total 1716 (delta 174), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Python has released a security update! Please consider upgrading to python-3.8.11 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.5 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing dependencies with Pipenv 2020.11.15 remote: Installing dependencies from Pipfile.lock (180c80)... … -
Architecture of web application with multiple microservices
I am currently planning a web application with multiple microservices and trying to think of a possible architecture. This is the stack I would like to use: Backend: Django Frontend: React DB: whatever fits Docker (or something else if it fits better) Messaging framework, such as RabbitMQ Task queue, such as Celery I would like to integrate different services with different languages, such as simple Bash scripts, larger Flask apps, projects on GitHub written in Python, Javascript, Bash, C++, etc. Given the nature of these projects, some are just simple API requests, others may require compilation. So I was thinking about dockerizing each service and putting it on a different server. I would then call each service via a button and arguments, with some sort of API, something like this: server-IP.service(args) which would then trigger the service. Some of these services won't be used often, so this would be along the lines of "hibernate in your Docker container until I call you". Some services might return more than a simple json response, for example there might be a screenshot tool that takes multiple screenshots. How would I get these back and display them in my front end? I'm thinking of … -
Django rest framework serializer fields using single API call
I have a route that uses a ViewSet router.register( r'mapping_details', GlobalMappingDetailsViewSet, base_name='global-store-product-mappings' ) This view set contains a get_queryset method and a serializer. class GlobalMappingDetailsViewSet(viewsets.ModelViewSet): serializer_class = GlobalMappingDetailsSerializer def get_queryset(self): return models.Mappings.objects.all().select_related('my_column') class GlobalMappingDetailsSerializer(serializers.ModelSerializer): class Meta: model = models.Mappings fields = ('column1', 'column2') I want to add 2 fields that are populated using a single API call in the response of the request. I could use serializers.Field but will have to make separate calls for both the fields. Does someone know the right way to handle this use case? -
How can a field in the Django admin panel be made writable for a model only when it is being created, and it'll be read only at other times?
I am working on a project similar to a stock market. In this project I have a model called Share which is as follows: class Stock(models.Model): _title = models.CharField(max_length=50) _description = models.TextField() _total_subs = models.IntegerField() _sold_out_subs = models.IntegerField() _created_at = models.DateTimeField(auto_now_add=True) _updated_at = models.DateTimeField(auto_now=True) _status = models.BooleanField() Access to create new records for this model is to be supposed only through the Django admin panel, so in the admin.py file in my app I wrote a class to manage it called StockAdmin as follows: class StockAdmin(admin.ModelAdmin): list_display = [] readonly_fields = ['_sold_out_subs'] class Meta: model = Stock How can I make a _total_subs so that it can be writable when it being create and then it should be in read-only fields? -
Best way to update a Django-model-instance/database-table from another server without Django
Say I have two servers prod and API. On prod I have a Django application running and say I have the following model class MyModel(model.Models): name = models.Charfield() age = models.IntField() birthdate = models.DateTimeField() has_birthday = models.BooleanField() thus the model in my database would look like name | age | birthdate | has_birthday -----+-------+-------------+------------- john 30 1990-01-30 0 doe 20 1987-05-01 0 .... Each day on API I run a daily script which checks, if someone has birthday - if they do, set has_birthday=1 (note, everything above is just an example for illustration purposes). Since API just is a server for daily jobs, I have not deployed a Django-application on that server, thus I wonder, what is the usual/best way to update the MyModel table with the following logic? My first intuition is just to make a plain and simple update- SQL statement e.g from utils import get_con_to_db con = get_con_to_db() query = <SQL update query> con.execute(query) but that is rather error prone in case I decide to change my model in some way. Is there a better/more secure way of doing so, without having to create a Django application on API thus maintaining two Django applications? -
Django REST Framework: NOT NULL constraint failed
I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem. I have the following setup in Django REST Framework: models.py: class Variant(models.Model): variant = models.CharField(max_length=30) class Question(models.Model): question = models.CharField(max_length=250) multiple = models.BooleanField(default=False) variants = models.ForeignKey(Variant, db_index=True, on_delete=models.CASCADE) answer = models.CharField(max_length=30) class Quiz(models.Model): name = models.CharField(max_length=250) description = models.TextField() questions = models.ForeignKey(Question, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now=True, db_index=True) serializers.py: class VariantSerializer(serializers.ModelSerializer): class Meta: model = Variant fields = ['id', 'variant'] class QuestionSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True, read_only=True) class Meta: model = Question fields = ['id', 'question', 'multiple', 'variants', 'answer'] def create(self, validated_data): variants_data = validated_data.pop('variants') question = Question.objects.create(**validated_data) for variant in variants_data: Variant.objects.create(question=question, **variant) return question class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['id', 'name', 'description', 'date_created', 'questions'] def create(self, validated_data): questions_data = validated_data.pop('questions') quiz = Quiz.objects.create(**validated_data) for question in questions_data: Question.objects.create(quiz=quiz, **question) return quiz When I try to post some data assigned using a JSON file like this one: { "name": "quiz", "description": "quiz quiz quiz", "questions": [ { "question": "What is the weather today?", "multiple": false, "variants": [ { "variant": "cloudy" }, { "variant": "cold" } ], "answer": "cloudy" }, { "question": "What is the weather … -
Node as opposed to Django for running big python scripts
I am building an app that requires running a python script that implies a significant wait time. I am having a hard time deciding whether I should stick with Django or should dive into Nodejs, due to the fact that I find plugging in my front end (React) a pain point, and because I would like to work with Apollo Server. What is your opinion? Is Nodejs not suited for running such python scripts? Thank you! -
See django template in pytest failure output
During rendering a Django template my pytest based test fails. I would like to see two things: The name of the template, and a snippet of the part which caused this exception. Maybe I am blind, but I don't see it: tests/magic/test_render_search.py:8 (test_render_foo_search_results) @pytest.mark.django_db def test_render_foo_search_results(): portal = PortalFactory.create() foo = fooFactory.create(name='dummy') foo_index.sync_foo(foo.id) foo_index.commit() > html = render_foo_search_results('name=dummy', portal=portal) test_render_search.py:16: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../../magic/templatetags/render_search.py:17: in render_foo_search_results return get_foo_search_results_context( ../../magic/render_util.py:62: in get_foo_search_results_context html_data = cached_foo_render(search_results, ../../magic/render_util.py:41: in cached_foo_render rendered = render_to_string(template, { ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/loader.py:62: in render_to_string return template.render(context, request) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/backends/django.py:61: in render return self.template.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:171: in render return self._render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/test/utils.py:96: in instrumented_test_render return self.nodelist.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:937: in render bit = node.render_annotated(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:904: in render_annotated return self.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/defaulttags.py:443: in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/urls/base.py:90: in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How to display data from a model method
Good evening community I am new to programming and I have been working on a Django project to enhance my skills. I would like to display data from a method model in my templates. Here is the project's model, class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name #Company methods def net_income(self): return self.revenue - self.expenses Here is the Views file, def tools(request): submitted = False form = CompanyForm() if request.method == 'POST': print(request.POST) form = CompanyForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/simple_investing/tools?submitted=True') else: form = CompanyForm if 'submitted' in request.GET: submitted = True context = {'form': form, 'submitted': submitted} return render(request, 'simple_investing/tools.htm', context) Here is the forms file, class CompanyForm(ModelForm): class Meta: model = Company fields = ('company_name', 'outstanding_shares', 'share_price', 'revenue', 'expenses', 'total_assets','total_liabilities', 'current_assets','current_liabilities', 'operating_cashflows', 'capex') widgets = { 'company_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'Company name'}), 'outstanding_shares': forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Shares outstanding'}), 'share_price' :forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Share price'}), 'revenue' :forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Revenue'}), …