Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
question mark breaks regex function in different ways
I have a function that finds substring which start with "@" (usernames), checks database for the username and transforms the substring to a html tag. But for some reason if there is a question mark in the string the first substring before questionmark doesn't get converted. Say the string is: the function above finds all the substrings which start with "@" sign and it works fine: user= re.findall(r"[@]([^¿#@$\\|]*)(?=[¿#@$\\|]|$)", string) user= list(set(user)) and the one above gets first 26 characters (max username len) of every substring and checks the database for usernames. for i in user: k = i[0:26] j = k.rstrip() while True: try: username= User.objects.get(username = j) rest = i.replace(j,"",1) url=url_text(j) string = re.sub(r"[@]({})(?=[¿#@$?\\|]|$)".format(i,),"¿<a class='user-link3' href='/user/{}--{}'>{}</a>{}".format(url,user.id,j,rest),string) break except: if " " not in j: break else: j = j.rsplit(" ",1)[0] j= j.rstrip() So far the function only breaks when there is a "?" in the string and I couldn't figure out why, as it behaves different depending on situation (also I'm not good in regex). Say the string is: string = "@mattarello xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:https://m.youtube.com/watch?v=zIV4poUZAQo" the function returns: @mattarello xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:https://m.youtube.com/watch?v=zIV4poUZAQo input 2: "@mattarello xxxxxxxxxxxx?" output 2 "?" gets doubled: "¿<a class='user-link3' href='/user/mattarello--2'>mattarello</a> xxxxxxxxxxxx??" input 3: "@mattarello ????" no output at all. -
How Can I Raise Validation Errors In The Same Way As 'Required' Errors?
I have three types of error messages being displayed. One is the Django error message when a user doesn't fill out a required field. Another is crispy error messages. The last is my own validation errors that are printed using Django messages. I know I can also loop through {% for error in field.errors %} and print them out. Having three different types of error messages doesn't offer a particularly pleasing user experience. I'd like to use just one, either the Django 'required' type errors or crispy errors are the nicest as they appear on the related field. Let's say I go with the Django 'required' type errors, how can I make my validation errors which are raised in my clean method be raised in the same way as required error messages? Thank you. -
I want to check whether the products in the category page exists in cart then show a added icon in webpage using django and jinja
I have a category page(having multiple products which have add to card button under them) in which I have a add to cart button but if that product already exists in the cart I want to show a Added to cart icon instead.I am not able to figure out the way to check that. Here is my models.py class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False,null=True,blank=False) transaction_id=models.CharField(max_length=100,null=True) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True) quantity=models.IntegerField(default=0,null=True,blank=False) date_added=models.DateTimeField(auto_now_add=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) productid=models.CharField(max_length=30) name=models.CharField(max_length=30) And here is my views.py def category(request): context = { 'types' : Category.objects.all(), 'prods': Product.objects.filter(), 'cartItems':[], 'in_cart': False, } if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) cartItems=order.get_cart_items, items=order.orderitem_set.all() context['in_cart'] =order.orderitem_set.filter(product__productid=id).exists() return render(request,"category.html",context) And here is my html code for that button {% if user.is_authenticated %} {% if in_cart %} <button data-product={{product.id}} data-action="add" class="btnabc btnabc-warning update-cart">Added</button> {% else %} <button data-product={{product.id}} data-action="add" class="btnabc btnabc-warning update-cart">Add to Cart</button> {% endif %} {% else %} <button class="btnabc btnabc-warning"><a href="/login/">Add to Cart</a></button> {% endif %} But it does not seem to be working even if product is not in cart it shows Added Please suggest me a way so that on my html code i can check whether the item exists in the cart or … -
I get error when I try to get the list of articles
I am currently working on making the blog site by myself using Python Django. However, I get an error when I run it locally. To write the detail, whenever I try to access (http://127.0.0.1:8000/blog/lp/), the computer says "maximum recursion depth exceeded while calling a Python object" . I didn't put only two or three data and didn't write endless loop syntax. Please tell me why this happens and how I can fix it. urls.py (I am using the url "blog/") from django.contrib import admin from django.urls import path,include from diary import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("",views.home,name="home"), path("diary/",include("diary.urls")), path("Tabelog/",include("Tabelog.urls")), path("Youtube/",include("Youtube.urls")), path("blog/",include("blog.urls")) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) blog/urls.py from django.urls import path,include from blog import views from blog.views import BlogList,BlogDetail,BlogPost,BlogUpdate app_name="blog" urlpatterns = [ path("lp/",views.lp,name="landing_page"), path("list/",views.BlogList.as_view(),name="list"), path("detail/<str:pk>/",views.BlogDetail.as_view(),name="detail"), path("post",views.BlogPost.as_view(),name="post"), path("update/<str:pk>/",views.BlogUpdate.as_view(),name="update"), path("comment/<str:pk>",views.BlogComment.as_view(),name="comment") ] blog/views.py from django.shortcuts import render,get_object_or_404,redirect from django.views import generic from blog.forms import PostBlog from blog.models import Article,Category,Comment,Tag from django.urls import reverse_lazy from blog.forms import CommentPost # Create your views here. def lp(request): return render(request,"blog/lp.html") class BlogList(generic.ListView): model=Article template_name="blog/list.html" class BlogDetail(generic.DetailView): model = Article template_name="blog/detail.html" class BlogPost(generic.FormView): template_name="blog/post.html" form_class = PostBlog success_url = reverse_lazy("blog:list") class BlogUpdate(generic.UpdateView): model = Article fields = "__all__" success_url … -
get_context_data variable doesn't show up at HTML file
I have just started with using Django with a Django Crash Course book and got stuck on a part. Let me show you what I have done so far and where I got stuck. I opened a templates folder on the hellodjango project folder and wrote some basic HTML code like this. <h1>Greetings</h1> <p>Hello, world!</p> <p>{{my_statement}}</p> Here, the book says that it is okay to write my_statement like this because it will be later understood in python. Later on it tells you to change views.py file under the homepage folder like this. from django.views.generic import TemplateView class HomepageView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_statement'] = "Nice to see you:" return context However, when I refresh the page my_statement variable doesn't show up on the webpage at all. What could I possibly be doing wrong? I think if I didn't didn't have the packages, an error would pop up? But errors don't show up as well. I have also checked the django documentation on this topic but the code here has similarities to the one I am working with. Thanks for your help. -
How can I create a Django model for a form in which users can choose to add more fields?
I am new to Django and trying to build a resume site. I am using Django WizardForms for users to build out their resume in stages. In the education form, users can add up to 5 different schools they went to. (By using +Add Fields button I implemented with JavaScript) Is this the correct way to write out all the fields in models.py and forms.py? I am sure there must be a cleaner way to do this rather than individually listing out all fields and differentiating them with a number at the end. I have looked into Django FormSets but I am not sure how I would use that with Django WizardForms. Thank you models.py class Profile(models.Model): education_school = models.CharField(max_length=500, null=True, blank=True) education_degree = models.CharField(max_length=500, null=True, blank=True) education_field = models.CharField(max_length=100, null=True, blank=True) education_start = models.CharField(max_length=100, null=True, blank=True) education_end = models.CharField(max_length=100, null=True, blank=True) education_grade = models.TextField(null=True, blank=True) education_description = models.TextField(null=True, blank=True) education_school2 = models.CharField(max_length=500, null=True, blank=True) education_degree2 = models.CharField(max_length=500, null=True, blank=True) education_field2 = models.CharField(max_length=100, null=True, blank=True) education_start2 = models.CharField(max_length=100, null=True, blank=True) education_end2 = models.CharField(max_length=100, null=True, blank=True) education_grade2 = models.TextField(null=True, blank=True) education_description2 = models.TextField(null=True, blank=True) education_school3 = models.CharField(max_length=500, null=True, blank=True) education_degree3 = models.CharField(max_length=500, null=True, blank=True) education_field3 = models.CharField(max_length=100, null=True, blank=True) education_start3 = … -
Is there a way to find the width of the page using jinja2
I am using a django framework and wanted to display another image on screen if the width of the screen is less than 800px (similar to the CSS '@media(min-width)' function). Is it possible to do it with jinja2 or can we do something in the django views to find the width of the page... Any help would be greatly appreciated! Thanks -
Problem while registering a model in admin.py file (Django)
from django.contrib import admin from . import models class TodoListAdmin(admin.ModelAdmin): list_display = ("title", "created", "due_date") class CategoryAdmin(admin.ModelAdmin): list_display = ("name",) admin.site.register(models.TodoList, TodoListAdmin) admin.site.register(models.Category, CategoryAdmin) I am trying to register two models in my Django admin.py file inside the app directory The model file is as follows : from django.db import models from django.utils import timezone # Create your models here. class Category(models.Model): name = models.CharField(max_length=200) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): return self.name class ToDoList(models.Model): title = models.CharField(max_length=250) contents = models.TextField(blank=True) created = models.DateField(default=timezone.now().strftime("%d-%m-%Y")) due_date = models.DateField(default=timezone.now().strftime("%d-%m-%Y")) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING) class Meta: ordering = ["-created"] def __str__(self): return self.title For some reason , there is no problem with Category class but I am encountering an error with ToDoList class . Django is showing the following error admin.site.register(models.TodoList, TodoListAdmin) AttributeError: module 'todolist.models' has no attribute 'TodoList' -
Django: what are the **kwargs arguments in get_context_data(self, **kwargs)?
What are the **kwargs arguments in get_context_data(self, **kwargs)? For example, in SomeListView.as_view(), what gets passed as **kwargs in the get_context_data method? -
javasript file can't work in django templates
I try to make a django project with bootstrap4.5 and django3.0.7 I already setting the staticfiles and templates dirs. I use this code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock title %}</title> <!-- bootstrap css --> <link rel="stylesheet" href="{% static "/css/bootstrap/css/bootstrap.min.css" %}"> </head> <body> <!-- navbar --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand ml-5" href="#">My ToDo List</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse mr-5" id="navbarSupportedContent"> <ul class="navbar-nav ml-lg-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Login</a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Register</a> </li> </div> </nav> {% block content %} {% endblock content %} <footer> </footer> <!-- bootstrap javascripts --> <script src="{% static 'css/bootstrap/js/bootstrap.min.js' %}"></script> <!-- jquery javascripts --> <script src="{% static 'js/jquery-3.5.1.slim.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> </body> </html> The is does not work. But if i use it with xampp that 100% work What i miss in my code?? -
Django check producing different results in different... Linux distros? (fields.E004)
Host Machine (Ubuntu 20.04, python 3.7.6, fresh virtualenv) I have a PostgreSQL database with a table having a column that has type character-varying. Then I run python manage.py inspectdb. It produces a model like this, which I save as a model file and use in the project: class TestModel(models.Model): message = models.CharField(max_length=-1, blank=True, null=True) (This is expected since Django does not support char fields with no max_length.) Then I run python manage.py check on the host machine, no errors. System check identified no issues (0 silenced). Finally, I run pip freeze > requirements.txt for later use. Docker Container (Base image: python 3.7.6:alpine) The docker image is created using the following Dockerfile: FROM python:3.7.6-alpine WORKDIR /usr/src/app RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY /my_app/requirements.txt . RUN pip install -r requirements.txt COPY /my_app . Then run /bin/sh with the docker image and try: python manage.py check ...It produces an error: myapp.TestModel.message: (fields.E121) 'max_length' must be a positive integer. How is that even possible? These two environments have the same python version, the same python packages. Outputs of python --version and pip freeze from sources are identical. The only difference I can tell … -
DRF Update method for images
I have a Django Post model contains images, text, date of creation and owner who can add other users to view it. I want to add a feature which allows user who is in the shared_to Field to add an image only once. Therefore, I have created ManyToMany Field in order to check if user has already added his image or not. If not, allow him to add an image along with his id so that he won't be able to do that again. I've tried some things in order to add users to ManyToMany field automatically, and check if they are already in it but won't work. model.py class Post(models.Model): post_name = models.CharField(max_length=255) post_text = models.TextField(max_length=360, blank=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='owner_user', on_delete=models.SET(get_deleted_user), default=1) created_on = models.DateTimeField(default=timezone.now) date_to_open = models.DateTimeField(blank=False) shared_to = models.ManyToManyField(UserProfile, blank=True, related_name='shared_to_user', null=True,) image_editor = models.ManyToManyField(UserProfile, blank=True, related_name='image_editor_user', null=True) def __str__(self): return self.capsule_name def save(self, *args, **kwargs): super(Capsule, self).save(*args, **kwargs) class PostImage(models.Model): post_file = models.FileField(blank=True, null=True, upload_to='media/covers/%Y/%m/%D/') gallery_post = models.ForeignKey(Capsule, related_name='images', on_delete=models.CASCADE) -
How should I set up the Django model for a complex blog application?
I am attempting to use Django to create a blogging website where I intend to host custom data visualisations created using d3.js. The data which drives the visualisations will then be a mixture of either stored on the server or accessed via APIs from other websites. I am wondering how this would be best implemented in the Django framework? Specifically: Should I store the custom JS as a field within the model? (It feels fundamentally wrong to store code in a text type field in a databse but this seems to be what would follow the model-view-template paradigm) How do I deal with each blog post potentially requiring different backend implementations to access data? -
How to branch My Django data Model base on user groups?
I need to branch my view base on users group. main model is Fact_CarCase: class Fact_CarCase(models.Model): CaseCode = models.IntegerField() ... CaseUnit = models.ForeignKey('Dim_Branch', to_field="BranchCode", related_name='Fact_CarCase_CaseUnit2', on_delete=models.CASCADE) CaseUserGroup = models.IntegerField(null=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.CaseCode) super().save(*args, **kwargs) related view is: @login_required def search(request): case_list = models.Fact_CarCase.objects.all().select_related('CaseType', 'VerdictType', 'AgentUnit','IncidentCity','CaseUnit','CaseDate') case_filter = filters.CaseFilter(request.GET, queryset=case_list) return render(request, 'CarIA/user_list.html', {'filter': case_filter}) related filter: class CaseFilter(django_filters.FilterSet): FraudulantRate__lte = django_filters.NumberFilter(field_name='FraudulantRate', lookup_expr='lte') CaseType__gte = django_filters.NumberFilter(field_name='CaseType', lookup_expr='gte') ... class Meta: model = models.Fact_CarCase fields = ['CaseType','CaseUnit','AgentUnit'] I define Groups for users. groups of users that can see every row of Fact_CarCase is defined in CaseUserGroup field. every user can be member of some groups. a member should see all case with CaseUserGroup equal to on of his groups. how I should change my Code for this purpose? -
Can't get Django with MariaDB running in virtualenv
I have a client who wants to get a django project. He would prefer MariaDB for the backend. I want to test the developing with MariaDB on my laptop and I want to do this in a virtualenv. I already setup a venv and then I ran pip3 install Django mysqlclient, but it failed and the traceback said something like that the installer is missing config files for the mysqlclient. I don't want to create config files on my machine, I just want them to be in the venv, so that I could send the whole project to my client. -
Is there any In built logger middleware in django?
Is there any In built logger middleware in django. I searched all over the internet but all that are creating custom middleware. If there is no inbuilt logger middle How can I make a custom logger middle ware for my django REST api ? -
i tried to connect python to mysql database it throws user 'root'@'localhost' in linux os
import mysql.connector as sa db = sa.connect(host="localhost",user="root",password="sandy123",database="school") print(db) Traceback (most recent call last): File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 216, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Access denied for user 'root'@'localhost' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "swip.py", line 2, in db = fuck.connect(host="localhost",user="root",password="sandy123") File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/init.py", line 264, in connect return CMySQLConnection(*args, **kwargs) File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 80, in init self.connect(**kwargs) File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/abstracts.py", line 966, in connect self._open_connection() File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 219, in _open_connection sqlstate=exc.sqlstate) mysql.connector.errors.ProgrammingError: 1698 (28000): Access denied for user 'root'@'localhost' sandytom@sandytom-Lenovo-ideapad-320-15ISK:~/Desktop/ruber$ python3 swip.py Traceback (most recent call last): File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 216, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Access denied for user 'root'@'localhost' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "swip.py", line 2, in db = fuck.connect(host="localhost",user="root",password="sandy123",database="school") File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/init.py", line 264, in connect return CMySQLConnection(*args, **kwargs) File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 80, in init self.connect(**kwargs) File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/abstracts.py", line 966, in connect self._open_connection() File "/home/sandytom/.local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 219, in _open_connection sqlstate=exc.sqlstate) mysql.connector.errors.ProgrammingError: 1698 (28000): Access denied for user 'root'@'localhost' -
Python library that rewrites code in an efficient way
What I'm trying to achieve: An application that would refactor a badly written code. That is, the badly written code will be passed as the input into this application & this application would rewrite the badly written code into efficient code & send the efficient code as output. What I'm looking for: A python package/library that would help me in achieving the above. Thanks -
Django create model with djongo
everybody, I want to get a data output like this in Mongodb, but there's an error in the migration. -
Django, What is the advantage of Modifying a model manager’s initial QuerySet?
The below model have EditorManager, class EditorManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(role='E') class Person(models.Model): first_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))]) people = models.Manager() editors = EditorManager() If I query Person.objects.filter(role='E') or Person.editors.all() I gets same result. then, Why do we go for writing EditorManager() ? The above code is from Django documentation (https://docs.djangoproject.com/en/3.0/topics/db/managers/). -
Django returning "unexpected keyword argument" from another function
I am having a problem with this function "Search", it returns the error "testr() got an unexpected keyword argument 'random'". Testr is another function and has nothing to do with "Search" I do not understand the connection django is making between the 2. And I do not know how to solve this. Could somebody help me please? def search(request,q): if request.method == "POST": query = request.POST['q'] entries = util.list_entries() for entry in entries: if entry == query: substring = [] if query in entries: substring.append(query) return render(request, "encyclopedia/title.html", { "entries": substring }) else: return render(request, "encyclopedia/error.html") the traceback error testr() got an unexpected keyword argument 'random' Request Method: GET Request URL: http://127.0.0.1:8000/wiki/search Django Version: 3.0.8 Exception Type: TypeError Exception Value: testr() got an unexpected keyword argument 'random' Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py in _get_response, line 113 Python Executable: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 Python Version: 3.8.3 -
Django dynamic database creation and configuration
What is the exact method of creating databases in django dynamically (at run time) and automatically add the details in settings file. I created database with python, updated settings.py file at run time but need server restart. So i think this is not a perfect solutions. Is there any way to handle this situation in django. -
IntegrityError: The row in table 'main_post' with primary key '2' has an invalid foreign key: main_post.author_id cointains a value '1'
After makemigrations, then migrate I got this error IntegrityError: The row in table 'main_post' with primary key '2' has an invalid foreign key: main_post.author_id cointains a value '1' that does not have a corresponding value in auth_user.id I try some solutions in similar question but it doesnot work My models.py User = get_user_model() class PostView(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) post = models.ForeignKey('Post', on_delete=models.CASCADE, blank=True) def __str__(self): return self.user.username class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.user.username class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class Category(models.Model): title = models.CharField(max_length=40) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() detail = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField(config_name='post_ckeditor') author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) def get_update_url(self): return reverse('post-update', kwargs={ 'id': self.id }) def get_delete_url(self): return reverse('post-delete', kwargs={ 'id': self.id }) @property def get_comments(self): return self.comments.all().order_by('-timestamp') @property def view_count(self): … -
I want to check whether the products exists in cart then show a added icon in webpage using django and jinja
I have a singleproduct page in which I have a add to cart button but if that product already exists in the cart I want to show a Added to cart icon instead.I am not able to figure out the way to check that. Here is my models.py class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False,null=True,blank=False) transaction_id=models.CharField(max_length=100,null=True) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True) quantity=models.IntegerField(default=0,null=True,blank=False) date_added=models.DateTimeField(auto_now_add=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) productid=models.CharField(max_length=30) name=models.CharField(max_length=30) And here is my views.py def singleproduct(request, id): if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() cartItems=order.get_cart_items types = Category.objects.all() prods= Product.objects.filter(productid = id) else: types = Category.objects.all() prods= Product.objects.filter(productid = id) cartItems=[] return render(request,"singleproduct.html", {'types':types,'prods':prods}) def cart(request): customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() context={ 'items':items, 'order':order } return render(request,"cart.html",context) And here is my html code for that button {% if user.is_authenticated %} {% if cart.productid %} <button data-product={{product.id}} data-action="add" class="btn btn-outline-info update-cart">Add to Cart</button> {% endif %} {% else %} <button class="btn btn-outline-info"><a href="/login/">Add to Cart</a></button> {% endif %} But it does not seem to be working with cart.productid. Please suggest me a way so that on my html code i can check whether the item exists in the cart or not and show the buttons accordingly. Any help would be … -
See all kwargs (python) in vscode
I am building a django project and sending REST API response using JsonResponse. JsonResponse has a kwargs status as you can see in image but I cannot see this argument in vscode. Can anyone help me with this