Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error when i execute the makemigrations command in django
I'm following the cs50 course, i have added a new passenger model in models.py file but cant execute the makemigration command. i pretty new to django, excuse me if im asking something obvious This is my models.py code from django.db import models class Airport(models.Model): city=models.CharField(max_length=64) code=models.CharField(max_length=3) def __str__(self): return f"{self.city} ({self.code})" # Create your models here. class Flights(models.Model): origin=models.ForeignKey(Airport , on_delete= models.CASCADE , related_name="departures") destination=models.ForeignKey(Airport , on_delete=models.CASCADE , related_name="arrivals") duration=models.IntegerField() def __str__(self): return f" {self.origin} to {self.destination} : {self.duration}" class Passenger(models.Model): first=models.CharField(max_length=24) last=models.CharField(max_lenght=24) flight=models.ManyToManyField(Flights , blank=True , related_name="passengers") def __str__(self): return f"{self.first} {self.last}" This is the error im getting, I couldnt find anything online that explained this issue $ python manage.py makemigrations Traceback (most recent call last): File "D:\practice\airlines\manage.py", line 22, in <module> main() File "D:\practice\airlines\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File … -
Google ads for django
I have created a django Web application. Now I want to deploy it in production but first I want to know that how can I run Google ads on it ? Whether we can run ads ? If yes then how ? Thanks in advance I tried searching for that on internet found some post but didn't get anything clearly -
Python Knowledge and Its Relevance in Django Development
I spent a lot of time learning Python and building a strong knowledge base in it. My goal was to enter the Django domain and explore frameworks like DRF (Django REST Framework) to become a proficient Python developer. I started learning Django and DRF a couple of months ago, and it has been a good experience so far. My question is: up until now, I haven't had the opportunity to use the majority of Python's advanced tools that I learned. Is it because I am still a beginner in Django, or is it unnecessary to use these advanced tools such as enumerations, metaclasses, modules like fractions, descriptors, etc.? From what I've observed, it seems that a basic understanding of Python is sufficient to work with Django. Thank you for taking the time to answer my question. I expected that having a good knowledge of Python would give me a significant advantage. -
AWS Route53 + Nginx + Django, host 2 applications with CNAME
I am trying to host 2 applications in aws EC2 instances. I am using dockerlized nginx, django. The 2 apps are 2 separate django containers. I added record Record A => www.main.com XXX.XXX.XXX.XXX Record CNAME => www.aap2.main.com www.app1.com Now, how should I configure Nginx so that if user access with URL www.main.com, it is served with app1 and if user access with URL www.aap2.main.com, it is served with app2? I tried playing around with nginx.conf file but did not have luck so far. -
how do i submit form elements to sever emidiately after filling a particular form field
i have this mini flask application i am building and i have nested a form in another and i wish to submit the nested form using just javascript after i finish filling it. i am trying to do this with javascript but currently what my script deos is it submits the nested form emidiately the page loads and when i fill the inputs it deosnt submit again. bellow are my code for my html form, flask route to collect the form and the javascript HTml <form method="POST" action="/skills" enctype="multipart/form-data"> <h3>Skills</h3> <form method="POST" action="/skills" enctype="multipart/form-data" id="myForm"> <div class="form-group"> <label for="skills">Skills (comma-separated)</label> <input type="text" class="form-control" id="skills" name="skills" required> </div> <h3>Work Experience</h3> <div id="work-experience"> <div class="form-group"> <label for="work-title-1">Title</label> <input type="text" class="form-control" id="work-title-1" name="work_title_1" required> </div> <div class="form-group"> <label for="work-company-1">Company</label> <input type="text" class="form-control" id="work-company-1" name="work_company_1" required> </div> </div> <!-- Add a hidden submit button --> <input type="submit" style="display: none;"> </form> <div class="form-group"> <label for="work-start-date-1">Start Date</label> <input type="text" class="form-control" id="work-start-date-1" name="work_start_date_1" required> </div> <div class="form-group"> <label for="work-end-date-1">End Date</label> <input type="text" class="form-control" id="work-end-date-1" name="work_end_date_1" required> </div> {% if ex_summary %} <div class="form-group"> <label for="work-end-date-1">description</label> <textarea class="form-control" id="sumary" name="ex_summary" rows="8">{{ ex_summary }}</textarea> </div> {% endif %} </div> <button type="button" class="btn btn-primary" id="add-work-experience">Add Work Experience</button> <h3>Certifications</h3> <div id="certifications"> … -
How to solve Django Rest Api Deployment 404 Error on Vercel
I tried to deployed my django rest api project on vercel and it shows the message deployment successfully. But i open the visit it shows an error 404: NOT_FOUND Code: NOT_FOUND ID: bom1::d724b-1688197940778-5b5d73a1c7a7 i dont know how to fix this error im using the vercel deployment on first time. There is any solution to fix this error -
request.user showing "AnonymousUser" in django classview dispatch method but not in "get_object" method
class ProductViewSet(viewsets.ReadOnlyModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] # @method_decorator(custom_ratelimit) def dispatch(self, request, *args, **kwargs): print(request.user.id) # return "AnonymousUser" return super().dispatch(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): # some lines of code return Response(serializer.data) def get_object(self): user=self.request.user print(user) # return user EMAIL (I am using custom user model) # some code return obj I am not able to understand why dispatch() method not able to find user on other hand get_object() method is able to find the user and returning user email. FYI- I am using a custom user model and instead of a username I am using email. I want to use a decorator to count request limits for that reason I am using this dispatch method to pass users. -
Django distincted queryset slicing does not have consistency
I have queryset of empoyees-attendance and i am doing aggregation & disctinction on (current day, employee code). I got distincted queryset, Afterthat i am doing slicing, and found slicing consistency not happenning as we are expecting. I am adding screenshot of reference here. Could you please anyone explain this behaviour and how we can overcome this? -
DjangoCMS placeholder giving error : "Invalid block tag on line 25: 'static'. Did you forget to register or load this tag?"
I have a template below. {% extends 'base.html' %} {% load static %} {% load cms_tags menu_tags sekizai_tags snippet_tags %} <body> <!-- header Start --> <header> <nav class="navbar-autohide navbar navbar-white bg-white fixed-top"> <div class="container-fluid"> {% block header %} <h3>THIS IS header</h3> {% placeholder header %} {% endblock header %} {% block navigation %} <h3>This is navigation</h3> {% placeholder navigation %} {% endblock navigation %} </div> </nav> </header> <!-- header End --> {% block content %} <h1>This is content</h1> {% placeholder first_fold %} {% placeholder proudly_contributing %} {% placeholder hot_to_use %} djangocms-snippet {% placeholder choose_us %} {% placeholder our_services %} {% placeholder our_portfolio %} {% endblock content %} {% block footer %} <h1>This is footer</h1> {% static_placeholder footer %} {% endblock footer %} </body> I have added https://github.com/django-cms/djangocms-snippet in each of the placeholder and each djangocms-snippet contains a corresponding HTML. That html contains django static tag and each of the placehloder prints similar error below. Invalid block tag on line 25: 'static'. Did you forget to register or load this tag? Though the same HTML works well if put directly inside the template. Thank for your help in advance. This is my second djangoCMS-based application and I have compared it with … -
when i try to activate my Virtual Environment its trows an error
**when i try to activate my venv its throw an error like " The module 'myworld' could not be loaded"** PS D:\Django> myworld\Scripts\activate.dat myworld\Scripts\activate.dat : The module 'myworld' could not be loaded. For more information, run 'Import-Module myworld'. At line:1 char:1 myworld\Scripts\activate.dat + CategoryInfo : ObjectNotFound: (myworld\\Scripts\\activate.dat:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoLoadModule ##Solution For This Error?? ! PS D:\Django> myworld\Scripts\activate.dat (myworld) C:\Users\Your Name> -
After adding a couple packages I got this error. django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple
after adiing the corsheaders and whitenoise packages to my api I got this error. (venv) kawekaweau@Ground-Control:~/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae$ python manage.py runserver Traceback (most recent call last): File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/manage.py", line 22, in <module> main() File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 234, in __init__ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple. File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/home/kawekaweau/Desktop/GeeksGeckosAndGoodVibes/Geckos/Gekkonidae/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 234, in __init__ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple. following is my settings file. minus some stuff """ Generated by 'django-admin startproject' using Django 4.2.2. from pathlib import Path # Build paths inside the project like this: … -
AttributeError 'model' object has no attribute 'get_choices'
I'm trying to send this model class Product(models.Model): title = models.CharField(max_length=100, verbose_name='title', unique=True) text = models.CharField(max_length=200, verbose_name='text', null=True, blank=True) price = models.BigIntegerField('price') description = models.CharField(max_length=500, verbose_name='description') category = models.ForeignKey(Category, on_delete=models.CASCADE) features = models.ManyToManyField(Features, ) created_time = models.DateTimeField(auto_now_add=True, verbose_name='created_time') update_time = models.DateTimeField(auto_now=True, verbose_name='update_time') The Product serializer class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) features = serializers.ManyRelatedField(child_relation=FeaturesSerializer()) rating = serializers.SerializerMethodField() class Meta: model = Product fields = ( "id", "title", "text", "price", "description", "category", "features", 'rating' ) I found out the problem is in the 'features' field, because if you remove this field in the serializer, then there is no more error, but instead of the 'features' fields, I get the id of the defined 'features' The Features serializer: class FeaturesSerializer(serializers.ModelSerializer): class Meta: model = Features fields = '__all__' Models: class Features(models.Model): key = models.CharField(max_length=200) value = models.CharField(max_length=200, unique=True) views.py class GetItemOfProduct(generics.RetrieveUpdateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAdminOrReadOnly, ] json without 'features' field in serializer: # ... product: title, id, price, description and other ... "features": [ 6, 4, 1 ], I tried to send 'features' field in json with key and value fields for example # ... product: title, id, price, description and other ... "features": [ { "id": 6, … -
Django Admin Inline - same UUID being generated for primary key
When I click on "add new button" in django admin to add another inline item. UUID field (primary key) is same for all inlines. see following gif: -
Image is not being upload Django
I created a post form and embedded with the template and view as usual, when I test the form and try to create a new post all the fields process and save the data correct to the object except the image object. It does not prompt me an error, it is like ignoring completely the file that I upload. The post model: from django.db import models from User.models import User class Post(models.Model): author = models.ForeignKey(User, related_name="post", on_delete=models.CASCADE) title = models.CharField(max_length=280) content = models.CharField(max_length=500) post_image = models.ImageField(upload_to="post_images/", blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The form class: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content', 'post_image'] The post_create view: def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): author = request.user title = form.cleaned_data['title'] content = form.cleaned_data['content'] post_image = form.cleaned_data['post_image'] post = Post.objects.create(author=author, title=title, content=content, post_image=post_image) return redirect("home") form = PostForm() return render(request=request, template_name="post/create_post.html", context={"form": form}) The create_post.html {% extends "base/base.html" %} {% block content %} <form method="POST" action="{% url 'create_post' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Create Post</button> </form> {% endblock %} The urls: from django.urls import path from . import views urlpatterns = [ path("create_post", views.create_post, name="create_post") ] When I create … -
Stripe integration is giving an error in views.py
my stripe integration code in the views.py code is following: def checkoutsession(request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': '20', 'quantity': 1, }, ], mode='payment', success_url='http://localhost:3000' + '/success.html', cancel_url='http://localhost:3000' + '/cancel.html', ) except Exception as e: return str(e) return HttpResponse(checkout_session.url, code=303) The error: AttributeError: 'str' object has no attribute 'get' the HTML code is following: {% extends 'basic.html' %} {% block body %} <script src="https://js.stripe.com/v3/"></script> <section> <div> <div> <h3>Pay</h3> <h5>$20.00</h5> </div> </div> <form action="/checkoutsession" method="POST"> {% csrf_token %} <button type="submit" id="checkout-button">Checkout</button> </form> </section> {% endblock body %} I am integrating a sandbox payment gateway. The frontend is displaying correctly , but the backend is problematic.I am using django framework. -
Nginx Is Showing the Default Page Instead of the Django Application
I am hosting a django website on gunicorn/nginx with ubuntu 22.04. I am following below guide for configuration. it is still showing the default nginx site. (I know there are similar question and also the troubleshooting guide and potential reasons also given in the document i am following; I tried everything but could not solve the issue. Infrastructure : 1) ubuntu 22.04 2) Hestial CP - Using for firewall instead using ufw (bcoz with Hestia default ufw is not installed) 3) Postgres 4) Django 5) gunicorn/nginx Followed all the steps and performed the verification at each stage the document suggest and its showing positive results. but when i am trying to access my site it is still showing the default nginx site. Configuration: etc/nginx/sites-available/myproject server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myuser/main/myproject; } location / { include proxy_params; proxy_pass //unix:/run/gunicorn.sock; } } etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/main/myproject ExecStart=/home/myuser/main/envProject/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Firewall (I have opened all major ports without ip restrictions, shall start closing once the setup works) PS: … -
Missing csrf_token in application cookies
I have problem with setting my csrf_token in cookies which i have to retrieve in order to use it in the next API call Response header Application cookies CSRFToken.jsx import React, { useState, useEffect } from "react"; import axios from "axios"; const CSRFToken = () => { const [csrftoken, setcsrftoken] = useState(''); const getCookie = (name) => { let cookieValue = null; if (document.cookie && document.cookie !== "") { let cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { let cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; useEffect(() => { const fetchData = async () => { try { await axios.get(`${import.meta.env.VITE_APP_API_URL}/api/csrf_cookie`); } catch (error) {} }; fetchData(); setcsrftoken(getCookie('csrftoken') || ""); }, []); return ( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} /> ); }; export default CSRFToken; Backend: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({ 'success': 'CSRF cookie set' }) Any help provided will be much appreciated, thanks! I should use csrftoken in API Call which i need to get from cookies, but they are not provided export const login = (email, password) => … -
API issue for webpage with Django+Rest backend and React+Axios frontend
I am developing a webpage ("loading" is rendered on the page when the datapoints cannot get fetched via the API) that will be used to display some data from a IOT project I am doing. The backend is written using Django with the Rest framework. The frontend is written in React and to handle http requests, axios is used. I am new to web development so I started writing everything without a thought of deploying and when I got everything up and running localhost on my maching, I started looking into how to deploy it. I then decided on using Docker, Nginx and Gunicorn to do this but seeing as I had written everything outside of docker, it was not as straight forward as I would have liked. I got everything to work except the API calls from axios to the backend. One of all the issues I have gotten is the Failed to load resource: the server responded with a status of 404 (Not Found).Here is the link to the Github repo where the code is stored, I figure it might be easiest to look through there because of the amount of code and me not understanding where the … -
how i can put two action for a html-python from?(Django)
I working on a django project which is employee management system. every employee has a card fill with personal information and this is a text box and a dislike button in form, working like that every time manager fill textbox with a number and pressing dislike button and the amount from salary and a SMS going to employee phone number. now I added a like button and i want when employee input a number and pressing like button employee have a increase on salary as given amount. have i can put two action on my form? view.py class PenaltyEmployee(LoginRequiredMixin, UserPassesTestMixin, generic.View): def post(self, request, pk): employee = get_object_or_404(Employee, pk=pk) penalty_amount = int(request.POST.get('penalty_amount')) employee.salary -= penalty_amount employee.save() employee_phone_number = employee.phon_number api_key ='#' url = '#/%s/#' %api_key pay_load = { 'sender' : '#', 'receptor': employee_phone_number, 'message': 'penalty' } res = requests.post(url, data = pay_load) return redirect('home') def test_func(self): return True and this is my list_view.html <form method="POST" action="{% url 'penalty' yaroo.pk %}"> {% csrf_token %} <input type="number" name="penalty_amount" placeholder="Enter penalty amount"> <button type="submit" class="btn btn-secondary"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" class="bi bi-hand-thumbs-down" viewBox="0 0 16 16"> <path> </path> </svg> </button> <p> | </p> <!-- ... this is my like button ... --> <button … -
boto3 call works in Python console but not in Django app -- exact same code, exact same machine
I have the following piece of code. (Redacting the value of COGNITO_POOL, but otherwise this is the exact code I am running.) AWS_REGION = "us-gov-west-1" COGNITO_POOL = "**********" import boto3 def demo(): client = boto3.client("cognito-idp", region_name=AWS_REGION) output = client.list_users( UserPoolId=COGNITO_POOL, Filter='email = "test@email.com"' ) print(output) I am running this on an EC2 instance, which has all the right permissions set up. I know it has the right permissions, because when I remote into the instance, open a Python shell, run the above code, and call demo(), it works fine and spits out a list. However, when a Django website running on the same machine imports the demo() method and runs it, I get: botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the ListUsers operation: The security token included in the request is invalid. I have done everything I can think of to make the shell run under the same conditions as Django. I tried activating my virtual environment before running the test. I tried writing a script that would import the demo function and execute it, then ran that script from the command line. I ran it under the same user as Django. No matter what I do, shell works and … -
How do I solve GET 500 (Internal Server Error) error?
After the + button is clicked The quantity increases when I refresh the page The console shows the 500 Internal Server Error every time I click the + button. Also, the ajax coding for the button only works when I refresh the page. Could someone enlighten me what causes this error and how to solve it? related section in cartpage.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="d-flex"> <div class="border rounded p-4 m-4" style="width:1000px;"> <p class="display-4 pl-4 ml-4">Shopping Cart</p> <hr> <table class="table table-fixed"> <thead class="thead-dark"> <tr> <th></th> <th class="w-5">Image</th> <th>Product</th> <th>Quantity</th> <th>Price</th> </tr> </thead> <tbody> <tr> {% for cart in cart %} <td><ion-icon name="close-outline"></ion-icon></td> <input type="hidden" name="prodid" value="{{product.ProdID}}" id="prodid" class="prodid"> <td class="w-5"><image src="{{ cart.product.ProdPic.url }}" style="height:80px; width:65px;" class="rounded-circle"></td> <td>{{cart.product.ProdName}}</td> <td class="cart-product-quantity"> <input type="button" pid = "{{ cart.product.ProdID }}" class="minus-cart btn btn-light btn-circle btn-sm" value="-"></input> <span id="quantity" min="1">{{ cart.item_qty }}</span> <input type="button" pid = "{{ cart.product.ProdID }}" class="plus-cart btn btn-light btn-circle btn-sm" value="+"></input> </td> <td>RM{{cart.product.ProdPrice}}</td> </tr> {% endfor %} </tbody> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <!-- links to popper js and bootstrap js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <script> $(document).ready(function(){ $('.plus-cart').click (function(){ var id=$(this).attr("pid").toString(); console.log(id) $.ajax({ type : "get", url … -
ImportError: cannot import name 'People' from partially initialized module 'Contacts.models' (most likely due to a circular import)
I have two models. People and Related Contacts. Related contacts has a foreign key relation from People. I don't understand why I'm getting a circular import yet they are not related to each other. The error from Miscellaneous.models import PersonContactTypes, Genders File "D:\Projects\Amicas\Back-End\Miscellaneous\models.py", line 2, in <module> from Contacts.models import People ImportError: cannot import name 'People' from partially initialized module 'Contacts.models' (most likely due to a circular import) Company model class Companies(models.Model): contact_type = models.ForeignKey(CompanyContactTypes, verbose_name='Contact Type', on_delete=models.CASCADE, max_length=255, null=True, blank=True) created_by = models.ForeignKey(User, verbose_name="Created By", on_delete=models.CASCADE) tenant = models.ForeignKey(Tenant, verbose_name='Tenant', max_length=255, null=True, blank=True, on_delete=models.CASCADE) People model from Tenants.models import Tenant from django.db import models from Members.models import User from django_countries.fields import CountryField from Miscellaneous.models import PersonContactTypes, Genders class People(models.Model): contact_type = models.ForeignKey(PersonContactTypes, verbose_name='Contact Type', on_delete=models.CASCADE, max_length=255, null=True, blank=True) gender = models.ForeignKey(Genders, verbose_name='Gender', on_delete=models.CASCADE, max_length=255, null=True, blank=True) created_by = models.ForeignKey(User, verbose_name="Created By", on_delete=models.CASCADE) company = models.ForeignKey(Companies, verbose_name='Company', max_length=255, null=True, blank=True, on_delete=models.SET_NULL) tenant = models.ForeignKey(Tenant, verbose_name='Tenant', max_length=255, null=True, blank=True, on_delete=models.CASCADE) Related Contacts model from django.db import models from Contacts.models import People from Tenants.models import Tenant from Members.models import User class RelatedContacts(models.Model): name = models.ForeignKey(People, verbose_name='Name', null=True, blank=True) created_by = models.ForeignKey(User, verbose_name="Created By", on_delete=models.CASCADE, blank=False, null=False) tenant = models.ForeignKey(Tenant, verbose_name='Tenant', max_length=255, null=False, … -
Limit Foreignkey choices in form
I have a form which has a foreignkey field 'mon_1', I am trying to limit it's choice by using init () method, but no changes is reflected in my webpage (Even if I make errors intentionally, it doesn't throw an error). Note: 'limit_choices_techers' function works fine, no error in that piece of code #forms.py def limit_choices_teachers(period): limited_choice = [] already_used_choice = TimeTable.objects.values_list(period,flat=True) #returns id of the teacher already linked on that period for teacher in Teachers.objects.all(): if teacher.id not in already_used_choice: limited_choice.append(teacher) return limited_choice class TimeTableForm(forms.ModelForm): class Meta(): model = models.TimeTable fields = ('__all__') def __init__(self, *args, **kwargs): super(TimeTableForm, self).__init__(*args, **kwargs) self.fields['mon_1'].queryset = limit_choices_teachers('mon_1') #models.py class Subjects(models.Model): Subjects_available = ( ('Maths','Maths'), ('English','English'), ('Computer','Computer'), ('Chemistry','Chemistry'), ('Physics','Physics'), ) subject_name = models.CharField(max_length = 256,choices = Subjects_available,unique=True) def __str__(self): return str(self.subject_name) class Teachers(models.Model): classes_available = ( ('Grade 1','Grade 1'), ('Grade 2','Grade 2'), ('Grade 3','Grade 3'), ('Grade 4','Grade 4'), ('Grade 5','Grade 5'), ('Grade 6','Grade 6'), ('Grade 7','Grade 7'), ('Grade 8','Grade 8'), ('Grade 9','Grade 9'), ('Grade 10','Grade 10'), ('Grade 11','Grade 11'), ('Grade 12','Grade 12'), ) name = models.CharField(max_length = 256) subject = models.ForeignKey(Subjects,on_delete=models.CASCADE,related_name='teacher_subject') teaches_for_class = models.CharField(max_length=256,choices=classes_available) def __str__(self): return str(self.subject) + ' - ' + self.name class TimeTable(models.Model): standard_choice = ( ('Grade 1','Grade 1'), ('Grade 2','Grade … -
How to delete password form (ps i ve redefined user model, authentication)?
i ve got a problem. First of all this is my idea: a user registers his account using username and his face. The website takes his photo. And so ive redefined authenctication, user model and so on. But i CANT DELETE PASSWORD FORM!!! let me show you my code first models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. \#user's part class UserManager(BaseUserManager): def create_user(self, username, \*\*extra_fields): if not username: raise ValueError('Users must have an username ') user = self.model( username=username, **extra_fields ) user.set_unusable_password() user.save(using=self._db) return user def create_staffuser(self, username): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( username, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, username): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( username, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): username = models.CharField( verbose_name='username', max_length=255, unique=True ) main_img = models.ImageField(upload_to='main_imgs/%Y/%m', verbose_name='Главное фото') checking_photo = models.ImageField(upload_to='checking_photo/%Y/%m', verbose_name='Временное фото для проверки ') is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a … -
why stripe button is not appearing?
I am integrating stripe checkout gateway in my website. For this , I am following a tutorial for this. I am copying its code as it is. However, the button is not displaying for me. {% extends 'basic.html' %} <h2> buy</h2> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ key }}" data-description = "payment gateway" data-amount = "500" data-locale="auto"> </script> I know that their is no button tag but the tutorial I am following is also the same . I tried to implement a button which will take me to the checkout form.