Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'
I'm using django and virtual environment "virtualenv", activate it, try to run the server in the project folder like this: python manage.py runserver, but I get this error: from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'. what could be happening? if someone can help, thank you in advance -
In django whenever I try to run the server, I want to see the login page first, but I am seeing the index page?
I am attaching my code in views and urls.py. Whenever the server runs, I want to see the login page first, but I am seeing an error that this page is not working. def loginPage(request): if request.user.is_authenticated: return redirect('/') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'accounts/login.html', context) urlpatterns = [ path('', views.loginPage, name="login"), path('index/',views.index,name="index"), -
DJANGO custom user model: create_superuser() missing 1 required positional argument: 'username'
I have the following User model which uses email as USERNAME_FIELD and leave the actual username unused. All authentication features work fine, but I just realized I cannot create superuser with manage.py because of the error: create_superuser() missing 1 required positional argument: 'username' Can anyone help me debug this error? users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown") profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] class Meta: swappable = "AUTH_USER_MODEL" users/services.py def user_create(email, password=None, **extra_fields) -> User: extra_fields = {"is_staff": False, "is_superuser": False, **extra_fields} user = User(email=email, **extra_fields) if password: user.set_password(password) else: user.set_unusable_password() user.full_clean() user.save() return user def user_create_superuser(email, password=None, **extra_fields) -> User: extra_fields = {**extra_fields, "is_staff": True, "is_superuser": True} user = user_create(email=email, password=password, **extra_fields) return user @transaction.atomic def user_get_or_create( *, email: str, first_name: str, last_name: str, profile_pic: str ) -> Tuple[User, bool]: user = User.objects.filter(email=email).first() if user: return user, False return ( user_create( email=email, first_name=first_name, last_name=last_name, profile_pic=profile_pic, ), True, ) Full error log ❯ docker-compose run --rm web ./manage.py createsuperuser ─╯ Email: example@email.com Password: Password (again): Traceback (most recent call last): File "./manage.py", line … -
for loop in django template returning blank list items
I'm looping through the field of joined for my Group model and returning the list of joined members in my GroupDetail template: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) Each member in the for loop relates to a User (or username) that has joined the Group: <ul> {% for member in joined_members %} <li>{{ member }}<li> {% endfor %} </ul> There are four members in the Group, and all members are being returned, however four empty list items are also being returned as such (via chrome dev tools): <ul style="display: block;"> <li>joe</li> <li></li> <li>johnny</li> <li></li> <li>ralph</li> <li>/li> <li>mike</li> <li></li> </ul> There are only four members (Users) joined to this particular group, so I don't understand what's happening. I assume the issue is from how I passed the data into the template from my view: class GroupDetail(DetailView): model = Group template_name = 'group_details.html' def get_context_data(self, *args, **kwargs): group = get_object_or_404(Group, id=self.kwargs['pk']) joined_members = group.joined.all() context = super(GroupDetail, self).get_context_data() context["joined_members"] = joined_members return context There are no actual errors, just these four empty list items. Is the issue with my for loop? Or is it with how I'm passing my context? -
PrimaryKeyRelatedField does not serialize the object
I have a game model like this: class Game(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) slug = models.SlugField() ... And a serializer like this: class GameSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = Game fields = ( "id", "name", "description", "owner" ) When I make a request I get this: description: "TestDescription" name: "TestName" owner: 1 I was expecting owner to be a dictionary with fields like an email, a username and so forth. What is wrrong? -
Fixing load static Django Templates
I've been searching for an answer to this and I feel like I'm doing everything right and have taken on suggestions in multiple posts but this is still stumping me. I'm trying to load static in my django template but for some reason I keep getting and unresolved template error and it won't load in my browser. project/settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_FILES_FIRS = [os.path.join(BASE_DIR, 'static')] I've set up the static root. Then in my base.html I've got: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" type="image/png" sizes="16x16" href="{% static "favicon/favicon.png" %}"> <title>Title</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> {% include "navbar.html" %} <img src="{% static "favicon/favicon.png" %}" alt="img"/> <main class="container mx-auto p-8"> {% block main %}{% endblock %} </main> </body> </html> I feel like I'm missing something because that directory should exist but the django template isn't finding it! I've tried using {% load staticfiles %} instead but that errors saying it can't find staticfiles. Any help would be appreciated! Thanks, Mitchell -
django ajax send form and csv
I am saving a form with ajax , I use the following code and it saves my form,but I have an input that captures a csv file that is not saved in a field of the form but I need to save the records of that csv in a different table. I don't know how to send both the form and the csv with ajax and capture them in the post method of the view , So far I send the data of the form form.py class AsignacionGeneralForm(forms.ModelForm): # idproyecto = forms.ModelChoiceField(queryset=None) def __init__(self, *args, **kwargs): super(AsignacionGeneralForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) self.fields['fecha_descarga'].widget.attrs.update({ 'class': 'form-control', 'data-inputmask-alias':'datetime', 'data-inputmask-inputformat':'mm/dd/yyyy', 'data-mask inputmode':'numeric' }) class Meta: model=Recaudo fields=['fecha_descarga','observacion'] html <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="action" value="{{ action }}"> {{form}} <div class="form-group"> <label>Cargar Archivo:</label> <div class="input-group"> <input type="file" class="form-control" name='file' accept=".csv" id="inputGroupFile" aria-describedby="inputGroupFileAddon04" aria-label="Upload" required> <button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon" onclick="resetFile()">Borrar</button> </div> </div> <div class="form-group"> <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="cancelar()">Cancelar</button> <button type="submit" class="btn btn-success float-right"> <i class="fas fa-save"></i> Guardar </button> </div> </form> ajax $('form').on('submit',function(e){ e.preventDefault(); var parameters=$(this).serializeArray(); console.log(parameters); var formData = new FormData(); formData.append('file', $('#inputGroupFile')[0].files[0]); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); console.log(formData); $.ajax({ url: '{% url 'gestionAsignacion:asignacion_general' … -
django custom serializer field not working
I am trying to add an additional field in the serializer but at the moment of adding it I get the following error error view During handling of the above exception ('MovieSerializer' object has no attribute 'len_name') I have seen many posts and all of them are working, what could it be? this is my code Model: from django.db import models class Movie(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField() active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=None, null=True) def __str__(self): return self.title serializer: from rest_framework import serializers from watchlist_app.models import Movie from watchlist_app.api.validations import MovieValidations class MovieSerializer(serializers.ModelSerializer): len_name = serializers.SerializerMethodField(method_name='len_name') class Meta: model = Movie fields = "__all__" read_only_fields = ['id', 'len_name', 'created_at'] required_fields = ['title', 'description'] @staticmethod def create(self, validated_data): return Movie.objects.create(**validated_data) @staticmethod def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.active = validated_data.get('active', instance.active) instance.save() return instance @staticmethod def get_len_name(self, obj): return len(obj.title) validators = [MovieValidations.validate_title, MovieValidations.validate_description, MovieValidations.validate_equals] everything works fine until I add the serializerMethodField -
Django Templates Syntax Error For If (Could not parse the remainder)
Why does this not work in Django? {% for img in image_list %} {% if img != image_list[-1] %} <img src="{% get_media_prefix %}{{ img.image }}" class="img-fluid rounded" alt="Recipe Image Secondary"> <br> {% endif %} {% endfor %} Simple Python (works): for img in image_list: if img != (image_list[-1]): print(img) {% if img != image_list[-1] %} throws a TemplateSyntaxError Could not parse the remainder: '[-1]' from 'image_list[-1]' -
How to annotate the number of times a related field appears for the parent [Django]
I've got 2 classes: class Agent(models.Model): pass class Client(models.Model): agent = models.ForeignKey( "agents.Agent", on_delete=models.SET_NULL, ) connected = models.BooleanField( default=False, ) I know that if connected was an integer, I could use Sum like this: Agent.objects.all().annotate( Sum("client__connected"), ) But how would I get the count based on the value of the related field? I've also tried: Agent.objects.all().annotate( connected=Count( "connected", filter=Q(client__connected=True), ) ) But this just gives me the error: An exception of type FieldError. Arguments: ("Cannot resolve keyword 'connected' into field. -
Making user.username (or any field) anonymous for certain users
I'm trying to make certain PII related attributes such as user.username or profile_picture anonymous for certain users. I have a field in my database called cant_see_pii that tracks whether a user can see other users sensitive data. class UserAttributes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'user_attribute') cant_see_pii = models.BooleanField(null=True, blank=True, default = False) profile_picture = models.ImageField("Profile Picture", default='images/default.svg', upload_to='images/', null=True, blank=True) If this field is true I want to obfuscate all other users pii related data, without hiding their own. Example: When a template has <H1>{{other_user.username}}</H1>, I want this to return <H1>Anonymous User</H1> or even better <H1>Anonymous User 12345</H1> I don't want to have to do this for every instance I use this in every template so something like this won't work: <H1>{% if userattribute.cant_see_pii == True %}Anonymous User{%else%}{{other_user.username}}{%endif%}</H1> -
Edit request in Django Rest Framework Testing
Im using django rest API for my requests and im trying to run some tests on them . GET/POST works correctly but when im trying to post something and then change it it just adds an extra instance to the db instead of editing the already existing one . edit works when placing the pk of the object in the url but instead of changing the already assigned ID it creates a new one . post request self.client.force_authenticate(self.user) response = self.client.post(reverse(xx:xx), { "user": '1', "friendly_name": "xx", "soil_type": "xx", "cultivation": "xx" },format='json') edit request self.client.force_authenticate(self.user) response = self.client.put( reverse('xx:xxx', kwargs={'field_id':1}), { "user": '1', "friendly_name": "XX", "soil_type": "XX", "cultivation": "XX" } ) -
please, how do I get over "int() argument must be a string, a byte-like object or a real number, not a 'NoneType'" error in my code?
<h1>This is food box page</h1><br><br> `<image src= "{% static 'food_app/image1.jpeg' %}">` <h2>{{food_box1.0}}</h2> <h3>{{food_box1.1}}</h3> <button type= "button"><strong>EAT ME!</strong></button><br><br> <form action="{% url 'food_app:price' %}" method="POST"> {% csrf_token %} <label for="price in packs"><strong>Price in packs</strong></label> `<input type="text" id="price in packs" name="price1" placeholder="Enter number between 20 and enter code h 500">` <h1>{{new_price}}</h1> <button type= "button"><strong>EAT ME!</strong></button> </form> <br> <br> <image src= "{% static 'food_app/image2.jpeg' %}"> <h2>{{food_box2.0}}</h2> <h3>{{food_box2.1}}</h3> <button type= "button"><strong>EAT ME!</strong></button><br><br> <form action="{% url 'food_app:price' %}" method="POST"> {% csrf_token %} <label for="price in packs"><strong>Price in packs</strong></label> `<input type="text" id="price in packs" name="price2" placeholder="Enter number between 20 and 500">` <h1>{{new_price2}}</h1> <button type= "button"><strong>EAT ME!</strong></button> </form> Python if request.method == "POST": price_pack_box = int(request.GET.get("price1")) if price_pack_box >= 20 and price_pack_box <= 500: food = Food.objects.get(pk=40) food_price = food.food_price total_price1 = price_pack_box*food_price elif price_pack_box < 20: messages.info(request, "number input too small!") return redirect('food_app:foodbox') elif price_pack_box > 500: messages.info(request, "number input too large!") return redirect('food_app:foodbox') print(total_price1) `elif request.method == "POST":` `price_pack_box = int(request.POST.get("price2"))` `if price_pack_box >= 20 and price_pack_box <= 500:` `food = Food.objects.get(pk=41)` `food_price = food.food_price` total_price2 = price_pack_box*food_price elif price_pack_box < 20: messages.info(request, "number input too small!") return redirect('food_app:foodbox') elif price_pack_box > 500: messages.info(request, "number input too large!") return redirect('food_app:foodbox') print(total_price2) my_dict = {'new_price':total_price1,'new_price2':total_price2,'new_price3':total_price3} return render(request, … -
django | model.objects.filter(user = request.user) not returning any data
I've been trying to render out user specific content, but when I use the line 'Job.objects.filter(user = request.user)' I don't get anything rendered in the form. I don't think that the problem is the template because when I use the line Job.objects.all() all instances are rendered out with no problem. What I'm trying to do is render out the instances that are 'posted' by a user. views.py @login_required(login_url='login') def manage_jobs(request): if request.user.is_employee: return redirect('home') else: form = JobForm(request.POST) jobs = Job.objects.filter(user=request.user) if form.is_valid(): form.save() context = {"form":form, "jobs":jobs} return render(request, 'employer/manage-jobs.html', context) class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employee = models.BooleanField(default=True, verbose_name='Are you using FilmLink as an employee?') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_employee'] objects = MyAccountManager() class Meta: permissions = [ ("post_jobs", "Can post jobs"), ] def __str__(self): return self.name def has_perm(self, perm, obj=None): return True def has_perms(self, perm): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") … -
can you please check if i done "register" function correctly in django
i am new in django , can you please check if I done "register" function in the correct way , without applying django forms because i find difficult to do it , so i choose this way my function: def register(request): if request.method == 'POST': db = Customers() db.fname = request.POST['fname'] db.lname = request.POST['lname'] db.email = request.POST['email'] db.password = make_password(request.POST['password']) repassword = request.POST['repassword'] db.username = request.POST['username'] db.save() if check_password(repassword, db.password): if User.objects.filter(username=db.username).exists(): messages.info(request, 'Username is already taken') return redirect("register") elif User.objects.filter(email=db.email).exists(): messages.info(request, 'Email is already taken') return redirect("register") else: user = User.objects.create_user( username=db.username, password=db.password, email=db.email, first_name=db.fname, last_name=db.lname) user.save() return redirect("login_user") else: messages.info(request, 'Both passwords are not matching') return redirect(register) else: return render(request, "compte/register.html") -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "package_code_key"
I have written a test case for create api in Django but I am getting the above error. I see in database it creates some objects and says that there is a duplicate key value in the error. My model is: class Example(models.Model): package = models.ForeignKey( Destination, related_name="packages", on_delete=models.CASCADE ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_packages", ) tour = models.ForeignKey( Tours, on_delete=models.CASCADE, null=True, related_name="tour_packages", ) My test case is as follows: import factory # Define your factories class PackageFactory(factory.django.DjangoModelFactory): class Meta: model = 'example.Package' class UserFactory(factory.django.DjangoModelFactory): class Meta: model = 'example.User' class TourFactory(factory.django.DjangoModelFactory): class Meta: model = 'example.Tour' class ExampleFactory(factory.django.DjangoModelFactory): package = factory.SubFactory(PackageFactory) user = factory.SubFactory(UserFactory) tour = factory.TourFactory(TourFactory) class Meta: model = 'example.Example' # And now, create a new example instance together with all related models. example = ExampleFactory() I cleared the database and start running the test but I get the same error. How to solve this?? -
How do I update settings.py using views and forms in Django? [duplicate]
I want to set my variables in settings.py through the front-end using Views and Forms. Let's say, I have following in settings.py: # My personal settings NO_OF_DAYS = 0 and I have following in my forms.py: def class SettingsForm(froms.Form): no_of_days = forms.CharField(max_length=254) Now, I want mixture of views and forms, something like below in my views.py: from django.conf import settings from .forms import SettingsForm class UpdateSettings(View): def get(self, request): settings_form = SettingsForm() return render(request, "settings-template.html", "form": settings_form) def post(self, request): settings_form = SettingsForm(request.POST) if settings_form.is_valid(): form_data = settings_form.cleaned_data settings.NO_OF_DAYS = int(form_data["no_of_days"]) # I WANT SOMETHING LIKE THIS, BUT I WANT SETTINGS.PY TO STORE THE VALUE FOREVER, NOT JUST IN THIS VIEW return redirect("/success/") How do I accomplish it? -
How to delete data after fetch in a same action in Django?
I have a table in DB named Plan. see code in models.py: class Plan(models.Model): id = models.AutoField(primary_key=True) Comments = models.CharField(max_length=255) def __str__(self): return self.Comments I want to fetch data(comments) from DB and after that data will be deleted. That means one data will be fetched once. And this data will be shown in the Django template. I tried, see views.py def Data(request): data = Plan.objects.filter(id=6) # latest_id = Model.objects.all().values_list('id', flat=True).order_by('-id').first() # Plan.objects.all()[:1].delete() context = {'data':data} dataD = Plan.objects.filter(id=6) dataD.delete() return render(request,'data.html',context) this code is deleting data from DB but not showing in the template. How can i do this? -
How do I get the id of the model item that is clicked on?
My main page on my website shows all the possible listings and when one of them is clicked on, the user is meant to be taken to a page that shows the listing's information. (This page is not finished yet.) This means that I need to be able to know which listing has been clicked on so I need a way to get the id of the listing. I've tried to do this by taking in a id parameter/argument that should be used inside the function to find out which listing this is. I want the url to be http://127.0.0.1:8000/[id]/[name of listing] where [id] and [name of lsiting] and the actual ids and names of the listings. id should be a number and name_of_listing should be a string. (The id is in Listing.id and the name of the listing is in Listing.name - Listing is the name of the model and the id and name are fields.) How do I get the id of a listing through a link? index.html: (this just displays all the listings - I've used comments to show where the links are) <main> <div class="listings-container"> {% for i in listings %} <div class="listing"> {% if i.photo_present … -
How do I get created objects as a query set from django bulk_create?
I am making use of bulk_create on a Django model. How can i get the values of the created object so i can proceed to make use of it, without querying the db again. -
ValueError: The 'image' attribute has no file associated with it Django
I'm working on a blog where i can allow other user upload/post content Now I'm working on the frontend user post where user can publish their post all fields are working except the image field after inputting the necessary detail it will show me this ''ValueError: The 'image' attribute has no file associated with it.'' Please how can i fix this my code below views.py if request.method == 'POST': form = ArticleForm(request.POST, request.FILES) if form.is_valid(): form.save() else: print(form.errors) # else: # form = ArticleForm() return render(request, 'CreatePost.html', {'form': form}) forms.py from django import forms from . models import Article class ArticleForm(forms.ModelForm): # image = forms.ImageField(**kwargs, upload_to='featured_image/%Y/%m/%d/') #this class Meta: model = Article fields = [ 'title', 'image', 'slug', 'author', 'body', 'publish', 'status' ] models.py # models from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') # post model class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) image = models.ImageField(upload_to='featured_image/%Y/%m/%d/') #this slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects … -
How to convert users' casual time input to an accepted time format in python DateTimeField?
In my Django application, there is a field that accepts User/ Admin's input time. The expect outcomes would be: Input 7 then the system will convert it to 7:00 Input 715, it would be recognized at 7:15. The same 2011 -->20:11, 015-->0015 How should I do it? Any comments? P.S. I don't have code because I would like to know the apprach first. Thank you! -
How to Join and Aggregate in Django REST Framework
I'm quite new to Django and I'm currently stuck on the following problem. I have models as: class City(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) area = models.FloatField() class NoiseData(models.Model): location = models.CharField(max_length=100) city_id = models.ForeignKey(City, on_delete=models.CASCADE) noise_type = models.CharField(max_length=30) I would like to have data aggregations by city in my api in form like: [ { "id": 1, "name": "New York", "count": 198, # this would be count of NoiseData, "count_area_normalized": 0.198 # this would be count of NoiseData / area of City, "noise_type_metadata": "{\"Loud Music/Party\": 167, \"Banging/Pounding\": 21, \"Loud Talking\": 9, \"Loud Television\": 1}", # ideally want a JSON in which I can show count for each noise_type in the city } Thanks a lot in advance! -
Is it possible to edit HTML for Django FileResponse via template or view?
I've an application that has a video that is being served as a fileResponse. It seems that the video is displayed in an html. I would however like to customize the tag. Does anyone know how I can add an HTML-template for a FileResponse? Or add attributes for the video-tag via the view ? -
How to run a model's function with DTL?
I am fairly new to django and I am trying the following: I am making an ordering web app for a nearby business. I am trying to add all the calories in a combo. I have a model "Consumable", this represent the different food and drinks there are. Here is the code for the "Consumable" Model: class Consumable(models.Model): name = models.CharField(max_length=80, unique=True) category = models.ForeignKey(FoodCategory, null=True, on_delete=models.SET_NULL) price= models.FloatField(default=0.00) calories = models.IntegerField(blank=False) image = models.ImageField(upload_to="images/Food/") description = RichTextField(blank=True, max_length=500) restaurant = models.ForeignKey(Place, on_delete=models.CASCADE) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name Then, I have a model called "Meal" which has the following code: class Meal(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/photos/meals') consumables = models.ManyToManyField(Consumable, related_name="consumable") restaurant = models.ForeignKey(Place, on_delete=models.CASCADE) price = models.FloatField() def add_cals(meal_consumables): total_calories = 0 for x in meal_consumables.values(): global total_calories += float(x.calories) return total_calories I am trying to call this model's function, add_cals from my HTML file using the DTL (Django Template Language). For example, if you have a model stored with the variable x in your view, and it is in the view's context dictionary, you could simply call the model by using <p>{{x}}</p>, for example. And if the model has a variable x1, …