Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
USSD on Django System
Am developing an application that will used ussd to query the database.The system is developed using django framework.There is no much information on the topic.Any infomation would be appreciated. regards -
How can solve profilepage key error in Json django deploy in web server
I have a problem that , my script run at localhost correctly but at cpanel host it doesn't run : problematic script : enter code here from django.shortcuts import render from django.http import HttpResponse import json import re import requests def home(request): return render(request,'home.html',{'name':'Shahin '}) def add(request): val = str(request.POST['num']) response = requests.get('https://www.instagram.com/' + val) json_match = re.search(r'window\._sharedData = (.*);</script>', response.text) profile_json = json.loads(json_match.group(1))['entry_data']['ProfilePage'][0]['graphql']['user'] res1 = profile_json['edge_followed_by']['count'] res2 = profile_json['edge_follow']['count'] res3 = profile_json['edge_owner_to_timeline_media']['count'] res4 = profile_json['is_private'] res5 = profile_json['is_business_account'] res6 = profile_json['business_category_name'] res7 = profile_json['is_verified'] res8 = profile_json['is_joined_recently'] res9 = profile_json['profile_pic_url_hd'] return render(request,'result.html',{'result1': res1 ,'result2': res2,'result3': res3,'result4': res4,'result5': res5,'result6': res6,'result7': res7,'result8': res8,'result9': res9,'val' : val }) and error : Exception Type: KeyError Exception Value: 'ProfilePage' Exception Location: /home/maadplat/instagram/instagram/views.py, line 14, in add Python Executable: /home/maadplat/virtualenv/instagram/3.7/bin/python3.7 error image : [1]: https://i.stack.imgur.com/48KZk.jpg -
Exception Value: join() argument must be str, bytes, or os.PathLike object, not 'function'
TypeError at /polls/ join() argument must be str, bytes, or os.PathLike object, not 'function' Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 3.1 Exception Type: TypeError Exception Value: join() argument must be str, bytes, or os.PathLike object, not 'function' Exception Location: c:\users\lenovo\appdata\local\programs\python\python38-32\lib\genericpath.py, line 152, in _check_arg_types -
Create external user with Django Rest Framework?
I would like to create a external user for use my DRF API in his application. I am using Django Oauth Tookit for verfy my user (https://django-oauth-toolkit.readthedocs.io/) The idea is, when the external user is registered by form, after a manual verification, I would like to send it a Client_id and Secret_id for use my API in his application, with his credentials. The question is: How can I create an Django oauth Toolkit Application (api/o/application) for other user, with my superuser account? And not allow the access to this user for modify his Client_id and Secret_id and obviously, Admin or other Staff resources. It is Django Oauth Tookit the best way to do it? -
How can I print query set element in Django Template?
I have this code in my template file {{markets|getSpiderItem:spider.id}} Mysql has market_timezone and market_location and it connects to another table with spider_id so I filtered as follow: @register.filter def getSpiderItem(datas, spider_id): return datas.filter(spider=spider_id) I am getting this output: <QuerySet [{'market_timezone': 'Turkey', 'market_location': 'Nigde'}]> I want to print this QuerySet item on Django Template separately. This function has already 2 for loop so I want to print just 1 time. I don't wanna use for loop like this: {% for market in markets|getSpiderItem:spider.id %} I want something like this but I couldn't figure out: For Example: {{markets|getSpiderItem:spider.id|market_timezone}} # I don't know the true way. -
Getting error while executing a django application
After running the server i am getting error as as_view() takes 1 positional argument but 2 were given please have a look on below code and suggest me. enter code here -------------views--------- from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.generic import View class EmpdataCBV(View): def empdata(self, request,*args,**kwargs): mydic = { 'emp_no': 1, 'emp_name': 'Pavan', 'emp_contactno': 9004981121, 'emp_sal': 50000, 'emp_addr': 'Sakinaka' } return JsonResponse(mydic) --------------url----------- from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), path('jsonresponseCBV/', views.EmpdataCBV.as_view), ] -
I get an error when setting a Django date field
I'm trying to set a date field to a constant date. My "models.py" with the date field: class Foo(models.Model): bar = models.DateField() In my view: import datetime from app.models import Foo foo = Foo(bar=datetime.date('1/1/2021')) The error: Exception Type: TypeError Exception Value: an integer is required (got type str) -
Duplicate UUID if we enter a new input from html?
getting error- i saved one form from html into my database while when i tried saving the next it gave me this error- IntegrityError at customer (1062, "Duplicate entry 'ad138e46-edc0-11va-b065-a41g7252ecb4'' for key 'customer.PRIMARY'") kindly explain my uuid in models.py is - class customer(models.Model): customerid = models.CharField(default=str(uuid.uuid4()), max_length=500, primary_key=True) kindly help -
Problem with request.method in django which is not recognising POST instead it is showing GET as request method
I was doing some practical with django for Post and Get request and some security related stuff related to urls so I made a form in a html file in which I have used method as post and when it is going inside the views template then it is showing my method as GET I am not able to figure it out so please solve my issue thank you! I am attaching screenshot with this Post for your reference. This code is for my form page in which I have used method as post I have attached my 'check function' in which it is always going to the else block and not if block Here I have attached my browser screen which shows that my method is using GET request Code(HTML) :- {% block body %} <form action="check" method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock body %} Code (Python) :- def check(request): if request.method == 'POST': return HttpResponse("Now url is not having your … -
Django oscar custom benefits does not work
I am building a commercial app using Django and Django-oscar and I am trying to create a custom benefit. I have read Oscar's documentation here and I have also found this relative question in Stack Overflow. I have forked Oscar's offer app and created a benefits.py file where I want to put my custom benefit. I also have change the INSTALLED_APPS setting to include my offer app and not Oscar's default. The problem is that Oscar's doesn't see the benefits.py file no matter what I try. At first I thought that something is wrong with my custom Benefit Class but I tried using Oscar's example and that didn't work either. Then I wrote a piece of code designed to fail (for example a variable which had never been assigned a value to) but it didn't so I am thinking that the file is never accessed. My installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.postgres', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.flatpages', # wagtail apps 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail_modeltranslation', 'wagtail_modeltranslation.makemigrations', 'wagtail_modeltranslation.migrate', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'newsletter', 'stentor', 'consent', 'banners', 'banners.dashboard', 'contact_form', 'faq', 'faq.dashboard', 'pages', 'blog', 'oscar', 'oscar.apps.analytics', 'oscar.apps.address', 'oscar.apps.partner', 'oscar.apps.payment', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', … -
Empty M2M data if using prefetch_related django
i'm using Django with DRF, and i stucked on a N+1 problem. So, i trying to use prefetch_related now, and i have some problems with it. prefetch_related returns empty queryset in any situation. I'm using: Django 3.0.7 Djongo (Django DB Backend for MongoDB) DRF (latest version) DRF Test query @api_view(['GET']) @permission_classes([AllowAny]) def test_prefetch(request): users = User.objects.prefetch_related('roles', 'badges').all() users = UserPromptSerializer(users, many=True).data return Response(users, status=200) Models: class UserRoles(models.Model): user = models.ForeignKey(to="User", on_delete=models.DO_NOTHING, default=None) role_type = models.CharField(default="", max_length=256) given_at = models.DateTimeField(default=api.functions.get_local_time) expires_at = models.DateTimeField(default=api.functions.get_local_time, null=True) def __str__(self): return self.role_type class User(AbstractBaseUser, PermissionsMixin): .... roles = models.ManyToManyField(UserRoles, symmetrical=True) Getting roles field through all() function: def get_user_badges(clazz, obj): roles = [] try: roles = list(obj.roles.all()) except UserRoles.DoesNotExist: roles = [] print(obj._prefetched_objects_cache) # returns {"roles": []} print(roles) # returns [] -
Dajngo inline formset and errors for required field
This is my model: class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) My views.py: def event_edit_view(request, id): event = get_object_or_404(Event, id=id) #MyOtherForm instantiated by event DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), widgets={ 'venue': s2forms.Select2Widget(), 'start_date_time': CalendarWidget(), form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id)) if request.method == "POST": if MyOtherForm.is_valid() and form_date_event.is_valid(): MyOtherForm.save() form_date_event.save() return redirect('my-events') else: raise forms.ValidationError(form_date_event.errors) #? context = { [other forms...] 'form_date_event': form_date_event, } return render(request, "events/template.html", context) And my template.html: <table id="dateEvent"> <thead> <th>Venue</th> <th>Date and time</th> <th>Link</th> <th>Link description</th> </thead> <tbody id='date_body'> {{ form_date_event.management_form }} {% for formDate in form_date_event.forms %} <tr class="form-row-dateEvent" style='display:table-row;'> <td>{{formDate.venue}}<br> <a href="javascript:void(0)" data-open="addVenue" onclick="sessionStorage.setItem('venueField', 'id_dateEvent-{{forloop.counter0}}-venue'); document.getElementById('addVenueForm').reset(); document.getElementById('errorVenue').innerText = '';">Add a new venue</a></td> <td>{{ formDate.start_date_time}}</td> <td>{{formDate.link}} {{formDate.this_composition}}</td> <td>{{formDate.id}}{{formDate.link_description}}</td> </tr> {% endfor %} </tbody> </table> Now, how can I enforce the user to fill in both venue and the date? As it is now if a user fills in the venue field and leaves the corresponding date field empty, Django redirects the user to an ugly yellow page ValidationError at /private/event-edit/1150/ ['This field is required.'] Request Method: POST Request URL: .../event-edit/1150/ Django Version: 3.1 Exception Type: ValidationError Exception Value: ['This … -
Incorrect padding. Django with Google Chrome
I asked the question yesterday, but removed it, because it seems I gave too few information and explained the question poorly. But it is kind of solved, but solutions relate to different problems. I just implemented ideas towards this particular problem and I would like to share it, so it might help to somebody out there. So the problem I bumped into is: My site is based on the Django app, when I use Google Chrome it interpret it as (as I understand) 32 bit, meanwhile it is 64 bit (I'm not sure if I'm giving here right description of the problem, but general idea is that) and Google Chrome fails and gives following message: Incorrect padding What I have done to fix the problem. The solution based on: https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770 So I went into: /usr/local/lib/python3.8/base64.py Function name is b64decode, it is on the line 87. It looks like: def b64decode(s, altchars=None, validate=False): """Decode the Base64 encoded bytes-like object or ASCII string s. Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. The result is returned as a bytes object. A binascii.Error is raised … -
How to create a fill-in-the-blank text in a survey? Got it vertically but not horizontally
I do a survey and want to create a fill-in-the-blank text. (How it looks right now). I use Django and CSS and can display it vertically, but how can I display my text and my IntegerFields horizontally within the same sentence? Since I use CSS I would like to code it within my forms.py file and not the template file. Anybody has an idea on how to do it? Thanks! forms.py class SurveyPolicy(forms.Form): policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.desc = "example" self.helper.layout = Layout( Fieldset( "<hr><h6 style='color: #2D2D2D; font-family: Arial;'>Die Maßnahmen sollten zu</h5>", Div('policy6b', css_class='form-group row-ml-0 mb-0'), ), Fieldset( "<h6 style='color: #2D2D2D; font-family: Arial;'>% durch eine Abgabe auf konventionelle Energieträger wie z.B. Erdgas finanziert werden - schließlich sollten Leute, die mehr CO2-Ausstoß verursachen auch mehr bezahlen.</h5>", ), [...] -
DRF HTML rendering
I recently finished Django doc. Now I am trying to recreate it with DRF. I am struggling with HTML rendering. Doing this code i have following mistake: object of type 'type' has no len() This how it look in Django(it works): class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] This is my code in DRF: class IndexViewDRF(APIView): renderer_classes = TemplateHTMLRenderer template_name = 'polls/index.html' def get(self, request): queryset = self.get_queryset() return Response({'latest_question_list': queryset}) @staticmethod def get_queryset(): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] HTML file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My$ite</title> {% load static%} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> </head> <body> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </body> </html> P.S.1) Am i using method get_queryset correcly? Is there a better way? 2) Am i need to use Serializers here, as it is DRF or i am confused in using Serializers? 3) As i understood, there is no way to use generics views here? P.P.S I hope this is enough information. -
Django: call a view function via a button click
I want to call a view function resign_game by clicking an html button. Here is what i have tried after reading some Stackoverflow posts: <form action="{% url 'resign_game' %}" method="POST"> <button type="button">RESIGN</button> </form> Here is what I have in my urls.py: path('resign_game/', views.resign_current_game, name='resign_game') However, the view function was never called after I clicked the button. I would appreciate your suggestions. Thanks! -
Django: Image field does not display and is not uploaded into target repo
I'm new to Django and got this problem: ImageField does not display (while other fields display well) When uploading, new image is not uploaded into target repo What I have: Target repo containing default image and future upload images. Repo name: media. Repo structure: on the same level with manage.py Code in settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Code in models.py class CustomUser(AbstractUser): image = models.ImageField(default='default.jpg', upload_to='images/', blank=True) phone_number = models.CharField(max_length=12, null=True) bio = models.TextField(null=True) def __str__(self): return self.username Code in forms.py: class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ['username', 'email', 'image', 'phone_number', 'bio'] Code in html: {% extends 'base.html' %} {% block content %} <h2>User Account View</h2> <div id="User"> <img src="media/{{ User.image }}"> <ul> <li>{{ User.username }}</li> <li>{{ User.email }}</li> <li>{{ User.phone_number }}</li> <li>{{ User.bio }}</li> </ul> </div> {% endblock %} I have researched on many sources and asked few mentors, but still have no luck. Please help if you can Cheers -
How to query in a list of values for text search in Django?
This is my modal description. class video_details(models.Model): video_id = models.CharField(max_length=50, unique=True) publishedAt = models.TextField() video_title = models.TextField(blank=True) video_desc = models.TextField(blank=True) thumbnail_url = models.TextField(blank=True) class Meta: db_table = 'VIDEO_DETAILS' I have to perform a search query based on a list of elements. response = video_details.objects.filter(Q(video_desc__incontains=['Control', 'simular'])| Q(video_title__incontains=['simular', 'Control'])) in more detail, I have to return those elements which are having video_desc and video_title as a substring from the list. sample values { "id": 91, "video_id": "Tr9-8tFVUOE", "publishedAt": "2020-09-02T18:20:59Z", "video_title": "b'Control Indirecto de un Motor CD con Python | Z Dynamics'", "video_desc": "b'Pyhon es una gran herramienta para simular sistemas din\\\\xe1micos. En este v\\\\xeddeo te mostramos c\\\\xf3mo simular el control de un motor de corriente directa - M\\\\xe1s ...'", "thumbnail_url": "https://i.ytimg.com/vi/Tr9-8tFVUOE/default.jpg" }, -
Django: Item "None" of "Optional[Any]" has no attribute "start_at"
I have this method within my PeriodManager model: def period_at(self, as_at, allow_erroneous=True) -> "Period": """ Return the period at the provided datetime. """ periods = ( self.get_queryset() .filter( Q(end_at__isnull=True) | Q(end_at__gt=as_at), start_at__lte=as_at, ) .order_by("-end_at") ) num_periods = len(periods) if num_periods == 0: raise self.model.DoesNotExist elif num_periods == 1: supply_period = supply_periods.first() elif num_periods == 2: if periods.first().start_at == periods.last().end_at: period = periods.first() else: raise self.model.MultipleObjectsReturned return period The "Period" model is defined as follows, related through a Foreign Key to the Property model: class Period(models.Model): property = models.ForeignKey( "properties.Property", related_name="periods", on_delete=models.CASCADE ) start_at = models.DateTimeField("Starts at") end_at = models.DateTimeField("Ends at", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) I am getting these errors from the python type checker: error: Item "None" of "Optional[Any]" has no attribute "end_at" [union-attr] error: Item "None" of "Optional[Any]" has no attribute "start_at" [union-attr] error: Incompatible return value type (got "Optional[Any]", expected "Period") [return-value] But don't understand why, as by nature the queryset 'periods' will be returning only instances of Period, which all have the attributes 'start_at' and 'end_at'. -
Why is it showing "I/O operation on closed file" in Django?
I am working on a project in which a user uploads a file from the front-end and without storing the file it goes to the backend where some processing is done and results are returned back. Here are the functions which are dealing these works in the views.py file: def midpro(request, *args): global file if(request.method == 'POST'): try: file = request.FILES['data'] except: print("No File") if(file!=None): if(file.name[-1:-4:-1]!="vsc"): return render(request, 'mapp/nocsv.html') else: return linml(request) return render(request, 'mapp/nofile.html') def linml(request, *args): global retdata global file ans = list() col = ['D1', 'D2'] if(file!=None): ins = mapp.Mapp(file) retdata = ins.linml() for i in zip(col, retdata): ans.append(i) context = { 'ans':ans, 'data':file } return render(request, 'mapp/linml.html', context) the code inside Mapp class is class Mapp: def __init__(self, file): self.file = file def linml(self, *args): data = pd.read_csv(self.file) data = np.array(data) return([np.mean(data), np.var(data)]) pd is the alias for pandas library. np is the alias for numpy library. the error I/O operation on closed file is occuring in data = pd.read_csv(self.file) step. Can anyone tell me how can i resolve this issue? Also if I try to explicitly open the file with: with open(self.file) as f: It shows expected str, bytes or os.PathLike object, not InMemoryUploadedFile error, … -
How can we perform left without foreign key in Django ORM
I have 4 models in django as follows, I am facing problem in left join because there is not foreign key. class A(Model): id = models.BigAutoField(primary_key=True) col1 = models.CharField(max_length=20, default='', blank=False, null=False) col2 = models.CharField(max_length=20, default='', blank=False, null=False) ... class Meta: db_table = "A" constraints = [ models.UniqueConstraint(fields= ['col1','col2'], name='UX_Col1Col2'), ] class B(Model): id = models.BigAutoField(primary_key=True) col1 = models.CharField(max_length=150, blank=False, null=False) ... class Meta: constraints = [ models.UniqueConstraint(fields=["so_number"], name='UX_SOHeader'), ] class C(Model): id = models.BigAutoField(primary_key=True) col1 = models.ForeignKey(B, on_delete=models.CASCADE, blank=False, null=False) col2 = models.ForeignKey(D, on_delete=models.DO_NOTHING, blank=False, null=False) ... class D(Model): id = models.BigAutoField(primary_key=True) col1 = models.ForeignKey(B, on_delete=models.CASCADE, blank=False, null=False) ... Now my sql query is SELECT (some columns) from B inner join C on B.id=C.id inner join D on D.id=D.id left join A on A.col=B.col and A.col=C.Col I am facing problem while doing left join I am doing like this B.objects.select_related('C','D') How can I do left join -
How to perform number of days calculation in Django related field query
I have 2 models: class Assets(models.Model): assetMake = models.CharField(max_length=50,blank=True,) assetModel = models.CharField(max_length=50,blank=True,) class Maintenance(models.Model): assetID = models.ForeignKey(Assets, on_delete=models.CASCADE) dateRequested = models.DateTimeField(null=True, blank=True) dateCompleted = models.DateTimeField(null=True, blank=True) complete = models.BooleanField(default = False) I want to have a view that displays all the Assets in order of when they were last maintained (dateCompleted). Which this accomplishes below: from django.db.models import Max Assets.objects.annotate( last_modified=Max('maintenance__dateCompleted') ).order_by('-last_modified') But how can I calculate the number of days from dateCompleted to now so that I can display this value as well. Something like: Assets.objects.annotate( last_modified=Max('maintenance__dateCompleted'), days = ((timezone.now() - maintenance__dateCompleted).days ).order_by('-last_modified') -
Multiple Django projects hosting in iis
Im using django webframework for web application and iis for the hosting purpose.I have created multiple projects in django.On hosting,I found that, they three ways for hosting multiple sites which is, 1)By Port 2)Different header 3)Different ip what i want is hosting my project as below, project1 ---- mysite.com/prj1 project2 ---- mysite.com/prj2 project3 ---- mysite.com/prj3 Note that mysite.com is my domain. prj1 is my first poject and others respectively. Can somebody give me an idea either, 1)Consolidate my project (or) 2)hosting as shown above in iis. Thanks in advance.Please help me to sort out. -
Return list of values of one column grouped by another column in Django viewset
Let's say I have a model: class Entry(models.Model): content = models.CharField(max_length=140) email = models.EmailField() upload_date = models.DateTimeField(default=timezone.now) class Meta: db_table = 'entries' What I want to achieve is the viewset to return list of content and upload_date values per single email (since many entries can have the same email value), like that: [ { "email": "address1@test.test", "entries": [ { "upload_date": "2020-09-03", "content": "test content 1" }, { "upload_date": "2020-09-02", "content": "test content 2" }, ... ] }, { "email": "address2@test.test", "entries": [ { "upload_date": "2020-09-03", "content": "test content 11" }, { "upload_date": "2020-09-02", "content": "test content 12" }, ... ] }, ... ] I tried messing around with .values() and .annotate(), but with no luck. -
filter item by categories in django admin
i want to filter item by categories in my admin view when the order is placed and show it in admin and able to filter that or give staff user access to only specific categories here is my views class CategoryView(View): def get(self, *args, **kwargs): category = Category.objects.get(slug=self.kwargs['slug']) item = Item.objects.filter(category=category, is_active=True) context = { 'object_list': item, 'category_title': category, 'category_description': category.description, 'category_image': category.image } return render(self.request, "category.html", context) @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "Item qty was updated.") return redirect("core:product", slug=slug) else: order.items.add(order_item) messages.info(request, "Item was added to your cart.") return redirect("core:product", slug=slug) else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "Item was added to your cart.") return redirect("core:product", slug=slug) @login_required def remove_from_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_qs = Order.objects.filter( user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item = OrderItem.objects.filter( item=item, user=request.user, ordered=False )[0] order_item.quantity = 1 order.items.remove(order_item) order_item.delete() order_item.save() messages.info(request, "Item was removed from your cart.") return redirect("core:order-summary") else: # add a message saying the user dosent …