Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Replication lag
Prerequisites: class Task(models.Model): class TaskStatus(models.TextChoices): HIDDEN = 'hidden', _('hidden') NEW = 'new', _('new') IN_PROGRESS = 'in_progress', _('in progress') DONE = 'done', _('done') FAILED = 'failed', _('failed') PLANNED = 'planned', _('planned') REVOKED = 'revoked', _('revoked') title = models.CharField(max_length=500) performer = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(choices=TaskStatus.choices, default=TaskStatus.HIDDEN, max_length=25) class TaskTransition(models.Model): task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, related_name='transitions') actor = models.ForeignKey(User, on_delete=models.RESTRICT, related_name='transitions') old_status = models.CharField(choices=TaskStatus.choices, max_length=25) new_status = models.CharField(choices=TaskStatus.choices, max_length=25) class TaskView(ModelViewSet): queryset = Task.objects.all() serializer = TaskSerializer class CreateTaskTransitionView(mixins.RetrieveModelMixin, generics.CreateAPIView): serializer_class = CreateTaskTransitionSerializer class CreateTaskTransitionSerializer(serializers.ModelSerializer): task = serializers.HiddenField(default=HiddenTaskField()) actor = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = TaskTransition fields = '__all__' def validate(self, attrs): # allowed status transitions: # hidden > new # new > in_progress, failed # in_progress > done, failed return attrs def save(self, **kwargs): task = self.validated_data['task'] new_status = self.validated_data['new_status'] TaskTransition.objects.create( task=task, new_status=new_status, old_status=task.status, actor=self.validated_data['actor'] ) task.status = new_status task.save() return {} We use two databases. First default for writing and replica for reading. Because of validation as you can see only one unique task transition can be done. But sometimes it happens that there can be multiple same transitions. For example 5 transitions in_progress > done. And when retrieve task instance task is with not actual status. It's obvious that this … -
what on_delete option to use in django app?
I have an Article model that allows admins to publish articles. Each article is assigned to a user that is creating this article. I want to make sure that all articles will stay untouched even if I delete the author of this particular article. I chose on_delete=models.DO_NOTHING to be sure that nothing except user account will be removed but I am not quite sure that is the most effective way. class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING) title = models.CharField('Title', max_length=70, help_text='max 70 characters') body = models.TextField('Description') Question Should I use another option to use or DO_NOTHING is good enough. Obviously the most important to me is that author's name will be visible in the article after deletion and the article itself cannot be removed. -
Django admin prepopulated fields and fieldsets
I am using Django 3.2 I have the following model: class Foo(models.Model): title = models.CharField() slug = models.SlugField() # remaining fields listed below In Admin manager, I have the model: class FooAdmin(admin.ModelAdmin): fieldsets = [ ('General', { 'fields': [ 'title', 'description', 'information', 'cover_photo', 'gallery', ] }), ('Details', { 'fields' : [ 'is_cancelled', 'start', 'finish', 'video_url', ] }), ] prepopulated_fields = {'slug': ('title',), } admin.site.register(Foo, FooAdmin) When I attempt to create a new Foo in the admin manager, I get the error: KeyError: "Key 'slug' not found in 'FooForm'. Choices are: cover_photo, description, finish, gallery, information, is_cancelled, start, title, video_url." When I add the slug field to the list of fieldsets, it works, but then the slug field is shown on the form (which I don't want). I know that I can solve this by overriding Foo.save(), but I want the admin manager to handle this for me. So, how do I use fieldsets with prepopulated fields that are not supposed to appear on the form? -
pop up modal appears again when clicked on back button
i have created a confirmation pop up modal using javascript in django's html page, my html template is generating delete links using for loop, so my my logic is i have used target the clicked html element using window event and then i fetch the value of href, store it in varibale, and then apply that value to the yes button of pop modal, and also set the href value of delete link to '#', so it should not work. now my problem is the modal is working properly, but aafter finishing the task, when clicked on browser back button, again the modal is appearing.enter image description here -
django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.']
I am trying to upload data in the django ORM by a script for which I have written this for index, row in df.iterrows(): allocated = row['is_allocated'] delivery_required_on = row['delivery_required_on'] linked = row['linked'] raised_by = row['raised_by'] raised_for = Company.objects.get(pk=row['raised_for']) ### double check rejected = row['is_rejected'] reason = row['reason'] remarks = row['remarks'] created = row['created_at'] owner = User.objects.get(pk=row['New owner']) j = literal_eval(row['flows']) flows = [] mobj = MaterialRequest.objects.create(owner=owner, is_allocated=allocated, delivery_required_on=delivery_required_on, linked=linked, raised_by=raised_by, raised_for=raised_for, is_rejected=rejected, reason=reason, remarks=remarks, created=created) It is running fine when the data is something like the following: But as soon as is_allocated reaches False it shows the following error: django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.'] I am unable to find something related to this -
python calculate rating by percent of complete
Let say, when student completed the course then he will get the percentage of his completion. Then we implement the max ratings is 5 stars which following these rules: 0%-4% => 0 star 5%-19% => 1 star 20%-39% => 2 stars 40%-59% => 3 stars 60%-79% => 4 stars 80%-100% => 5 stars So, based on student score: 0% percent complete will get 0 rating star. 10% percent complete will get 1 rating star. Also, another conditionals it can be 30% percent complete will get 2.5 rating stars. NOTE: The max 5 stars is dynamic value, it can be 10 stars. how we can accomplish this? -
Why is Heroku installing SQlite 3 even though I don't have it in requirements.txt
I am deploying a Django 3.2 website (with PG db backend) on Heroku, when I do a git push, this is a snippet of the console output: Enumerating objects: 18, done. Counting objects: 100% (18/18), done. Delta compression using up to 8 threads Compressing objects: 100% (11/11), done. Writing objects: 100% (11/11), 1.04 KiB | 265.00 KiB/s, done. Total 11 (delta 9), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python 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.10.4 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.10.3 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip Why is Heroku installing SQlite3 - even though I don't have it in my requirements.txt? Heroku seems to install SQLite3 first, before checking what the requirements are - Why? -
Number of elements in database array using django
I am pretty new in django and I am trying to dispaly using django number of images that appears in my database on my datatable field called number of images Explanation : I have a document that contains several elements. One of these elements is an array called Feedback that contains an array called images with urls of photos. What I need is that I get number of all urls that appears in images array but not only in one but all the document in all Feedback array not only one array image. I have tried this line of code in my django template but it doesn't display the right number of images. Code: <td>{{ product.Feedback.2 | length }}</td> Here is a screenshot of my Mongodb database to clarify my expalanation : Any help would be great !Thank you. -
Reset password email from django doesn't appear in my mailbox
Scenario: In my django application, admin should create users using 'username' and 'email', 'password' will be generated auto .Welcome email will be sent to users with redirect link to reset password. Issue: after entering email for reset password the app should send email with link to confirm reset password. THE PROBLEM is the email it never show in user "inbox" but i can find it in app "outbox mails" How can i make it appear in user mailbox? Any Help or idea? I'm using: -Python3 -Django4 -enable two factor authentication(2FA) for Google account Settings.py: #SMTP Config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = "webapp@app.com" DEFAULT_FROM_EMAIL = "MyApp <no-reply@app.com>" EMAIL_HOST_PASSWORD = "******" APP/URLS: urlpatterns = [ path('',views.login_user, name ='login'), #login fonction path path ('user_logout',views.user_logout, name = 'logout'), #logout function path path('dashboard/', views.dashboard, name='dashboard'),# dashoard view path path ('daily',views.DailyView, name = 'dailydashboard'),#daily view depath path ('monthly',views.MonthlyView, name = 'Monthlydashboard'),#monthly view path path ('yearly',views.YearlyView, name = 'Yearlydashboard'), #yearly view path path("reset_password/", auth_views.PasswordResetView.as_view(template_name="password/password_reset.html"), name="reset_password"), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name="password/password_reset_done.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), ] -
Foreign Key field cant not be save in Django
I have this two model that is related by a foreign key. I take response from a webhook regarding a transaction and save into the model. What i am trying to do is save the the foreign key element into the Transaction History but i keep getting error when data is about to be saved that Cannot assign "'1'": "TransactionHistory.level" must be a "Level" instance. model class Level(models.Model): name = models.CharField(max_length=200, null=True, blank=True,) fees_amount = models.PositiveSmallIntegerField() class TransactionHistory(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE, null=True, blank=True, ) student_full_name = models.CharField(max_length=120) transaction_id = models.CharField(max_length=120) student_id_number = models.CharField(max_length=120) amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) status = models.CharField(max_length=120, null=True, blank=True) email = models.EmailField(max_length=120, null=True, blank=True) phone = models.CharField(max_length=120, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) View.py @csrf_exempt def webhook(request): # Verify if request came from Paystack if request.method == 'POST': response_data = json.loads(request.body) if response_data["event"] == "charge.success": transaction_id = (response_data["data"]["reference"]) if not TransactionHistory.objects.filter(transaction_id=transaction_id).exists(): status = (response_data["data"]["status"]) amountraw = (response_data["data"]["amount"]) student_full_name = (response_data["data"]["metadata"]["custom_fields"][0]["student_full_name"]) level = (response_data["data"]["metadata"]["custom_fields"][0]["level"]) student_id_number = (response_data["data"]["metadata"]["custom_fields"][0["student_id_number"]) email = (response_data["data"]["metadata"]["custom_fields"][0]["email"]) phone = (response_data["data"]["metadata"]["custom_fields"][0]["phone"]) amount = (str(int(amountraw) / 100)) if status == 'success': transaction = TransactionHistory( level=level, student_full_name=student_full_name, amount=amount, transaction_id=transaction_id, status=status, student_id_number=student_id_number, email=email, phone=phone, ) transaction.save() return HttpResponse(status=200) This is the error i get: raise ValueError( ValueError: Cannot … -
Django Taggit - insert hyperlink if the word in body matches with tag
I am using django-taggit to handle tags in my app. I am also using django-ckeditor in my body field. I'd like to implement a function or a decorator or anything that will look at the text in the body field, find automatically tags in the text, and insert hyperlink like this one: http://127.0.0.1:8000/tag/test1/. I am not sure where should I start and how to implement such a feature. I know that CKEditor offers such a feature and it can be found here but I believe that I need a premium version of CKEditor5, right? If it is free is there any other way to handle CKEditor configuration than React, Angular, and Vue? Can I use Boostrap to for setting up the link feature? -
Connect via a secure websocket WSS from Django project to Redis/Daphne
I am trying to connect a secure websocket WSS with Redis/Daphne from my Django-Project: new WebSocket('wss://myproject.com:9002/ws/myChat/') But it is not possible to connect. In the Browser-Console I always get the following error: myCode.js:36 WebSocket connection to 'wss://myproject.com:9002/ws/myChat/' failed This is the only error I see, e.g. Nginx (sudo tail -F /var/log/nginx/error.log) shows no related error. The Daphne and Redis-Services seem to work: Redis Status: redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-04-07 08:44:07 CEST; 55min ago Docs: http://redis.io/documentation, man:redis-server(1) Process: 281 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS) Main PID: 381 (redis-server) Tasks: 4 (limit: 60) Memory: 4.1M CGroup: /system.slice/redis-server.service └─381 /usr/bin/redis-server 127.0.0.1:6379 Daphne-Service Config: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django_user/appdir/myProject ExecStart=/home/django_user/appdir/env/bin/python3 /home/django_user/appdir/env/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/myproject.com/fullchain.pem myproject.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target Daphne-Service Status: daphne_myproject.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne_myproject.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-04-07 08:44:04 CEST; 50min ago Main PID: 277 (python3) Tasks: 1 (limit: 60) Memory: 74.8M CGroup: /system.slice/daphne_myproject.service └─277 /home/django_user/appdir/env/bin/python3 /home/django_user/appdir/env/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/live/myproject.com/fullchain.pem myproject.asgi:application Nginx-Config: upstream websocket{ server 127.0.0.1:6379; } server { server_name myproject.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django_user/appdir/myProject; } location / { include … -
How I can open page when click on user name in user list and his/her name show in page
I did the list page and user information page but how I can when click on user name in list it open page has name of that user and I can add user email and phone number information and save it in db so when open it again i can see the added information in the page. -
How to show MQTT data on Django webpage?
I am relatively new to Django and I am trying to figure out how I can display some mqtt data in realtime on a django webpage as the client. I have created a python generator that sends data to self created mqtt broker and all of that seems to be working. In my django project I have the following: import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): client.subscribe("TEST/#") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) pass client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set("broker", password="pass") client.connect("127.0.0.1", 1883, 60) Here you can see me printing the payload that comes through but I can't seem to figure out a way to get this showing on the a webpage in realtime. Any help will be appreciated. Thank you! -
Django - List Filtering using a ForeignKey within a ForeignKey
I can filter the list of Bookings from "housing" using the "Housing" ForeignKey But I need to do it based on the h_type which uses the "HousingType" ForeignKey I am not sure of the correct terminology here but I think I am trying to use a ForeignKey within a ForeignKey, not sure how to accomplish this within the view. models.py class HousingType(models.Model): name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) class Housing(models.Model): h_type = models.ForeignKey('HousingType', null=True, blank=True, on_delete=models.SET_NULL) class Booking(models.Model): housing = models.ForeignKey('Housing', null=True, blank=True, on_delete=models.SET_NULL) views.py def view_bookings(request): housing = Housing.objects.all() bookings = Booking.objects.all() if request.GET: if 'housing_type' in request.GET: h_types = request.GET['housing_type'].split(',') bookings = bookings.filter(housing_type__name__in=h_types) h_types = HousingType.objects.filter(name__in=h_types) html template <a href="{% url 'view_bookings' %}?housing_type=apartments">Apartments</a> -
Show file contents to html page in django
I am running one shell script from django views.py. below is code def result(request): if request.method=="POST": process=subprcoess.Popen(cmd, shell=True, stdout=subprcoess.PIPE, stderr=subprcoess.PIPE, universal_newlies=True) while process.poll() is None: print(process.communicate()[0]) continue return render(request, 'result.html') Now here can able to get logs on file, instead directly need to redirect to html page. Could anyone please help here? Thank You. -
Django: add only permissions of specific application
I´m using django for my backend and this backend is managing multiple applications. For example i have app_a and app_b. for app_a i created a lot of custom permissions and groups. Now i want to give another user the permission to access the admin panel, but i wan`t that he can only add permissions and groups to users that belongs to app_a. I tried to use add_group or add_permission, but this is assigned to all apps. Thank you for support! -
How to modify timestamp field format in Django Rest Framework
I have this model: class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField('User', null=True, blank=True, related_name='liked_posts') savers = models.ManyToManyField('User', null=True, blank=True, related_name='saved_posts') likes = models.IntegerField(default=0) I want to return the timestamp field in json as: timestamp.strftime('%b %d %Y, %I:%M %p') I've been suggested to write this code in the model's serializer: class PostSerializer(serializers.ModelSerializer): str_timestamp = serializers.SerializerMethodField( method_name="get_str_timestamp" ) class Meta: model = Post fields = '__all__' def get_str_timestamp(self, obj: Post): return obj.timestamp.strftime('%b %d %Y, %I:%M %p') But it doesn't work and it still has its raw format. -
Django BaseManager and DefaultManager clarification
I am using Django 3.2. I am reading a section on Custom managers, and came across this text in the documentation: By default, Django uses an instance of the Model._base_manager manager class when accessing related objects (i.e. choice.question), not the _default_manager on the related object. This is because Django needs to be able to retrieve the related object, even if it would otherwise be filtered out (and hence be inaccessible) by the default manager. If the normal base manager class (django.db.models.Manager) isn’t appropriate for your circumstances, you can tell Django which class to use by setting Meta.base_manager_name. Base managers aren’t used when querying on related models, or when accessing a one-to-many or many-to-many relationship. For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions. The section text seems a bit convoluted. Is it possible to explain what is being said in the above text, by using the models below? class Foo(models.Model): name = models.CharField(max_length=64) deleted = models.Boolean(default=False) # ... class FooBar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='foos') start_date = models.DateTimeField(default=now, db_index=True) end_date = models.DatetTimeField(default=now+timeddelta(days=200), db_index=True) # ... -
How to grant access to download files from AWS S3 bucket?
I'm totally new to AWS and don't have much idea about it. When I try to download an image file from S3 it opens the file instead of downloading it. Here's my s3 bucket policy and the URL Django URL pattern: { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my_bucket_name/*" } ] } <a href="{{products.files.url}}" download="{{products.files.url}}">Download</a> -
How to gracefully handle DoesNotExist exception when admin user is not found?
I have a created_by field in my model which defaults to the admin user upon object creation. I am fetching the admin user using this piece of code, admin_user_name = settings.ADMIN_USER_NAME admin = User.objects.get(username=admin_user_name) Now if I have to handle the object.DoesNotExist exception like try: admin_user_name = settings.ADMIN_USER_NAME admin = User.objects.get(username=admin_user_name) except User.DoesNotExist: # handle the exception gracefully How do I handle the exception without throwing an error in such a case? -
fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User' with CustomUser model
In this project, I've used fcm-django package for push notifications in the flutter app. And I have got the following error though I've set up appropriately. Please help me what I wrote wrong! fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. Here is my fcm-settings: # FIREBASE_APP = firebase_admin.initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "django_fcm", # Your firebase API KEY "FCM_SERVER_KEY": "AAAAGhkzsi8:APA91bGCGga9FZnwASRy8NtLpp7jpINJcWbUiz9EHOFIxJjla8yVlpGtdqL7QB5rII0vKKExkpUw9PuRHt6khrpgcqDxcbzQvCWzgsBmT4SRRfoCirpGFXETIdIetgxBvktKJYSdjf_O", # true if you want to have only one active device per registered user at a time # default: False "ONE_DEVICE_PER_USER": False, # devices to which notifications cannot be sent, # are deleted upon receiving error response from FCM # default: False "DELETE_INACTIVE_DEVICES": True, } DEFAULT_AUTO_FIELD = 'FcmDjangoConfig.default_auto_field' And, I also imported the following lines: from fcm_django.apps import FcmDjangoConfig firebase_admin.initialize_app() os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './push_notification/serviceAccountKey.json' -
How I validate if user belongs and if not he is not allowed in Django
I have a view that I want to pass all the requests that belongs to a hospital. And, the user which belongs to a hospital, can't see others hospital requests. How can I return a HttpResponseNotAllowed ? It is a M:1 model, Hospital has many users, and a User has only 1 hospital. The requests belongs to the hospital and the user. I have this code in my view, but it doesnt work. Only shows me the requests that belongs to the hospital. But still I can change the Url to another Hospital ID and see others. View def Get_UserRequest(request, Hospital_id): # if not request.user.is_authenticated: # return redirect('login') if request.user.is_authenticated and request.method == "GET": user_sector = int(request.user.FKLab_User.id) if user_sector != Hospital_id: HttpResponseNotAllowed() requests = RequestHepatoPredict.objects.filter(Hospital_id=Hospital_id) return render(request, 'user_profile/requests.html', {'requests': requests}) -
Django migrations: base data with tests
I am adding some base data to database with Django's database migrations. Base data consists of predefined values of types which are accessible to all users. There is also possibility to create custom types by users. Problem is that when running tests with --keepdb option, tables will be flushed and also base data will be removed. Without --keepdb option tests are considerably slower. Is there a way to create base data so that it would be available to tests with --keepdb option? Or is there a way to run tests so that base data would be accessible without doing all migrations again? Migrations I have created look like this: def set_default_values(apps, schema_editor): Type = apps.get_model('app1', 'Type') Type(name='name1', user=None).save() Type(name='name2', user=None).save() Type(name='name3', user=None).save() class Migration(migrations.Migration): # ... operations = [ migrations.RunPython(set_default_values, elidable=True) ] -
I'm having an issue displaying the card rate according to the selected card category
Please, I need help with my Django project. I'm having an issue displaying the card rate according to the selected card category. I have been having this Issue for a while now please I need help. Here is my my view: @login_required(login_url='/Authentication/login') def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) context = { 'giftcards': giftcards, 'categories': categories, } return render(request, 'dashboard/giftcard.html', context) Here is my models and I link them using ForeignKey: class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard/', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) card = models.ForeignKey(Giftcard, on_delete=models.CASCADE) class CardRate(models.Model): rate = models.IntegerField() card_category = models.ForeignKey(Category, on_delete=models.CASCADE) Here is my template, i think am writing the wrong code here: {% for giftcard in giftcards %} <!-- Card --> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <select id="category" class="form-select py-2" aria-label="Default select example"> {% for spec in giftcard.category_set.all %} <option value="{{ spec.category }}">{{ …