Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception Value : no such table: users_customuser
I am working on a group django project, and I created a 'customuser' model in an app called 'users'. I have created the model and changed everywhere that referenced django's base user model to reference my user model. In our app, we want the CustomUser to hold a list of events from the Event Model. #users.py from django.db import models from django.contrib.auth.models import AbstractUser from cal.models import Event # Create your models here. class CustomUser(AbstractUser): events_attending = models.ManyToManyField(Event,blank=True) The webapp runs locally, but when I try to log in or register as a user I get the error that there is no such table as customUser. my migrations are as follows: C:\Users\joe4a\Desktop\Newest\STAJJ>python manage.py showmigrations admin [X] 0001_squashed_0001_initial (1 squashed migrations) [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length cal [X] 0001_initial cockycal [X] 0001_initial [X] 0002_initial contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial users [X] 0001_initial Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.1.3 Python Version: 3.10.10 Installed Applications: ['cockycal.apps.CockycalConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'cal', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Comment form not working when separating views
I received some advice on separating my comment function into a separate view from 'ViewPost' view. When I do this the comment section no longer displays comments, and form doesn't appear to add a new one. Please see attached image for the code combined(I don't want to clog the question with code) I am lost for ideas and hoping some one has some input to share. My views separated def ViewPost(request, slug): try: post = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: print("Blog with this slug does not exist") post = None return render(request, 'mhpapp/view-post.html', {'post': post, 'slug': slug,}) def PostComment(request, slug): template_name = 'view-post.html' post = get_object_or_404(BlogPost, slug=slug) comments = post.comments.filter(status=True) user_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet user_comment = comment_form.save(commit=False) # Assign the current post to the comment user_comment.post = post # Assign comment to user user_comment.user = request.user # Save the comment to the database user_comment.save() else: comment_form = CommentForm() return render(request, template_name, {'post': post, 'comments': comments, 'user_comment': user_comment, 'comment_form': comment_form}) COMBINED WORKING CODE -
Vue app on server cannot communicate with DRF back-end on same VPS using caddy
It's my first time that I'm deploying Vue and DRF(Django rest frame work) app on production server. I used npm run build to build my Vue app as my front-end and I moves the dist folder to /var/www/html/frontend/. I'm calling my request using fetch api from Vue and this is the base url of all request: import {defineStore} from 'pinia' export const useGeneralConfig = defineStore('generalConfig',{ state: () => { return { BASE_URL : "http://127.0.0.1:6000/api" } } }) I'm using caddy as server and here is the Caddyfile content: :80 root * /var/www/html/frontend/dist encode gzip zstd try_files {path} {path}/ /index.html reverse_proxy /api/* localhost:6000 file_server Now when I enter X.X.X.X (my VPS IP address) in the browser I can see that Vue app is serving but it does not communicate to DRF back-end and I cant see any request log in my backend logs. I run the backend like this: python3 manage.py runserver 6000 And here is the output: System check identified no issues (0 silenced). February 26, 2023 - 02:23:18 Django version 4.1.5, using settings 'project_name.settings' Starting development server at http://127.0.0.1:6000/ Quit the server with CTRL-BREAK. Any help would be appreciated. -
django bootstrap select element one column
i use djando and bootstrap. I use a form with a method POST and "select" option. I try to select elements belong to a table. I can see the database elements, but elements it's not showing in a column, they showing in a row (one consecutive to another). I try to figure what is the error, but i not fix it. It's my firts time with django and python;-)! Thanks in advance! Elements in a row The code: ` <form method="POST" action="{% url 'consorcio' %}">{% csrf_token %} <div class="row"> <div class="col"> <input type="text" class="form-control" id="name_consorcio" required name="name_consorcio" placeholder="Nombre Consorcio:"><br/> </div> <div class="col"> <input type="text" class="form-control" id="direccion_consorcio" required name="direccion_consorcio" placeholder="Direccion Consorcio:"><br/> </div> <div class="col"> <input type="text" class="form-control" id="cuit" required name="cuit" placeholder="CUIT:"><br/> </div> <div class="col"> <select class="form-select"> <option selected>Seleccionar Administracion: <option value="1"> <ul> {% for a in all_consorcio %} <li>{{ a.administracion.name_administracion }}</li> {% endfor %} </ul> </option> </option> </select> </div> </div> <input type="submit" class="btn btn-primary" value="Guardar">` </form><br> I tried to modificate the blucle for and add other stuff, like and , etc... -
Override default behavior of def destroy() in ModelViewSet to allow query parameters
I understand the intended DELETE behavior in DRF ModelViewSet is that a pk must be specified. For example, DELETE /api/document/1/. However, I'm trying to implement DELETE using query parameters which I understand should be acceptable in a REST API. For example, DELETE /api/document/?product_id=1, which would DELETE all documents associated with a product_id. When you pass query parameters to Django with DELETE, it returns: { "detail": "Method \"DELETE\" not allowed." } Remove the parameters and specify a pk and it works fine. If that is the case, if you are wanting to delete all documents related to a product_id, you'd first need to query to get the list of documents related to that product_id, iterate through it and DELETE on each pk. Seems like there should be a better way. I'm testing if I can even override the destroy(), grab the query parameters, and do what I need to do: class DocumentToProductViewSet(viewsets.ModelViewSet): queryset = DocumentToProduct.objects.all() serializer_class = DocumentToProductSerializer def destroy(self, request): print('destroy test') pass The request doesn't reach the method before I get that error since 'destroy test' doesn't print out in the console. I'm using SimpleRouter() which is likely where the error is generated from, and have also have tried … -
How do you efficiently load 10 million rows, run a function on them and then write some changes back to the db
Say you have 10 million rows in a db table represented by a django model. How do you efficiently load all of these, run a function on them and then write some changes back to the db. I am trying to find the correct course of action when dealing with such a problem -
chained select_related from many tables in django
Here I have the following models: class GenericUserData(AbstractUser): username = None id = models.UUIDField(primary_key=True, default=uuid4, editable=False) email = models.EmailField(max_length=100, unique=True) date_joined = models.DateTimeField(auto_now_add=True) .... class NormalSellerDetails(models.Model): userid = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True,db_column='UserID', unique=True) # from table user. mobileauthenticationenabled = models.IntegerField(db_column='MobileAuthenticationEnabled', default=0) # Field name made lowercase. ..... class UserBan(models.Model): user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True,db_column='UserID', unique=True) # from table user. from_date = models.DateField(null=False) and I want to perform a select like the following: SELECT * FROM genericuserdata, normalsellerdetails, userban WHERE genericuserdata.id = normalsellerdetails.UserID AND genericuserdata.id = userban.UserID I also have there seializers: class GenericUserRetrievalSerializer(serializers.ModelSerializer): class Meta: model = GenericUserData fields = [ "email", "first_name", 'last_name', 'is_seller', 'is_normal', 'is_emp', 'is_male', 'bdate'] class AccountNormalSerializer(serializers.ModelSerializer): userid = GenericUserRetrievalSerializer(many=False) class Meta: model = NormalSellerDetails fields = ['mobileauthenticationenabled', 'emailauthenticationenabled', 'mobilephone', 'profilepiclink', 'userid', 'userban' ] I could link between GenericUserData, and NormalSellerDetails by doing so: class NormalAccountList(generics.ListAPIView): serializer_class = AccountNormalSerializer def get_queryset(self): queryset = NormalSellerDetails.objects.all().select_related('userid') return queryset but I couldn't link between all three into one query, noting model NormalSellerDetails relates to GenericUserData which in turn has an inverse relation to UserBan My question is: 1- how to do that link? 2- userban table has rows for users who only are banned, How do create an output field … -
Getting an error in entering time when default value for time is given in Django
I made the below Django form. class SearchTimeSlotsForm(forms.Form): available_from = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), initial=time(0)) available_till = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), initial=time(23,59,59)) As you can see that I have given default value to the form but when entering a value, I am getting an error 'Please select a valid value'. Here is the screen shot of the error. Please note the user can enter any time, it has got nothing to do with the default value or its format so the above error should not come. Can someone tell me why it is coming? -
How do i implement a web app based on keystroke dynamics authentification
I am interested in coding an application that uses keystroke dynamics recognition for user authentication. I would like to build a web-based application using Python and Django. What are the key steps involved in building such an application, and what are the best practices for implementing keystroke dynamics recognition in web-based applications? Are there any specific libraries or frameworks that I should use? Any tutorials or resources where i could start would be greatly appreciated. -
Dynamic Data sent back to views.py in POST request Django
I have a dynamically generatyed HTML file that displays quizzes for a class that was gathered from an API request. Within this page, I have a scan button that will scan the selected quiz and kick off a python script on the backend. When the scan button is clicked, I need that specific class data sent back to my views file so I can kick off an API request on the back end for the scan. The issue I am having is that when the scan button is pressed, only the last element in the list (of the dynamically generated html page) is sent back to my views.py file. How do I set up my POST reuquest on button click to handle the dynamic data so the data that gets sent back is correct as. Images below will show what is happening. Image of html page Dynamic HTML page code <div class="container"> <form method="post"> {% csrf_token %} {% for quiz in assignment_data %} <div class="assignment hide-content"> <div class="row assignment-header"> <div class="col">{{quiz.title}}</div> <div class="col">published: {{quiz.published}}</div> <div class="col">Questions: {{quiz.question_count}}</div> <div class="col-sm toggle-col"> <i class="toggle-drop-icon drop-icon-down fa-sharp fa-solid fa-caret-down"></i> <i class="toggle-drop-icon drop-icon-up fa-sharp fa-solid fa-caret-up"></i> </div> </div> <div class="row assignment-content"> <div class="col"> <button … -
Can not validate the AuthForm
I'm developing the Login view of my app, in order to do that I used the Django's built-in authentication form, but when I try to validate the form it returns False and I don't know why. I let here my code... models.py class User(AbstractUser): ''' Model that represents a user in the database ''' first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) username = models.CharField(max_length=50, null=False, blank=False, unique=True) email = models.EmailField(null=False, blank=False, unique=True) password1 = models.CharField(max_length=25) password2 = models.CharField(max_length=25) birthday = models.DateField(null=False, blank=False) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.first_name}: {self.email}' forms.py class AuthForm(AuthenticationForm): ''' Form that uses built-in AuthenticationForm to handel user auth ''' email = forms.EmailField(required=True, widget=forms.TextInput(attrs={ 'placeholder': 'Correo electrónico', 'name': 'email', 'type': 'email', 'class': 'form-control' })) password1 = forms.CharField(max_length=25, required=True, widget=forms.PasswordInput(attrs={ 'placeholder': 'Contraseña', 'name': 'password1', 'type': 'password', 'class': 'form-control' })) class Meta: model = User fields = ('email','password1', ) login.html <form action="{% url 'users:login' %}" method="post"> {% csrf_token %} <div class="mb-3">{{ form.email }}</div> <div class="mb-3">{{ form.password1 }}</div> <div class="mb-3"><button class="btn btn-primary shadow d-block w-100" type="submit">Iniciar sesión</button></div> <p class="text-muted">Recuperar contraseña</p> </form> views.py def login_page(request): if request.method == 'POST': form = AuthForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user … -
How to put description under fields in Django
fieldsets = [ ('ALERT', { 'classes': ['collapse'], 'fields': [ ('field_1'), ('field_2'), ('field_3'), ], 'description': "Some helpful text", }), ('NEXT', { 'classes': ['collapse'], 'fields': [ ('field_5'), ('field_6'), ('field_7'), ], 'description': "Some helpful text", }), ] When using this code, the description text is placed above the fields. I need to place description text below the fields. Please advise how to move the text down or maybe there is another way to place the description text after the fields. I'm trying to add descriptive text to each section, but it appears at the top of the fields and interferes with filling in the fields. But in all the options that I used, the text is placed above the fields and I do not know how to place it below, below the fields. -
Handling header form in Django
I have some pages on my blog site: news, explore and my_profile. On header i have a form to add new article. How can I to RENDER and HANDLE a form in header on ANY page? Because any page includes header. I tried to register new jinja tag with my form: # myapp/templatetags/my_tags.py from django import template from myapp.forms import ArticleForm register = template.Library() @register.simple_tag def article_form(): return ArticleForm() But I don't think it's a good idea. -
Django - No module named 'webapp'
Settings.py INSTALLED_APPS = [ 'webapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Apps.py class WebappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'webapp' Error ModuleNotFoundError: No module named 'webapp' Am I missing something here? Same result when using mysite.webapp... -
Send 'User' name and 'Form content' in email notification
I'm trying to get the form to send an email notification of the 'Users' username and content of the 'Comment' its self. I have managed to get the title of the post working but nothing else. Need a little help. Thanks in advance Views def ViewPost(request, slug): try: post = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: print("Blog with this slug does not exist") post = None comments = post.comments.filter(status=True) user_comment = None if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.post = post user_comment.user = request.user user_comment.save() messages.success(request, ("Comment successfully posted, thank you...")) send_mail('You have recieved a comment on a blog post', post.title, post.user # not working , #reference comment here [ 'codewithdmh@gmail.com']) else: comment_form = CommentForm() return render(request, 'mhpapp/view-post.html', {'post': post, 'slug': slug, 'comments': user_comment, 'comments': comments, 'comment_form': comment_form}) Comment Model class BlogComment(models.Model): post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE) user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, default="",) name = models.CharField('Name',max_length=100, default="") text = models.TextField('Comment',max_length=1000, default="") date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ("date",) def __str__(self): return '%s -> %s'%(self.post.title, self.user) -
Run two commands, one after the other, on digitalocean app platform
I want to automatically start huey (a background task manager) going when I deploy a Django site on Digital Ocean's "App" platform. It provides a "run command" box where one can input commands when deploying (after the server is built). I cannot work out why this isn't working: gunicorn --worker-tmp-dir /dev/shm core.wsgi; python manage.py run_huey I've tried the "&&" separator but that doesn't work either. The "python manage.py run_huey" command just doesn't get run. -
Why am I getting 500:INTERNAL_SERVER_ERROR on vercel when trying to deploy a django app?
Basically, I am trying to deploy a django project to vercel using the default settings, however I get this error when doing so 500: INTERNAL_SERVER_ERROR Code: FUNCTION_INVOCATION_FAILED ID: iad1::kgz72-1677350120288-41179987b8c3 The vercel website simply tells me to read the logs, The logs only provide the follwoing message [GET] /favicon.ico 12:35:20:58 [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' Traceback (most recent call last): Heres the repository I am trying to deploy -
Reverse query clash
I am trying to make a chat system where a user can create a chat and become the owner of the said chat and the chat can have other users inside. class UserProfile(models.Model): #username = models.CharField(max_length=30, unique=True, default=User.username)# django creates username automatically? user = models.OneToOneField(DjangoUser, on_delete=models.CASCADE) display_name = models.CharField(max_length=50) picture = models.ImageField(upload_to = 'profile_images', blank=True) def __str__(self): return self.user.username Thats my user model class Chat(models.Model): name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=240) users = models.ManyToManyField(UserProfile) owner = models.OneToOneField(UserProfile, on_delete = models.CASCADE) def __str__(self): return self.name Thats the chat model -
The error " Could not parse the remainder: '=' from '=' "
This error is displayed in the line <form action="{% url "make_order" product_id=product.id %}" method-="POST"> I do not know how to fix it, because everything seems right I hope you can help me {% extends "core/base_layout.html" %} {% load static %} {% block meta %} <link rel="stylesheet" href="{%static 'styles/make_order.css'%}"> {% endblock %} {% block content %} <form action="{% url "make_order" product_id=product.id %}" method-="POST"> {{ error }} {% for input in form %} <div> <label for="{{ input.id_for_label }}"> {{input.label}}</label> </div> {{ input }} <p> {{ input.errors }} </p> {% endfor %} </form> {% endblock %} -
Django Filterset object is not callable
I'm trying to use a custom filterset class with DjangoFilterBackend to filter my products by some details that are different based on their category, but I get the error "'ProductFilter' object is not callable". My filtering works fine when I don't limit the choices based on chosen category, but when I try limitting them I get the above error. these are my models: class Category(models.Model): title = models.CharField(max_length=50) desc = models.TextField(default='', blank=True) slug = models.SlugField() class ProductEnumProperty(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='product_enum_properties') name = models.CharField(max_length=20) def __str__(self): return self.name class ProductPropertyState(models.Model): property = models.ForeignKey(ProductEnumProperty, on_delete=models.CASCADE, related_name='product_property_states') state = models.CharField(max_length=20) def __str__(self): return f'{self.property.name} - {self.state}' class Product(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') desc = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) props = models.ManyToManyField(ProductPropertyState, ) For example: Category: jeans---------->ProductEnumProperty:flyer type----------->(ProductPropertyStates:(1-buttons 2-zipper)) filters.py: class ProductFilter(FilterSet): class Meta: model = Product fields = { 'price': ['gt', 'lt'], 'props': ['exact'], } def __init__(self, *args, **kwargs): category_slug = kwargs['category_slug'] del kwargs['category_slug'] super(ProductFilter, self).__init__() self.filters['props'].extra.update( {'queryset': ProductPropertyState.objects.filter(property__category__slug=category_slug)}) views.py: class ProductByCategory(ListAPIView): def get_category(self): category_slug = self.kwargs.get('category_slug') return category_slug serializer_class = ProductMiniSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter(category_slug=get_category) search_fields = ['title', 'desc', 'category__title'] ordering_fields = ['price', … -
Django RichTextUploadingField in ckeditor related issue
I am facing a problem in RichtextEditor when I used RichTextUploadingField is field in model then I add data to admin panel and after calling by api it is showing this image after api call but the problem is frontend developer can't use it to show this image. Is there any problem in my code? ` INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = "uploads/" STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] Media MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' ` when add data through admin panel in rich text editor rich text editor look like this from postman "body_with_image": "<p><img alt=\"\" src=\"/media/uploads/2023/02/25/mountains-3840x2160.jpg\" style=\"height:2160px; width:3840px\" /></p>" Is there any correction needed in my code -
How to change Django default date format
I want to change the default Django date format from year-day-month to day-month-year format I tried adding DATE_INPUT_FORMATS=[‘%d.%m.%Y] in settings.Py file but the changes still doesn’t reflect while using the form -
Django. POST request after reloading a page. Sign up form
When user enters incorrect data in form, he gets errors. If after that user reloads a page, he gets the same page, the same form with the same fields, errors. I don't know why after reloading a page request is POST. Every time after sending form, when I reload page with form I send a POST request. views.py from django.shortcuts import render from django.shortcuts import render, redirect from .forms import LogInForm, SignUpForm from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.hashers import make_password from django.contrib.auth import authenticate, logout, login as auth_login from django.contrib import messages import os import shutil # Create your views here. @login_required def index(request): return render(request, 'index.html') def login(request): logInForm = LogInForm() if request.method == 'POST': form = LogInForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate( username=cd['username'], password=cd['password']) if user is not None: auth_login(request, user) return redirect("main") else: messages.error(request, "Invalid login or password") return redirect('login') else: form = LogInForm() else: return render(request, 'logIn.html', {"form": logInForm}) def signUp(request): def createFolder(username): toFolder = "jsons/" + username fromFolder = "scripts/" os.mkdir(toFolder) toFolder = "jsons/" + username + '/scripts' os.mkdir(toFolder) os.mkdir("jsons/" + username + "/messages") if (os.path.exists(fromFolder) and os.path.exists(toFolder)): for file in os.listdir(fromFolder): if os.path.isfile(os.path.join(fromFolder, file)): shutil.copy(os.path.join(fromFolder, file), os.path.join(toFolder, file)) if os.path.isdir(os.path.join(fromFolder, … -
can't multiply sequence by non-int of type 'decimal.Decimal'
I have a cart in my project which was working fine but I don't know what happened that now when adding an item to my cart this error keeps coming up: TypeError at /cart/ can't multiply sequence by non-int of type 'decimal.Decimal' this is my form: class AddToCartProductForm(forms.Form): QUANTITY_CHOICES=[(i,str(i)) for i in range(1,30)] quantity=forms.TypedChoiceField(choices=QUANTITY_CHOICES,coerce=int) inplace=forms.BooleanField(required=False,widget=forms.HiddenInput) this is my add function in card class: def add(self,post,quantity=1,replace_current_quantity=False): post_id=str(post.id) if post_id not in self.cart: self.cart[post_id]={'quantity':quantity} if replace_current_quantity: self.cart[post_id]['quantity']=quantity else: self.cart[post_id]['quantity']+=quantity self.save() and this is my view: def add_to_cart_view(request,post_id): cart=Cart(request) post=get_object_or_404(Posts,id=post_id) form=AddToCartProductForm(request.POST) if form.is_valid(): cleaned_data=form.cleaned_data quantity=cleaned_data['quantity'] cart.add(post,quantity,replace_current_quantity=cleaned_data['inplace']) else: print(form.errors.as_data()) return redirect('cart:cart_detail') I tried giving the quantity a default int value in case it is null but didn't work. -
Adding simple cart item in Cart in Django
Being completely new to Django, I want to add simple cart item in Django. And also want to retrieve this cart items in Get request. What I will send in POST request is: {"item":"itemName","price":"100"} This should get stored for the current user. And when I make GET request, I want JSON array containing all previously stored items. [{"item":"itemName1","price":"100"}, {"item":"itemName2","price":"200"}, {"item":"itemName3","price":"300"}] If anyone can put very simple code in terms of views and models, that would be very helpful. In examples on stackoverflow, I saw multiple posts. Some use complex Product object, some use .html forms etc. But I need to store simple objects and get these objects as JSON. Any working code help?