Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post working from build-in rest_framework UI (in browser) but not from Postman
while starting my backend project I've run into a problem and can't find a solution. I work with django and wanted to implement crud operations for one table named tutorials and these operations run great when I use the browser or build-in rest_framework UI from the browser but when I try the post request from postman (sending a json object) it gives me the 500 internal server error from postman this is my project structure , I have only one app called platforme : project structure This is the code in platforme/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from platforme import views urlpatterns = [ path('tutorials/',views.TutorialList.as_view()), path('tutorials/<int:pk>/',views.TutorialDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) This is the code in platforme/models.py , I only have one model from django.db import models # Create your models here. class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) This is platforme/serializers.py from rest_framework import serializers from platforme.models import Tutorial class TutorialSerializer(serializers.ModelSerializer): class Meta: model = Tutorial fields = ('id','title','description','published') And finally this is the platforme/views.py : from rest_framework import generics from rest_framework import mixins from platforme.models import Tutorial from platforme.serializers import TutorialSerializer class TutorialList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Tutorial.objects.all() serializer_class … -
Docker files to be ignored on .gitignore
I'm new to docker. I've finalized dockerizing a Django projet of mine. What files and/or folders should I add to my .gitginore before pushing the changes to the project? Or no files should be added? I'm not talking about my .dockerignore file. -
Django migrations problem: Field id expectet a number but got 'China'
I set a default value of Country field in Item model as 'China'. Then i tried migrate and i showed an error that should set a default value in each of field. I've done it but after next migrate command i got an error "Field id expecter a number but got 'China'", but i change a default value to '4'. P.S.: I don't use Model.objects.filter() anywhere. I just work with models only. It's my models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from slugger import AutoSlugField class Item(models.Model): title = models.CharField(max_length=128) price = models.DecimalField(max_digits=7, decimal_places=2, default='0') color = models.ForeignKey('Color', on_delete=CASCADE, default='White') category = models.ForeignKey('Category', on_delete=CASCADE, default='SOMECATEGORY') age = models.ForeignKey('Age', on_delete=CASCADE, default='0') description = models.CharField(max_length=5000, default='') in_stock = models.BooleanField(default=True) country = models.ForeignKey('Country', on_delete=CASCADE, default='4') # here was default value China slug = AutoSlugField(populate_from='title', default='') def __str__(self): return self.title class Color(models.Model): color = models.CharField(max_length=32) def __str__(self): return self.color class Category(models.Model): category = models.CharField(max_length=64) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.category class Country(models.Model): country = models.CharField(max_length=64) class Meta: verbose_name_plural = 'Countries' def __str__(self): return self.country class Age(models.Model): age = models.CharField(max_length=32) class Meta: verbose_name_plural = 'Ages' def __str__(self): return self.age -
How to export python list into excel file using xlwt?
Here I am trying to export python list to the excel file but it is not working correctly. The list will be dynamic. response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="excle_file.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('datas', cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['col1', 'col2', 'col3', 'col4', 'col5'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = [20, Decimal('50000.00'), Decimal('10.00'), Decimal('40000.00'), Decimal('90000.00'), 21, Decimal('31000.00'), Decimal('2000.00'), Decimal('41000.00'), Decimal('74000.00')] for i,e in enumerate(rows): ws.write(i,1, e) wb.save(response) return response I want response like this. col1 col2 col3 col4 col5 20 50000 10 40000 90000 21 31000 2000 41000 74000 Current response col1 col2 col3 col4 col5 20 50000 10 40000 90000 21 31000 .... Also I want to increase the size of the column based on the text? How it will be done ? -
How to add javascript variable to django model database
I want to insert this javascript variable into django model which look like this. It's a location info variable which has address, latitude, longitude and place name. placeInfo = { address: "address example" latlng: pa {La: 51.12508408777138, Ma: 1.3337612324096222} name: "name example" } The database model consists of Posts model and Place model is subordinated to the Posts model. I want to put placeInfo javascript variable to the Place model. from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) lat = models.CharField(max_length=25) lng = models.CharField(max_length=25) def __str__(self): return "{}".format(self.name) class Posts(models.Model): title = models.CharField(max_length=50, null=True) pick_date = models.DateField(null=True) create_date = models.DateField(auto_now=True, null=True) music = models.CharField(max_length=100, null=True) mood = models.CharField(max_length=50, null=True) description = models.CharField(max_length=300, null=True) image = models.ImageField(upload_to="images/", null=True) place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name="location") def __str__(self): return str(self.title) What I've searched until now is about AJAX handling but I'm not used to it so any help would be appreciated -
Getting ModuleNotFoundError in Django
Project Structure urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('login_user', views.login_user, name='login_user'), path('logout_user', views.logout_user, name='logout_user'), path('register_user', views.register_view, name='register_user'), path('dashboard', views.dashboard, name='dashboard'), ] chat_app2/views.py from django.contrib.auth import logout, authenticate, login from django.http import HttpResponse from django.shortcuts import render, redirect from chat_app2.account.forms import RegistrationForm def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect('homepage') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'register_user.html', context) settings.py AUTH_USER_MODEL = 'account.Account' # Application definition INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Error File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\urls.py", line 3, in <module> from . import views File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\views.py", line 4, in <module> from chat_app2.account.forms import RegistrationForm ModuleNotFoundError: No module named 'chat_app2.account' I'm trying to add new user to the database using a user … -
React and Django - Connect the Note model with the specific User
I am creating a notes saving app using react and django_rest_framework. My Note model - from django.db import models from django.contrib.auth.models import User class Note(models.Model): title = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.title Note Serializer - from rest_framework import serializers from .models import Note class NoteSerializer(serializers.ModelSerializer): class Meta: model = Note fields = ("id", "title", "content") For register and logging in I am following the answer here - Answer Now, how do I connect my note object to the specific logged in user so a particular note is only visible to that user? This can be done with ForeignKey in django but how to do it in django_rest_framework? Please help. Thanks! -
Fast Search With Django + PostgreSQL
I am newbie working on Django with PostgreSQL database. I want to know that, what are the most efficient approaches for fast search on large data (millions of records). because I ran query on 300K records, it took too much time. Please kindly guide me that how can I do fast search in Django? Thank you so much. -
unable to get CSS to load on a Django html page
My css is not rendering on any of my HTML pages in a dJango project. I have followed a few Stack solutions to no avail, including adding <link rel="stylesheet" href="{% static "styles.css" %}" type="text/css" media="screen" /> as described here: Django static files (css) not working and also changing that to <link rel="stylesheet" href="{% static 'style.css' %}" />, suggested here: Unable to Apply CSS on my HTML file Django currently my HTML looks like: {% extends "mail/layout.html" %} {% load static %} <link rel="stylesheet" href="{% static 'styles.css' %}" /> {% block body %} <div id="inbox-view"> <h3>Inbox</h3> <button id="show-email-row" class="btn default"> email row </button> <button class="btn default">Default</button> </div> {% endblock %} {% block script %} <script src="{% static 'mail/inbox.js' %}"></script> {% endblock %} And my css file called styles.css, which is in a folder called '''static''' looks like this: textarea { min-height: 400px; } .btn { border: 2px solid black; background-color: white; color: black; padding: 14px 28px; font-size: 16px; cursor: pointer; } /* Gray */ .default { border-color: #e7e7e7; color: black; } .default:hover { background: #e7e7e7; } Ideally, the button will change color on hover, and have a dark background. Thank you -
Django.db.utils.DataError: value too long for type character varying(300) In django Models
I'm not sure what limit is this error django.db.utils.DataError: value too long for type character varying(300) is referring to, Can you tell me what I'm doing wrong and how to fix that problem. #models.py class Meetings(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name = "Appointment Made By") reasonOfAppointment = models.TextField(null=True, blank=True, verbose_name = "Reason of Appointment") dateOfBirth = models.CharField(max_length=200, null=True, blank=True, verbose_name = "Patient Date Of Birth") gender = models.CharField(max_length=200, null=True, blank=True, verbose_name = "Gender") maritalStatus= models.CharField(max_length=200, null=True, blank=True, verbose_name = "Merital Status") phoneNumber=models.CharField(max_length=200, null=True, blank=True, verbose_name = "Phone Number") emergencyContactNo=models.CharField(max_length=200, null=True, blank=True, verbose_name = "Emergency Contact Number") medicalHistory= models.TextField(null=True, blank=True, verbose_name="Patient Medical History") previousTreatmentDetails=models.TextField(null=True, blank=True, verbose_name="Prevous Treatment Details") allergicTo= models.CharField(max_length=200, null=True, blank=True, verbose_name="Allergies") taxPrice = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) consultancyServiceFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) totalFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False, verbose_name= "Is Payment Recieved ") paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True, verbose_name= "Paid At") meetingWillBeConductedOn = models.CharField(max_length=200, null=True, blank=True, verbose_name ="Meeting Venue Zoom or etc") meetingSchedual = models.CharField(max_length=200, null=True, blank=True, verbose_name ="Give Tentative Time Of when Meeting will be conducted") meetingLink = models.CharField(max_length=2000, null=True, blank=True, verbose_name ="Enter Meeting Link") isMeetingConducted = models.BooleanField(default=False, verbose_name="Is Meeting Has been Held") meetingConductedAt = models.DateTimeField( auto_now_add=False, null=True, blank=True, verbose_name="Meeting … -
how can i deal with this problem "i want a button which shows when i click on radio button after that it will display "
enter image description here I want this button whenever i clicked on perfect address so please can any one help me -
How to serve dynamic sitemap.xml through nginx?
How to serve dynamic sitemap.xml file (generated from a CMS) through nginx? Is there any rules that have to be configured? Thanks -
send user to a link with data in that link
The main idea is I want to generate a Qrcode that going to have a URL, I want the URL to contain data {object}, and I want to collect that object in the other page(URL). I hope the Idea is clear, and can someone please help me with methodologies to achieve that result. -
__str__ returned non-string (type NoneType) ERROR when adding DATA
Right now I'm trying to get user-specific data in a website I'm using but I'm getting what seems to be a pretty basic error when I click submit on one of my forms. The error is: str returned non-string (type NoneType) my view looks like this: def adddata_asbestos(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = SheetForm_Asbestos(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Successfully Created") return HttpResponseRedirect("/front_page/sheets/list_data_asbestos/") context = {"form": form,} return render(request, 'sheets/add_data/add_data_asbestos.html', context) And importantly this is the form that adds data: {% load static %} <!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static "css/add_data.css" %}"> <link rel="stylesheet" href="{% static "css/materialize2.css" %}"> <title>Ladder - Asbestos Add Data</title> </head> <div class="back_button_sheet"> <a style="background-color: #2f3d50; border-radius: 18px;" href="{% url 'list_asbestos' %}" class="btn btn-primary">< Back</a> </div> <div class="table_position_add container my-4"> <div class="card my-3"> <div class="card-body"> <h4 style="font-size: 30px; text-align: center;">Asbestos Testing</h4> <form class="table_add" method="POST" action=""> {% csrf_token %} <table class="table table-bordered"> <tr> <td style="font-weight: bold;">Date</td> <td> <input placeholder="MM/DD/YYYY"{{ form.date }} <div style="font-size: 15px;">{{ form.date.errors }}</div> </td> </tr> <tr> <td style="font-weight: bold;">Time</td> <td> <input placeholder="HH:MM am/pm"{{ form.time }} <div style="font-size: … -
Modify objects before making query in Django
I have a model like this: name price N1 950 $ N2 930 € N3 1200 $ N4 800 € I want to get objects that their price is lower than or equal 1000 $. But before that, I want to first convert the unit of all prices to dollars and secondly convert their data type to int. Some thing like this: for i in range(0, len(price)): if '€' in price[i]: price[i] = int([int(s) for s in price[i].split() if s.isdigit()][0] * 1.18) else: price[i] = int([int(s) for s in price[i].split() if s.isdigit()][0]) print(price) ############ Output ############ # [950, 1097, 1200, 967] and then make this query:(Entry.objects.price__lte=1000). (N1, N4 must be results) -
Remove text without tags
I am trying to do a manual rendering of Django forms and it generates the code below, is there a way to get rid of the texts that do not have any HTML tags, a good example is the texts "Currently: " and "Change:" it is really difficult to style with CSS. <div class="row align-center mb-0 text-center"> <div class="col-md-12"> <div class="fuzone mb-2"> <div class="fu-text"> <span><i class="mdi mdi-image-area"></i> Click here or drop files to upload</span> </div> Currently: <a href="/media/realtor/download.jpeg">realtor/download.jpeg</a> <input type="checkbox" name="image-clear" id="image-clear_id"> <label for="image-clear_id">Clear</label><br> Change: <input type="file" name="image" accept="image/*" class="clearablefileinput form-control-file" id="id_image"> </div> </div> -
SQL statement INNER JOIN to Django ORM
I'm new with Django but my sql is working fine. I wonder how i can make such query in Django I have SQL statement with join select a.id, b.id from model.a join model.b on model.b.a_id=model.a.id where 'need to find'=Any(a.info); Models: class A(models.Model): name = models.CharField(max_length=200) info = models.ArrayField() class B(models.Model): name = models.CharField(max_length=200) a = models.ForeignKey('A', related_name='a', on_delete=models.CASCADE) -
Django No Such Table exception after three simple commands
I am following this Django tutorial, and tried to do copy the code from the video. I have created a class which is a to-do-list, and I want to show it in the shell by running ToDoList.objects.all(). my models.py: from django.db import models from django.forms import model_to_dict from django.utils.timezone import now class Item(models.Model): title = models.CharField(max_length=200) # Short description of the item datetime_found = models.DateTimeField(default=now, blank=True) # Date and time of when the item was found def items(): res = [] for i in Item.objects.all(): res.append(model_to_dict(i)) return res # I ADDED THESE TWO CLASSES BELOW class ToDoList(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class ListItem(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) # from ToDoList class text = models.CharField(max_length=300) complete = models.BooleanField() # Boolean says if we're completed list item def __str__(self): return self.text Then I ran py manage.py makemigrations and got this prompt: Migrations for 'myapp': myapp\migrations\0005_listitem_todolist.py - Create model ToDoList - Create model ListItem In the shell I wrote >>> from myapp.models import ToDoList, ListItem >>> t = ToDoList(name="My list") >>> t.save And I got this prompt: <bound method Model.save of <ToDoList: My List>> But now, that I try to see my list object by writing ToDoList.objects.all() I get an … -
Page Not found 404 when i try to create a new comment to Post object?
I am trying to let users create comment from listview on the social app am working on currently but am having a hard time working out the pattern. I keep getting the Error 404 when i try to load the listview. Here is Formlist view which my Post list view inherent from. class FormListView(FormMixin, ListView): def get(self, request, *args, **kwargs): if request.method == 'GET': post_id = request.GET.get('post_id') comment = request.GET.get('comment', False) post_obj = get_object_or_404(Post, pk=post_id) session_obj = User.objects.get(username=request.user.username) create_comment = Comment.objects.create( post=post_obj, user=session_obj, comment=comment) create_comment.save() # From ProcessFormMixin form_class = self.get_form_class() self.form = self.get_form(form_class) # From BaseListView self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty and len(self.object_list) == 0: raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__}) context = self.get_context_data(object_list=self.object_list, form=self.form) return self.render_to_response(context) def post(self, request, *args, **kwargs): if request.method == "POST": description = request.POST['description'] pic = request.FILES.get('pic', False) #tag = request.FILES['tag'] user_obj = User.objects.get(username=request.user.username) post_data = Post(username=user_obj,pic=pic,description=description,) post_data.save() messages.success(request, f'Posted Successfully') return redirect('feed:feed') return self.get(request, *args, **kwargs) For one strange thing am able to create New Post from the PostListview but, Comment has been a challenge for me, for the past two weeks now and i have look on here but can't seem to find a … -
Django - can't download file (showed as text instead)
I have a pdf in my static files, I need to add it some text and let the user download it, but the download part gives me some problems, here is part of my code: views.py import io from werkzeug.wsgi import FileWrapper from pathlib import Path from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from django.http import HttpResponse, FileResponse def downloadpdf(request): pdf_path = (Path.home()/"bot"/"mysite"/"static"/"images"/"tesseragenerica.pdf") # 1 pdf_reader = PdfFileReader(str(pdf_path)) packet = io.BytesIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) testo = "text to add" #in future "text to add" will be the username can.drawString(5, 5, testo) can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(open("/home/myusername/bot/mysite/static/images/tesseragenerica.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = open("destination3.pdf", "wb") output.write(outputStream) outputStream.close() return FileResponse(FileWrapper(packet), as_attachment=True, filename='hello.pdf') The code for adding text to pdf is correct because in local it works so i think the problem is what i'm putting as the first argument of FileResponse, if I put FileWrapper(packet) for … -
Django searching for user with url
I have a problem with django. I try to search for users by getting an inputvalue and append this value to my url, so that one can basically search by typing a name in the url too (like it is by Instagram). For example: "localhost/name", it gives me all information to the User. Although the value is in the url and I have a dynamic url function, it doesn´t work. I read a lot of questions here but none worked for me. Thanks in advance. urls.py path("<str:name>/", views.search, name="search"), views.py @login_required(login_url="login") def search(response, name=None): if response.method == "POST": searched = response.POST['searchinput'] users = User.objects.filter(username=name) return render(response, "main/search.html", {"searched":searched, "user":users}) else: return redirect("home") base.html (for the input) <form id="searchform" class="form-inline my-2 my-lg-0" name="searchinputform" method="POST" action=" {% url 'search' name=None %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" name="searchinput" id="searchinput" placeholder="Suche" > <script> $( "#searchform" ).submit( function( e ) { e.preventDefault(); document.location = $( "#searchinput" ).val(); } ); </script> -
How to add data from a Postgres View to an existing Django View?
I’m new to Django and still trying to get my head around some of its concepts. So far I have been able to get everything I want working, except for this thing where I clearly don’t fully grasp some of its concepts. If only I knew where the gap in my understanding is. I have a Postgres database with a number of tables. All tables are in models.py and I can read from the main table tbl_items using a Django model and template. So far so good. There is one more complex bit of data that needs to be combined from three tables in two JOINS. I have created a Postgres View that does the heavy lifting with all the JOINS and it works fine. I can query the View from the PSQL command line as if it was a real table and everything works as expected. I then added the Postgres View tbl_combi to models.py, migrated it, and figured that from now on, every part of Django should be oblivious to the fact that tbl_combi is actually a Postgres View instead of a real table. This is the relevant part from models.py: from django.db import models class TblItems(models.Model): item_id … -
Django Formset: how to get the current user? (using django-extra-views)
I'm used to collecting the current logged in user in a CreateView and passing it to the form like so: class MakeFantasyTeam(CreateView): form_class = MakeFantasyTeamForm [...] def form_valid(self, form): form.instance.tourney = Tournament.objects.filter(id=tourney_id).get() form.save() return super(MakeFantasyTeam, self).form_valid(form) However, this doesn't seem to work when using an InlineFormSetView as provided by django-extra-views. I get an error NOT NULL constraint failed: tournament_invite.invited_by_id and I'm not sure how to get the user.id passed on to the form. My View: class InvitePlayersView(InlineFormSetView): template_name = 'invite_players.html' model = Tournament inline_model = Invite form_class = InvitePlayerForm pk_url_kwarg = 'tourney_id' factory_kwargs = {'can_delete': False, 'extra': 1} def formset_valid(self, formset): tourney_id = self.kwargs['tourney_id'] formset.instance.invited_for = Tournament.objects.filter(id=tourney_id).get() formset.instance.invited_by = self.request.user formset.save() return super(InvitePlayersView, self).formset_valid(formset) def get_success_url(self): return reverse('make_team', kwargs={'tourney_id': self.object.invited_for.id}) My Model: class Invite(models.Model): name = models.CharField(max_length=200, blank=True, null=True) email = models.CharField(max_length=320, null=False, blank=False, validators=[EmailValidator],) invited_by = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING) invited_for = models.ForeignKey(Tournament, on_delete=models.DO_NOTHING) created_dt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email def get_absolute_url(self): return reverse('home') My Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = Invite fields = ('name', 'email',) Any tips or hints much appreciated! Thank you, Jon -
my add to cart form throwing me to the register form
i created a add to cart form in my section.html but when i click add to cart button it redirect me to register page what i want to achieve is load the same page and open the same spot where i click add to cart but it not happening here is my section.html <ul class="sec"> {% for section in section_list %} <div class="card col-11" id="{{ section.id }}"> <div class="card-header"> {{ section.title }} </div> <div class="card-body"> <h5 class="card-about">{{ section.about_section }}</h5> <br> <i class="price fas fa-rupee-sign"> {{ section.price }}</i> <br> <br> <i class="icon text-white fas fa-chalkboard-teacher"> {{ section.teacher }}</i> <i class="icon text-white fas fa-clock"> {{ section.content_duration}}</i> <i class="icon text-white fas fa-tags"> {{ section.subject.name }}</i> <form action="/{{section.id}}" method="POST"> {% csrf_token %} <input hidden type="text" name="section" value="{{section.id}}"> <input type="submit" class="btn btn-outline-primary" value="Add To Cart"> </form> </div> </div> {% endfor %} </ul> and here is my views.py for section.html @method_decorator(login_required, name='dispatch') class Sections(View): def post(self, request, subject_id): sections =request.POST.get('section') cart = request.session.get('cart') if cart: cart[sections] = 1 else: cart = {} cart[sections] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('subjects:section', subject_id=subject_id) def get(self, request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject sections = subject.section.all() # get the sections related to the subject return … -
Virtualenv and django not working in bash on windows 10
I have a problem with using virtualenv and django in bash. If I type python -m venv env in cmd, then env\Scripts\activate, and then virtualenv - I get 'virtualenv' is not recognized as an internal or external command, operable program or batch file.. If I do the same in bash I get bash: virtualenv: command not found. How do I fix this?