Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UniqueConstraint returns error after adding modifying by adding a field to it
I have UniqueConstraint on a model and realized I needed to add one more field (field3) to prevent double entries but when I did that and I run python manage.py makemigrations it works fine but python manage.py migrate returns the error below: django.db.utils.OperationalError: (1553, "Cannot drop index 'bulk_fee_amount_key': needed in a foreign key constraint") The initial unique constraint is models.UniqueConstraint(fields=['field1', 'field2'], name='special_key') The new updated unique constraint is models.UniqueConstraint(fields=['field1', 'field2', 'field3'], name='special_key') But I get the error above when I try applying the migration. I use MySQL as my database management system. -
making an app using python with django library but the server not responding
i have installed django using command prompt and do coding on visual studio code by installing python. it is showing the django installed successfully but after the project setup , it does not show any kind of output . instead it is showing ' this site can't be reached . server refused to connect.' -
How to correctly output an image to the template in Django?
The image of the page is not displayed. Most likely I am incorrectly specifying the path to the image file. Please tell me what I should fix in my code? Code in the template <main> {% block content %} <p> <img src="../outputs/imgoutputs/14.jpg" width="189" height="255" alt="lorem"> </p> {% endblock %} </main> Approximate project structure: project -generate(app) -views.py -outputs -imgoutputs -14.jpg -templates -thankyou.html Help me please to correctly specify the path to the image. -
Can we connect sqflite and django in flutter?
With flutter I am using sqflite package for my reminder feature where user will be able to create a reminder, and I am using django for my other backend tasks, now the problem is, there will multiple users in an app and each user will have their own user_id and password to login into the app (the users are created from django) and since reminder feature will use sqflite package to store the user data it can't differentiate between users, meaning: if user "A" logged into the app and created a reminder and then user "B" logged into the app then he will also see the reminder created by user "A", user "B" will be able to see only the reminders set by user "A" not other personal data of user A which are coming from django server. So is there any way that I can make the reminder only visible to that particular users who created them ? or any way I can connect my sqflite package with my django?? -
Could someone check out my code error please?
Hello, could someone take a look at my code please? My login button return NONE and I am lost with it since 2 days. The views: def login_view(request, *args, **kwargs): context = {} user = request.user if user.is_authenticated: return redirect("index") destination = get_redirect_if_exists(request) print("destination: " + str(destination)) if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) if destination: # si destination n'est None return redirect(destination) return redirect("index") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, "login.html", context) def get_redirect_if_exists(request): redirect = None if request.GET: if request.GET.get("next"): redirect = str(request.GET.get("next")) return redirect The root_urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include("vazimba.urls")), path('account/', include("account.urls")), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) The_app_urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from .views import register_view, login_view, logout_view urlpatterns = [ path('login/', login_view, name="login"), path('logout/', logout_view, name="logout"), path('register/', register_view, name="register"), The templates: ==> account(the app) => templates/account/login.html {% if user.is_authenticated %} # html code----- {% else %} <div class="container"> <h1>home page</h1> <h2>Vous vous … -
Django relations sqlite
in my models i have a problem. Using Types model i want to take the costs from Outgo. I cant do this other way, mayby you know how to take it and display in template? class Types(models.Model): name = models.CharField(max_length=50, unique=True) class Outgo(models.Model): name = models.CharField(max_length=50) cost= models.DecimalField(max_digits=9, decimal_places=3) date = models.DateField(default=datetime.date.today) types= models.ForeignKey(Types,null=True, blank=True) -
Django - authenticate always returns None
I'm trying to create a login form for my website, but I cannot log into any existing account. def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid username/password') context = {} return render(request, 'base/login_register.html', context) Even if I use the correct credentials, it will display: User does not exist Invalid username/password I've also added this to my settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) I've created those accounts manually from the Django admin account, not with a registration form, could this be the issue? -
Django DRF - Manually validate CSRF token
I read in the docs that DRF only validates CSRF tokens on authenticated requests and login views should explicitely check the CSRF token. Problem is, how does one manually check the CSRF token? In my settings.py: MIDDLEWARE = [ ... "django.middleware.csrf.CsrfViewMiddleware", ... ] Here's my view: from rest_framework.decorators import api_view from django.http import JsonResponse from django.views.decorators.csrf import get_token # I have to manually generate the csrf token and put it in the response body, because I use react-native and that can't read the token from the 'Set-Cookie' header @api_view(["GET"]) def user_info(request): return JsonResponse({"csrf_token": get_token(request)}) @api_view(["POST"]) def login(request): return JsonResponse({"foo": "bar"}) When I make a POST request in the frontend and I don't provide the CSRF token, it should fail, but I actually receive the {"foo": "bar"} JSON. I tried the @csrf_protect and @requires_csrf_token decorators, but the request is still not failing. I also tried this, but that errors on required positional argument: 'get_response CsrfViewMiddleware().process_request(request) If I pass a function to get_response, that function is never called: def test_get_response(req): breakpoint() CsrfViewMiddleware(get_response=test_get_response).process_request(request) I checked that the CSRF token is not passed in the headers, not the cookies, and I tried different browsers and incognito mode. How do I get my api requests … -
Page not reloading on targeted elements except the first session
I'm working on an e-commerce store, it has a cart page where there are quantity increase and decrease buttons for every product added to the cart, I'm trying to reload the page every time someone hits any of these buttons. So when I have only one product in the cart, the reloading works fine when clicking on the buttons, but when I have more than one product in the cart and I try to increase or decrease the quantity of the second or the third product, it doesn't reload. It seems reloading only works with the first product that has been added, any clue why this is happening? I'm guessing this has something to do with DOM, but how do I fix this? {% for item in items %} <div class="quantity"> <p id="quantity-style" class="quantity-style">{{item.quantity}}</p> <div class="quantity-arrows"> <img data-product="{{item.product.id}}" id="reload_arrow_up" data-action="add" src="{% static 'shop/images/arrow-up.png' %}"> <img data-product="{{item.product.id}}" id="reload_arrow_down" data-action="remove" src="{% static 'shop/images/arrow-down.png' %}"> </div> </div> {% endfor %} $('#reload_arrow_down').click(function() { location.reload(); }); $('#reload_arrow_up').click(function() { location.reload(); }); -
Please help, I got ProgrammingError at /perzsi/api/register (1110, "Column 'is_active' specified twice") and I have been facing this for up to a week
The code below shows the models.py Despite checking all the variable and values here, I couldn't see a reason why the column 'is_active' appeared twice. class Tbuser(models.Model): iduse = models.IntegerField(primary_key=True) regdate = models.DateTimeField(blank=True, null=True) lastname = models.CharField(max_length=20, blank=True, null=True) name = models.CharField(max_length=20, blank=True, null=True) username = models.CharField(max_length=100, blank=True, null=True) businessname = models.CharField(max_length=100, blank=True, null=True) url = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=2, blank=True, null=True) state = models.CharField(max_length=2, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) zip = models.IntegerField(blank=True, null=True) phone = models.CharField(unique=True, max_length=20, blank=True, null=True) email = models.CharField(unique=True, max_length=80, blank=True, null=True) securepass = models.TextField(blank=True, null=True) securepassconfirm = models.TextField(blank=True, null=True) a_role = models.CharField(max_length=5, blank=True, null=True) user_type = models.CharField(max_length=16, blank=True, null=True) questionaire = models.CharField(max_length=500, blank=True, null=True) otp = models.CharField(max_length=500, blank=True, null=True) otp_expire_at = models.DateTimeField(blank=True, null=True) password_token = models.CharField(max_length=500, blank=True, null=True) password_token_expire_at = models.DateTimeField(blank=True, null=True) archive_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'tbuser' The code below shows the serializers.py Despite checking all the variable and values here, I couldn't see a reason why the column 'is_active' appeared twice. from api import models from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Tbuser User=Tbuser() class UserSerializer(serializers.ModelSerializer): class Meta: model = Tbuser fields = ('iduse','email', 'username', 'securepass') extra_kwargs = {'securepass': … -
Vscode does not show arguments suggestion for models fields
It should be like this screenshot But in my case it shows this instead screenshot I use newest version of vscode (1.71.2), I have tried every django extensions on marketplace, nothing work. How can I fix this? -
AttributeError: 'ForeignKey' object has no attribute 'types_pizza_set'
AttributeError: 'ForeignKey' object has no attribute 'types_pizza_set' I want to get the values from the types_pizza model and immediately assign the value of the field in the new model How can this be done correctly? from django.db import models ##### тип пиццы, время готовки размер стоимость class types_pizza(models.Model): pizza_type = models.CharField(max_length= 30, help_text="type pizza") # цена по размерам 30 35 40 45 price_small = models.BigIntegerField(help_text="price_small") price_midle = models.BigIntegerField(help_text="price_midle") price_large = models.BigIntegerField(help_text="price_large") price_very_large = models.BigIntegerField(help_text="price_very_large") def __str__(self): return str(self.pizza_type) + "price: " + str(self.price_small) + " "+ str(self.price_midle) + str(self.price_large ) + str(self.price_very_large) ### тип данных для заказа class order_to_user(models.Model): id_oder = models.AutoField(primary_key =True, ) adress_order = models.CharField(max_length=30) def __str__(self): return self.adress_order ### тут хранится пицца заказанная и прекрепляется к заказу class pizza(models.Model): SIZE_CHOISE=[ ("sm", "small"), ("md", "middle"), ("lg", "large"), ("vlg", "very large" ), ] pizza_type = models.ForeignKey(types_pizza , on_delete=models.CASCADE ) pizza_size = models.CharField(max_length= 5, choices=SIZE_CHOISE, default="md", verbose_name="размер") order_pizza = models.ForeignKey(order_to_user, on_delete=models.CASCADE) number_of_units_pizza= models.BigIntegerField( unique=False ) ## price = pizza_type.types_pizza_set.price_small def __str__(self): return str(self.pizza_type) + "шт" -
django admin site returns MultipleObjectsReturned exception with inspectdb imported legacy database and composite primary key
Using inspectdb, I have imported a legacy database, that contains entities with composite primary keys, in django . The database schema contains about 200 different entities and inspectdb is quite handy in that situation. This is the schema in mysql: CREATE TABLE `mymodel` ( `id` bigint(20) unsigned NOT NULL DEFAULT '0', `siteid` bigint(20) unsigned NOT NULL DEFAULT '0', ... PRIMARY KEY (`siteid`,`id`), ... Following the autogenerated model in django (imported using python manager.py inspectdb) class Mymodel(models.Model): id = models.PositiveBigIntegerField() siteid = models.PositiveBigIntegerField(primary_key=True) ... class Meta: managed = False db_table = 'mymodel' unique_together = (('siteid', 'id'), I have registered all models in the admin site using the following approach: from django.contrib import admin from django.apps import apps app = apps.get_app_config('appname') for model_name, model in app.models.items(): admin.site.register(model) After all the work is done, I navigate to the admin site and click on any object in the "mymodel" section and the following exception will be returned: appname.models.Content.MultipleObjectsReturned: get() returned more than one Mymodel-- it returned more than 20! Obviously, (this is what it seems to me at least) admin is using the siteid to get the object, tough it should use the unique_together from the Meta class. Any suggestions how I can achieve … -
jquery can't select unique elements using classes
I'm trying to use ajax on some auto generated html elements from django. I saw that you do this by selecting the instances via the class, but I can't seem to get it working. What do I have wrong here? javascript $(document).ready(function() { $('.fix-button').on('submit', function(event) { event.preventDefault(); var $issue_id = $(this); $.ajax({ url: '{% url "fix_issue" %}', type: 'POST', datatype: 'json', data: { issueid: $issue_id.val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("fixed_bool").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) { } }); }); }); html <button class = "fix-button" value = "{{ issue.id }}">Fix</button> views.py def FixView(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('issueid')) issue = get_object_or_404(Issue, id=id) if issue.fixed == False: issue.fixed = True result = str(issue.fixed) issue.save() else: issue.fixed = False result = str(issue.fixed) issue.save() return JsonResponse({'result': result, }) -
how do i solve this permission denied error when i run python manage.py startapp
am pretty new to django and i just installed VS code and python and django too. then in the VS terminal when i type python manage.py startapp base i get the error bash: /c/Users/Admin/AppData/Local/Microsoft/WindowsApps/python: Permission denied. how do i tackle this problem. i don't think this is a VS issue, am suspecting its from my installation or something. i installed django in my desktop and it was successfull. what then could be denying it permission -
Can someone help me to understand why this is happening?
Problem is shown in the link given below ** when i try to hover or press on the navlinks it's not selecting but showing text cursor but by moving a few inches it shows why this is happening is something wrong with the padding or its the chrome ? ** (https://www.youtube.com/watch?v=Vbt5geHBPz4) my html code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- icons --> <link rel="stylesheet" href="https://unpkg.com/boxicons@latest/css/boxicons.min.css"> <!-- own css --> <link rel="stylesheet" href="{% static '/css/home/style.css' %}"> <!-- google fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Abyssinica+SIL&family=Montserrat:wght@500&display=swap" rel="stylesheet"> <title>Document</title> </head> <body> <header> <a href="#" class="logo">TakeAway</a> <div class="bx bx-menu" id="menu-bar"></div> <ul class="navbar"> <li><a href="#"></a>Home</li> <li><a href="#"></a>Home</li> <li><a href="#"></a>Home</li> <li><a href="#"></a>Home</li> </ul> </header> </body> mycss *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Abyssinica SIL', serif; scroll-behavior: smooth; list-style: none; text-decoration: none; } :root{ --main-color:rgb(243, 176, 88); --text-color:#fff; --bg-color:#ff4b24; --big-font:5rem; --h2-font:2.25rem; --p-font:0.9rem; } *::selection{ background:var(--main-color); color: rgb(0, 0, 0); } body{ color: var(--text-color); background: var(--bg-color); } header{ position: fixed; top: 0; right: 0; width: 100%; z-index: 1000; display: flex; align-items: center; justify-content: space-between; padding: 30px 150px; background: var(--bg-color); } .logo{ color: var(--main-color); font-weight: 600; font-size: 2.4rem; } .navbar{ … -
Sorting the search result
I'm starting to learn Django and I ran into this problem: I can't add parameters to the link Example: Link before the change: http://127.0.0.1:8000/?brand=&search= Link after the change: http://127.0.0.1:8000/?brand=&search=&sort= What I get: http://127.0.0.1:8000/?sort= How to implement it? views.py def filters(request): #search search_post = request.GET.get('search', '') if search_post: all = Product.objects.filter(Q(title__icontains=search_post) & Q(content__icontains=search_post)).order_by() else: all = Product.objects.all() #sort by price sort_by = request.GET.get("sort", '') if sort_by == "l2h": all = Product.objects.all() all = all.extra(order_by = ['-price']) elif sort_by == "h2l": all = Product.objects.all().order_by('price') filters = IndexFilter(request.GET, queryset=all) context = { 'filters': filters } return render(request, 'index.html', context) urls.py from django.urls import path from .views import * urlpatterns = [ path('', filters, name='filters') ] index.html <form method="get" action="{% url 'filters' %}"> {{ filters.form }} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> <a class="filter_by" href="?sort=l2h">Price:--low to high</a> <a class="filter_by" href="?sort=h2l">Price:-- high to low</a> </form> -
I am working on a django project that involves three models as indicated below Client,Loan,Payment
I am getting alot of duplicates in my template when i try to call the calculated loan payments in templates. My models: class Client(models.Model): full_name = models.CharField(max_length=200,blank=True) staff=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,null=True,blank=True,related_name="client") date = models.DateTimeField(default=timezone.now) class Loan(models.Model): ref = ShortUUIDField(length=6,max_length=6,alphabet="ABCDZXFQFHKRKL0123456789",unique=True) loan_amount = models.IntegerField(blank=True,null=True) staff=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,null=True,blank=True,related_name="loans") search_client=models.ForeignKey(Client,on_delete=models.SET_NULL,null=True,blank=True) @cached_property def loan_repayments(self): myfilter = Loan.objects.filter(ref=self.ref,payment__payment_reason='loan repayment') result=myfilter.aggregate(total=Sum(F('payment__amount'))) total = result['total'] if total is None: return 0 return total class Payment(models.Model): ref = ShortUUIDField(length=6,max_length=6,alphabet="ABCDZXFQFHKRKL0123456789",unique=True) payment_reason = models.CharField(max_length=200, null=True, blank=True,choices=PAYMENT_REASON,default='loan repayment',db_index=True) amount = models.IntegerField(blank=True, null=True) lender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, related_name="payments") loan = models.ForeignKey(Loan, on_delete=models.CASCADE, blank=True, null=True) my view: class Loan(LoginRequiredMixin,ListView): query_set =Loan.objects.filter(status="active",action="creating loan").select_related('staff','search_client') context_object_name = 'transactions' paginate_by = 15 my template: duplicates am getting: duplicates in the toolbar -
Django how to create child record with parent id
I am trying to link the accounts table with the user table using the Foreigkey field. Inside my model, I have Account class. class Account(models.Model): account_number = models.CharField(max_length=30) account_type = models.CharField(max_length=20) user = models.ForeignKey(User, related_name='accounts', on_delete=models.CASCADE) Below is my serializers.py class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'account_number', 'account_type') class UserSerializer(serializers.ModelSerializer): accounts = AccountSerializer(many=True) class Meta: model = User fields = ('id', 'first_name', 'last_name', 'email', 'password', 'accounts') extra_kwargs = {'password': {'write_only': True, 'required': True}} In my view.py, I created AccountViewSet class AccountViewSet(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = AccountSerializer I am trying to insert an account record with a user id using Postman, I am getting the following error message. django.db.utils.IntegrityError: null value in column "user_id" of relation "app_account" violates not-null constraint DETAIL: Failing row contains (7, 0187898789, Saving, null). I already have a user record with id 1 in the database, and in postman, I did pass the user_id. However, when I try to print the validated_data it doesn't show the user_id -
django iterate through model objects that contain another particular model object in a ManyToManyField
I have the following models in my django app. class author(models.Model): name=models.CharField(max_length=100) class book(models.Model): name=models.TextField() authors=models.ManyToManyField(author) A author definately have written multiple books. A single book can also have multiple authors. I want to iterate through all books by a particular author. Till now I have tried for b in book.objects.filter(authors__name='HiDe'): print(b) which gives AttributeError: 'function' object has no attribute 'objects' probably because authors in book is a ManyToManyField. Adding books=models.ManyToManyField(author) will make the database large and cumbersome to manage as an author can have too many books, so this is not the solution I want. -
AJAX only updates a single django model instance
I have a django project that shows a list of "issue" objects, and each issue object has a boolean field called "fixed". I want the user to be able to press a button that will change "fixed" using ajax, but the button only changes one of the issue objects rather than whatever "issue" that button belongs to, here's a gif of my problem Here is my html: {% for issue in projects.issues.all %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ issue.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ issue.author }}</a> <small class="text-muted">{{ issue.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'issue-detail' issue.id %}">{{ issue.title }}</a></h2> <p class="article-content">{{ issue.description }}</p> <p>{{ issue.severity }}</p> {% if projects.author == user %} <span id="fixed_bool">{{ issue.fixed }}</span> {% csrf_token %} <button class = "btn btn-primary btn-sm" id="fix-button" value = "{{ issue.id }}">Fix</button> {% endif %} </div> </article> {% endfor %} Javascript: $(document).on('click', '#fix-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "fix_issue" %}', data: { issueid: $('#fix-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("fixed_bool").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) { } }); }) my url path('fix/', views.FixView, name='fix_issue'), and my views def FixView(request): if request.POST.get('action') … -
[Dokcer]python3: can't open file '/app/manage.py': [Errno 2] No such file or directory
I'm new to docker, and I tried to run django on the docker container. However, after I ran the "docker-compose up -d" command the error python3: can't open file '/app/manage.py': [Errno 2] No such file or directory shows in docker. Since it seems that the code can be run successfully in mac os, I doubt if it is the problem of Windows11 which I run the file currently. My questions are: 1.Why the this error happens? 2.How I can fixed it? The dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ the docker-compose file version: '3' services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db I've tried to solve the problem for hours, but the solutions I searched did not work. Hope someone can help. Thank you very much!! -
Finding 2 values if available in a list in a Django Template
I have the following list called `` :[(2, 'Flat Bench'), (1, 'Flat Bench'), (3, 'Flat Bench')] I am trying to find if the b.order which is the first number and e.name which is the 2nd string is available from a django template. In my trial I made sure that b.order is equal to 2 and e.name is 'Flat Bench'. Here is the django template: {% if b.order and e.name in all_logs %} available {% else%} not available {% endif %} In my case there is no error, it is just always showing not available even if it is available. I am not sure what change I should be doing to get this code to work. -
How to populate a model's foreignkey field from another model instance's foreignkey field
I have the models: Recipe, Ingredient, and Cart. I'll have 2 types of Users: Cooks and Eaters. Cooks create Recipe posts and include the Ingredients for each Recipe. Ingredients are mapped to Products I want the Eaters, as they're on the recipe_detail.html, to have their Cart pre-populated with all the Products referenced in the Ingredient list associated with the Recipe currently being visited. Here's my code: #ingredients/models.py class Product(models.Model): name = models.CharField(max_length=255) class Ingredient(models.Model): recipe = models.ForeignKey(Recipe,on_delete=models.CASCADE, blank=True, related_name='ingredients') product = models.ForeignKey(Product,on_delete=models.CASCADE, blank=True) #cart/models.py class Cart(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='products') #cart/views.py class CartCreateView(CreateView): model = Cart template_name = "recipes/recipe_detail.html" form_class = CartModelForm def dispatch(self, request, *args, **kwargs): """ Overridden so we can make sure the `Recipe` instance exists before going any further. """ self.recipe = get_object_or_404(Recipe, pk=kwargs['Recipe_id']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): """ Overridden to add the recipe relation to the `Ingredient` instance. """ ingredients = self.recipe.ingredient.all() form.instance.owner = self.request.user.pk form.instance.product = None # <---- The problem return super(CartCreateView, self).form_valid(form) #recipe_detail.html <!-- Recipe --> <div> <h2>{{ recipe.title }}</h2> <p>By: {{ recipe.owner }}</p> </div> <!-- Ingrediants --> <div> <h4>Ingrediant list:</h4> <ul> {% for ingrediant in recipe.ingrediants.all %} <li>{{ ingrediant }} {{ ingrediant.context }} {% … -
How to get values of a dictionary in a Django Template without for loop
I am trying to get a value of a dictionary in a Django Template. I am not sure whether this is possible or not. Here is the following template: {{ active_session.log.values }} This is the print out of it: <QuerySet [{'id': 318, 'log_order': 1, ......other repeated keys and values}> My question how can get all the values of the log_order with going through a for loop in the template knowing that it is a many to many relationship. Here is the models: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. here is the views: class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) p = Log.objects active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id) context = super().get_context_data(**kwargs) context['exercises'] = exercises context['form'] = LogForm() context['p'] = p context['active_session'] = active_session return context There are several answers out there saying that can create a function lookup but it got me an error Failed lookup for key [log_order] in <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x046FE4A8> Here is the function in the models: @register.filter(name='lookup') def lookup(value, arg): value_dict = ast.literal_eval(value) return value_dict.get(arg) Here is the template: {{ mydict|lookup:active_session.log.log_order }}