Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error: Invalid block tag on line 28: 'endfor'. Did you forget to register or load this tag?
I'm stuck on this error I am a new user of Django I am following the steps correctly and learning through YT. When I run python manage.py runserver the HTML shows My index.html file <!DOCTYPE html> <header> CRUD Operation with PostgreSQL </header> <body> <center> <h1>How to create CURD Ops with PostgreSQL</h1> <h3>Learning Django and CURD</h3> <hr/> <table border = "1"> <tr> <th>Employee Id</th> <th>Employee Name</th> <th>Email</th> <th>Occupation</th> <th>Salary</th> <th>Gender</th> </tr> {% for results in data% } <tr> <td>{{result.id}}</td> <td>{{result.name}}</td> <td>{{result.email}}</td> <td>{{result.occupation}}</td> <td>{{result.salary}}</td> <td>{{result.gender}}</td> </tr> {% endfor %} </table> </center> </body> I tried to change endfor to endblock nothing works. I don't know how to solve this, Please help. -
Django - annotate the most frequent field taken from another model linked with foreignKey
I have a model of users and a model with a survey in which users express their opinion with a vote with an integer number that identified a particular color of eyes. A srcID user describes the color of the eyes of a dstID user according to his opinion. A user can votes himself. It's possible that a user doesn't receive any votes so there isn't a tuple with dstID equal to his ID. The integer number of eyeColor rapresent a specific color, for instance: 1 => blue eyes 2 => lightblue eyes 3 => brown eyes 3 => green eyes ecc. class user: userID = models.AutoField(primary_key = True, auto_created = True, unique = True) name = models.CharField(max_length=100) class survey: srcID = models.ForeignKey(user, on_delete = models.CASCADE, related_name='hookSrc') dstID = models.ForeignKey(user, on_delete = models.CASCADE, related_name='hookDst') eyesColor= models.IntegerField() My goal is to annotate in the user model the most frequent type of eyeColor voted, so the eyesColor that other people think is the eyesColor of that user. If a user doesn't receive any votes I want to annotate 0. In case there are more than one color with the same voting frequency, if the user has voted himself (tuple with srcID = … -
Will I need to create a virtualenv every time I runserver with Django?
Currently taking CS50 Web Programming with Python and Javascript. I'm on the Week 3 Django lecture and trying to follow along but I'm running into trouble while trying to run python manage.py run server. I'm getting the "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" error. I'm using Windows, Django IS installed and I've reinstalled it multiple times. I've found a workaround by following the steps from https://www.youtube.com/watch?v=eJdfsrvnhTE&t=296s to set up a virtual env and can proceed after that, but in the lecture Brian doesn't need to setup a virtual env? It just loads straight through for him? Yes I have scoured through reddit, stackoverflow, youtube, and other articles online before asking this here. It's not too much trouble to do so but I'm just wondeirng why he didn't need to make a virtualenv and if I'm actually going to have to make a virtual env for every Django project going forward? Is it because things have changed with python/pip/Django? I would just find it more convenient if I could just run the run server command without having to run the extra 4 commands … -
hi, i have this error when i try to make migrations comand with django project: [duplicate]
I have not been able to find a solution to this problem since the database or mysql is not right, I do not understand it, if anyone knows a solution for this, my OS is mojave on Mac, I do not know if it is because of the version or what problem it has this bash: : command not found (base) MacBook-Pro-de-andrex:python_web andrexbaldion$ python3 manage.py makemigrations Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.18.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/andrexbaldion/Desktop/djangoproyecto2/python_web/manage.py", line 22, in <module> main() File "/Users/andrexbaldion/Desktop/djangoproyecto2/python_web/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked … -
Django static files not working in localhost
I have my Django app running on a development server. The HTML templates are serving fine but I'm really having a lot of trouble getting the static files to serve. I've tried lots of ideas from Stack Overflow but not getting anywhere. I just get a 404 error on the image. Can anyone help me please? My urls.py is: from django.contrib import admin from django.urls import path from app import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns # The rest of my urls here... urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my settings has included: STATIC_ROOT = "/home/me/django-test/djangoproject/static" STATIC_URL = 'static/' and my template has: <!doctype html> {% load static %} <img src="{% static 'e.png'%}"> -
Django serializer very slow takes 8-10 seconds
I'm trying to develop dashboard API which requires fetching data from several tables for each product, lets I have 5 products I need to query 5-6 other tables to get the data for each table. Those 5 tables are very large table in future it might even reach to 1-2M records.(they are added every minute) I used prefetch related for the backward relation - I agree query time gets reduced a lot, but serializer gets very slow no matter how many fields I have. For dashboard I need to pick the latest record related to entities I'm displaying in dashboars. My Model Class Product(): name Slug Class ProductViewedByUser()// need last user who viewed the product Users Time Similar to ProductViewedByUser I have 5-6 tables from which I need to fetch latest record. I tried Prefetch Related query time is 115 ms for 3 products and nearly 500000 cached rows. When I pass this to serializer no matter what fields are there even with one CharField- time goes to 3seconds When I have multiple fields time goes to 10 seconds I'm expecting serialization to be fast as possible. Is it good idea to create one another table for storing latest records … -
A site on cPanel loaded perfectly, but when I downloaded the latest update to the site, this error appears .How to solve this problem؟
A site on cPanel loaded perfectly, but when I downloaded the latest update to the site, this error appears .How to solve this problem؟ Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. -
Tweepy .get_me() error when using OAuth 2.0 User Auth flow with PKCE
Trying to get an authenticated user's Twitter ID and Twitter username via the Tweepy package. With authentication through the OAuth 2.0 flow (using a Django view). I've been able to create an instance of the Tweepy pkg's Client class using the OAuth 2.0 User Context flow, but when I use the .get_me() method on it, I get an error. The error is: "Consumer key must be string or bytes, not NoneType" The error would suggest that the method wants a Consumer Key, but in this case, I initialized the Class using the OAuth 2.0 User Context flow with PKCE, which doesn't require it. I created the instance with the snippet below (in the same way it's specified in the Tweepy docs here): import tweepy oauth2_user_handler = tweepy.OAuth2UserHandler( client_id="Client ID here", redirect_uri="Callback / Redirect URI / URL here", scope=["follows.read", "users.read", "tweet.read", "offline.access"], client_secret="Client Secret here" ) access_token = oauth2_user_handler.fetch_token( "Authorization Response URL here" ) client = tweepy.Client("Access Token here") The Client object doesn't appear to be the issue, as I'm getting redirected to Twitter to authorize and redirected back via the callback as it should work. The Consumer Key is a requirement of the OAuth 1.0 User Context flow, but that's … -
CSS Grid with Django
I am studying Django and I have a question regarding CSS Grids and Dynamic content. In the HTML code below I am trying to get from my views.py file the values of a dictionary. # From 'views.py' def index(request): values = { 1: 'Value 1', 2: 'Value 2', 3: 'Value 3' } past_values = { 'past_values': experiences } This is part of the HTML I was talking about: <!-- START PORTFOLIO --> <section id="portfolio" class="tm-portfolio"> <div class="container"> <div class="row"> <div class="col-md-12 wow bounce"> <div class="title"> <h2 class="tm-portfolio-title">My <strong>Past Values</strong></h2> </div> <!-- START ISO SECTION --> <div class="iso-section"> <ul class="filter-wrapper clearfix"> <li><a href="#" class="opc-main-bg selected" data-filter="*">All</a></li> <li><a href="#" class="opc-main-bg" data-filter=".html">Cat 1</a></li> <li><a href="#" class="opc-main-bg" data-filter=".photoshop">Cat 2</a></li> <li><a href="#" class="opc-main-bg" data-filter=".wordpress">Cat 3</a></li> <li><a href="#" class="opc-main-bg" data-filter=".mobile">Cat 4</a></li> </ul> <div class="iso-box-section"> {% for key, value in past_values.items %} <div class="iso-box-wrapper col4-iso-box"> <div class="iso-box html photoshop wordpress mobile col-md-3 col-sm-3 col-xs-12"> <div class="portfolio-thumb"> <img src="{% static 'images/portfolio-img1.jpg' %}" class="fluid-img" alt="portfolio img"> <div class="portfolio-overlay"> <h3 class="portfolio-item-title">{{value}}</h3> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonumm.</p> </div> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> </section> <!-- END PORTFOLIO --> Here is the related CSS: /* START PORTFOLIO */ .tm-portfolio { … -
Apache webserver with app using GDAL not working on windows
I am trying to deploy a django project using POSTGIS on my windows 11 PC with Apache 2.4. The web page is working as long as I am not using 'django.contrib.gis'. When I add 'django.contrib.gis' to my INSTALLED_APPS and define GDAL_LIBRARY_PATH to point to my gdal installation things stop working. Specifically, trying to access the web app ends up in infinitely loading the page. Weird enough there are no errors in the apache error log. The apache service starts fine. As far as I can see gdal install is correct as the app is working fine on the same machine with the same python environment with the django development server. Actually, I have the same issue with other python libraries that need some dlls, like opencv. So my guess is that it is a security related issue, but I do not find any clues on how to solve it. Any ideas? I tried also to grant rights to the directory where gdal is install in apache conf. But no luck. -
in Django FormView I cant see the form
I have some issues where I can see the form nor the parameter this is my code Here I pass an ID from the previous selection as parameter URL file path('make_payment/<int:jugador_id>', views.Payment_ViewMix.as_view(), name = "make_payment"), view fiel: here I try to catch the parameter and also get the current time and get the form, when I delete the get_context_data function, the form is shown correctly when I add it again nothing sows and the ID is never shown in the HTTP template class Payment_ViewMix(FormView): form_class = PagoJugadorForm template_name = "includes/make_payment.html" context_object_name = 'payment' def get_context_data(self, **kwargs): idjug = self.kwargs idjugador = int(idjug['jugador_id']) print(idjugador) context = { 'idjugador':idjugador, } return context def form_valid(self, form): context = self.get_context_data(context) print(context) fecha_pago = datetime.datetime.now() print(fecha_pago) jugador_id = context['idjugador'] fecha_pago = fecha_pago #jugador_id.instance = self.object monto = form.cleaned_data['monto'] notas = form.cleaned_data['notas'] id_categoriapago = form.cleaned_data['id_categoriapago'] id_group_categoria =form.cleaned_data['id_group_categoria'] JugadorPagos.objects.create( idjugador = jugador_id, fecha_pago = fecha_pago, monto = monto, notas = notas, id_categoriapago = id_categoriapago, id_group_categoria = id_group_categoria, ) return super(Payment_ViewMix, self).form_valid(form) form file : here in the form I do not show the ID because is the one that I want to get from the parameter given and the current date is the one that I would … -
nested one to many serializer model django
I am trying to create a relationship between databases result : => [ { "id":1, "title":"mobile", "category_two":[ { "id":3, "title":"brand" }, { "id":4, "title":"memory" } ] } ] and i expect : => [ { "id":1, "title":"mobile", "category_two":[ { "id":3, "title":"brand", "category_three":[ { "id":1, "title":"samsung" }, { "id":2, "title":"apple" } ] }, { "id":4, "title":"memory", "category_three":[ { "id":1, "title":"32gb" }, { "id":2, "title":"64gb" } ] } ] } ] // views class get_Category(APIView): def get(self, request): category = CategoryOne.objects.all() serializer = CategoryTwoSerializer(category, many=True) return Response(serializer.data) //serializers class CategoryOneSerializer(serializers.ModelSerializer): class Meta: model = CategoryOne fields = '__all__' class CategoryTwoSerializer(serializers.ModelSerializer): category_two= CategoryOneSerializer(many=True,read_only=True) class Meta: model = CategoryTwo fields = '__all__' depth=5 class CategoryThreeSerializer(serializers.ModelSerializer): category_three = CategoryTwoSerializer(many=True,read_only=True) class Meta: model = CategoryThree fields = '__all__' depth=5 // models class CategoryOne(models.Model): title = models.CharField(max_length=225) def __str__(self): return self.title class CategoryTwo(models.Model): title = models.CharField(max_length=255) categoryone = models.ForeignKey(CategoryOne,related_name='category_two',on_delete=models.SET_NULL,null=True) def __str__(self): return self.title class CategoryThree(models.Model): title = models.CharField(max_length=255) categorytwo = models.ForeignKey(CategoryTwo,related_name='category_three',on_delete=models.SET_NULL,null=True) def __str__(self): return self.title -
Updating value on django model object does not update value on related foreign key model
I have 2 models, House and Room where Room has a foreign key to House: class House(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) class Room(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) color = models.CharField(max_length=50) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name='rooms') When I run the following test, for some reason the colors are not matching, even though the ids do. Can someone help figure out why? def test_color_change(self): h = House(name='new house') h.save() r = h.rooms.create( name='living room', color='blue' ) r2 = h.rooms.get(name='living room') r2.color = 'green' r2.save() self.assertEqual(r.id, r2.id) self.assertEqual(r2.color, r.color) I've been looking at the django documentation for RelatedManager, but haven't been able to figure it out. I would have expected r and r2 to be pointing to the same object, but apparently they are not. -
Tracking Django sessions with custom cookies
I am looking for a way to track the time users spend on the site. I have found the package django-tracking2, which tracks visitors by the Django session. However, my session expiry is set to 2 weeks, which makes it useless to track daily activity. My thoughts are that I can create a different cookie that expires every day, so that I can use this cookie for tracking. However, I do not quite understand how exactly I would assign a random cookie every day for users, as the Django docs does not quite have examples on this. The desired logic is: When a user opens the app, check if cookie custom_cookie is set If not, create it with a random value (probably uuid4?) The cookie should expire the same day at midnight I have come across this way of creating cookies in the middleware, however I think it will yield different random values in the request and response objects: class MyCookieProcessingMiddleware(object): # your desired cookie will be available in every django view def process_request(self, request): # will only add cookie if request does not have it already if not request.COOKIES.get('custom_cookie'): request.COOKIES['custom_cookie'] = uuid.uuid4() # your desired cookie will be available … -
Django multistep form
I have a multi-step form that is 3 steps but it has 4 forms. In the first form, the user has to choose from two choices. The user's first form choices will determine the next form that will be displayed. The first form template. {% extends 'base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> {% block head %} {% endblock %} </head> <body> {% block content %} {% if form.customer_choices == 'commercial': %} <form action="{% url 'datacollector:step2aformview' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% else %} <form action="{% url 'datacollector:step2bformview' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endif %} {% endblock %} </body> </html> form.py from .models import CustomerInfo, CustomerDocument from django.forms import ModelForm from django import forms CUSTOMER_CHOICES = [ ('commercial', 'Commercial'), ('private', 'Private'), ] class CustomerTypeForm(forms.Form): customer_chioces = forms.CharField(label="Customertype", widget=forms.RadioSelect(choices=CUSTOMER_CHOICES)) #Commercial customer information class CustomerInfoForm1(ModelForm): class Meta: model = CustomerInfo fields = "__all__" #Private customer information class CustomerInfoForm2(ModelForm): class Meta: model = CustomerInfo fields = ['name1', 'name2', 'name3', 'street', 'house', 'zip1', 'city'] class CustomerDocumentForm(forms.ModelForm): class Meta: model = CustomerDocument fields = ['document'] Views from django.shortcuts import render … -
i keep on getting 404 error for my static file in django 4.1.3
currently trying to implement Dialogflow cx chatbot into a website using Django and Kommunicate watched a Youtube vid and followed it everything works until the last part when trying to get script.js the website just cant get the script.js part tried online solutions but didn't work for me ps its my first time asking a question on stack overflow -
How to render the values without writing the logic in every view, Django?
In my view I want to request data from database, and on other page I also need this information, but I don't want to write this request logic again. views.py def account(request): user_id = request.user.id balance = Customer.objects.filter(name_id=user_id).values("usd").first() bonus = Customer.objects.filter(name_id=user_id).values("bonus").first() context1 = {'usd':balance['usd'], 'bonus':bonus['bonus'], return render(request, 'account.html', context1) def main(request): (here I also need to request balance and bonus) In def main(request): and on other pages I also need balance and bonus, but I don't really want to request this values in every view. Can I somehow write it somewhere once and to render on pages, and do not write it in every view?? -
How to get const from forEach method in javascript?
I have django application with quiz model: class Quiz(models.Model): name = models.CharField(max_length=50) topic = models.CharField(choices=TOPICS, max_length=50) number_of_questions = models.IntegerField(validators=[MinValueValidator(1)]) time = models.IntegerField(help_text="duration of quiz in minutes", default=5) pass_score = models.IntegerField(help_text="score required to pass in %", default=90, validators = [MaxValueValidator(100), MinValueValidator(0)]) difficulty = models.CharField(choices=DIFFICULTY_CHOICES, max_length=10) I get it in view: def quiz_view(request, pk): quiz = models.Quiz.objects.get(pk=pk) return render(request, 'quizes/quiz.html', {'obj':quiz}) Then I get data of obj in html: {% for obj in object_list %} <button class="modal-button" data-pk="{{ obj.pk }}" data-name="{{ obj.name }}" data-topic="{{ obj.topic }}" data-questions="{{ obj.number_of_questions }}" data-difficulty="{{ obj.difficulty }}" data-time="{{ obj.time }}" data-pass="{{ obj.pass_score }}"> {{ obj.name }} </button> {% endfor %} <div id="modal"></div> Then I get data from button in javascript forEach method: let modal = document.getElementById('modal') const modalBtns = [...document.getElementsByClassName('modal-button')] modalBtns.forEach(modalBtn => modalBtn.addEventListener('click', ()=>{ const pk = modalBtn.getAttribute('data-pk') const name = modalBtn.getAttribute('data-name') const topic = modalBtn.getAttribute('data-topic') const numQuestions = modalBtn.getAttribute('data-questions') const difficulty = modalBtn.getAttribute('data-difficulty') const passScore = modalBtn.getAttribute('data-pass') const time = modalBtn.getAttribute('data-time') if(modal.classList.contains('close-modal')){ modal.classList.remove('close-modal') } modal.classList.add('open-modal') modal.innerHTML = ` <p class="text">Are you sure you want to open</p><p class="name_of_quiz"><b>${name}?</b></p> <ul class="description"> <li>Topic: ${topic}</li> <li>Questions: ${numQuestions}</li> <li>Difficulty: ${difficulty}</li> <li>Score to pass: ${passScore}%</li> <li>Time to solve: ${time} min</li> </ul> <div class="buttons-container"> <button class="close-button" onclick="close_modal()">Close</button> <button class="proceed-button" id='start_button' onclick="startQuiz()">Yes</button> </div> ` … -
How to create model object that via user foreignkey, FOREIGN KEY constraint failed?
In my view I am creating the object model, and in this model that I am creating is one field, name=models.ForeignKey(User, on_delete=models.CASCADE). And I am using ForeignKey because in this object can be made multiple time by a single user. And I get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed Here is the model: from django.contrib.auth.models import User ... class Customer_status(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.CASCADE) creation_date = models.CharField(max_length=28) status=models.CharField(max_length = 8) def __str__(self): return str(self.name) + '_' +str(self.id) And in this view I am creating this model: def status_create(request): if request.user.is_authenticated: print('This print work but after it, is an ForeignKey error') Customer_status.objects.create ( name=request.user, creation_date=datetime.datetime.now(), status='Pending' ) The thing is that I had OneToOne and I couldn't make more than 1 model from 1 user, after I changed it to ManyToMany I have the this error django.db.utils.IntegrityError: FOREIGN KEY constraint failed. When it was models.OneToOne, request.user worked, but when I put ForeignKey, it doesn't work -
Django3.2 connection OneToOneField on related_name object has no attribute 'all'
I have a problem getting data through related_name, it can't find the attribute all(). =( The picture shows my attempts, but they did not lead to a result. -
How can I set Django views depending on api source?
I need to show my django views after login when api boils. But I can't provide this because it validates from a database in django in standard django functions. When the API I set up with Fastapi boils, I can login by generating access_token, but then I cannot authorize my viewsets or condition a condition such as access_token_required. How do you think I can achieve this? views.py def _login(request): if request.method == 'POST': loginPayload = { "username" : request.POST['username'], "password" : request.POST['password'] } loginActionResult = LoginAction(loginPayload).__login__() actionResult = loginActionResult['result'] token = loginActionResult['detail'] if not actionResult: messages.add_message(request, messages.ERROR, token) else: return redirect('chockindex') return render(request, 'account/login.html',context = { "loginform" : UserLoginForm() }) @acces_token_required <========== I want to take a precaution like this def owners(request): return render(request, 'pages/owners.html') and this loginactionfunctions class ApiUrls(): def __init__(self): self.headersDefault = { "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0", "Content-Type" : "application/x-www-form-urlencoded", "Accept-Language" : "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3", "accept" : "application/json" } self.loginUrl = "http://127.0.0.1/login" self.bonusRequestsUrl = "http://127.0.0.1/results" class LoginAction(ApiUrls): def __init__(self, loginPayload): super().__init__() self.loginPayload = loginPayload def __login__(self): loginRequest = requests.post( url=self.loginUrl, headers=self.headersDefault, data=self.loginPayload ) loginResponse = loginRequest.json() try: return { "detail" : loginResponse['detail'], "result" : False } except: return { "detail" : loginResponse['access_token'], "result" … -
Can anyone help me out with discount coupons in Python Django?
everyone Currently I am working on a E-Commerce Website, I Need to Implement these Offers on add to cart as the Products are being add the Price should be deducted according to the Offer Provided. The Offers are as follows:- Offer 1- Buy one get one free, Offer 2- 50% off on more than 2000 buy, Offer 3- 30% off on selecting more than 2 products to add to the cart. I have made the E commerce website everything is fine but just don't know how to use the Offer logic and though tried multiple things but nothing worked as it should be working. The offers must automatically work on cart as soon as the products are added and before payment gateway the discount should work and get deducted. -
django DRF Performance problems with logic with multiple conditions
The shopping cart model stores cart items for both guest users and registered users. I provide the guest user a unique key using uuid and save it to the cookie. The situation that I want is to link the cart items that is included in the guest user's status to the login user's cart. So I wrote logic considering 3 situations. When you are a guest user, press the shopping cart button to create a cart model. If you fill up the shopping cart before logging in, remove the unique key of the shopping cart model and update it with your user information. If you press the shopping cart button after logging in immediately, create a cart immediately. Does configuring logic under these three conditions adversely affect performance? Is it common to use multiple conditions like this? Is it overloading the server? Help me improve my logic. thanks @api_view(['POST']) def addToCart(request): user = request.user data = request.data guest_id = request.COOKIE.get('guest_user') #if anonymous user puts item in the cart if not request.user.is_authenticated: cart = Cart.objects.create( guest_id = guest_id ) CartItems.objects.create( cart = cart, product = data['product_id'], product_option = data['product_option'], qty = data['qty'] ) serializer = CartSerializer(cart, many=False) return Response(serializer.data) #if guest_user … -
How to write dynamic data in django template
I want only integer value but string is also being printed in it how do I fix this. I want only integer value -
include self relation data in query in django
i have comment model and i want to include all child comment in list query. in this modal a comment can have parent comment class Comment(models.Model): user = models.ForeignKey( "accounts.CustomUser", on_delete=models.CASCADE) post = models.ForeignKey(Blog, on_delete=models.CASCADE) body = models.TextField(blank=True) parentId = models.ForeignKey( "self", blank=True, on_delete=models.CASCADE, null=True) class Meta: ordering = ['-created_at'] i want to list comments which should include parent commnet data expected array [ { id:1, body:"anything", parentId:{ id:34, body:"second" } }, { //second } ]