Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch: Reverse for 'view_director' with arguments '('',)' not found. 1 pattern(s) tried: ['crew/view_director/(?P<dslug>[-a-zA-Z0-9_]+)\\Z']
i made two apps called crew which contains the table Director and movie which contains the table Movie when i try to click this link, it shows the error given above. <a href="{% url 'crew:view_director' director.slug %}"> <img src="{{mov.director.photo.url}}" class="card-img-top rounded-0" alt="..."> </a> urls.py from django.urls import path from crew import views app_name='crew' urlpatterns = [ # function based path path('view_director/<slug:dslug>',views.view_director,name='view_director'), ] views.py from django.shortcuts import render from crew.models import * # Create your views here. def view_director(request,dslug): director=Director.objects.get(slug=dslug) return render(request,'director_detail.html',{'director':director}) models.py from django.db import models # from movie.models import Movie # Create your models here. class Director(models.Model): name=models.CharField(max_length=30,blank=True,null=True) photo=models.ImageField(upload_to='crew/director') slug=models.SlugField(max_length=50,unique=True,blank=True) # movies=models.ForeignKey(movie.Movie,on_delete=models.CASCADE,null=True) about=models.TextField(max_length=2000,blank=True) def __str__(self): return self.name also iam not getting the directors name and image from this code on the movie detail page <div class="card rounded-0" style="width: 14rem;"> <a href=""> <img src="{{mov.director.photo.url}}" class="card-img-top rounded-0" alt="..."> </a> <div class="card-body"> <h5 class="card-title">{{mov.director.name}}</h5> <p class="card-text">Director</p> </div> </div> How can i get the director detail page and display those details on the movie detail page, what am i doing wrong here ? -
django create object and many to many relationship in bulk
Hi I am trying to create multiple objects in bulk with a specific many to many field id specified. Looking at the documentation found this: >>> e = b.entry_set.create( ... headline="Hello", body_text="Hi", pub_date=datetime.date(2005, 1, 1) ... ) This works fine and creates the entry object as well as the many-to-many field relation as well. So modified this to handle bulk_creates: >>> e = b.entry_set.bulk_create( ... entry_objects ... ) This does create the entry objects however the many-to-many relation is not getting created in the database. Am I missing something here? -
Getting django.http.request when print for loop content
In django, I am trying to view google search result (2) for a keyword by using beautifulsoup. but when enter keyword I am getting result as "Source code for django.http.request https://docs.djangoproject.com/en/2.1/_modules/django/http/request/" views.py from django.shortcuts import render import requests # 👉️ Requests module from bs4 import BeautifulSoup # 👉️ BeautifulSoup module from django.http import HttpResponse def search(request): if request.method == "POST": url = f"https://www.google.com/search?q={request}" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } response = requests.get(url, headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") results = [] search_results = soup.select("div.g") for result in search_results[:2]: # Limiting to the first 2 results title = result.select_one("h3").get_text() #description = result.select_one("div.IsZvec").get_text() link = result.select_one("a").get("href") results.append({"title": title, "link": link}) return render(request, "result.html", {"results":results}) return render(request, "result.html") Here is the template I am using as html template HTML Template <!DOCTYPE html> <html> <head> <title>Django FBV With Beautifulsoup</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <style> p { font-size: 20px } h1 { text-align: center; } </style> <body> <div class="container"> <h1 class="mt-5 mb-5">Get Title From Any Website</h1> <!-- Form --> <form method="POST" action="{% url 'results' %}"> {% csrf_token %} <div class="mt-4"> <div class="col"> <input type="text" name="keyword" class="form-control" placeholder="Enter keyword" rows="5" required="required"> </textarea> </div> … -
Using Postgres 'delete field' jsonb operator with Django ORM
I am using Postgres 14, Django 4.1, and Python 3. I have a JSONB field which contains a lot of data. To reduce bandwidth, I am reducing the amount of data selected by using the #- operator. This works, but now because of the way I queried it, the model no longer matches and my JSONField() doesn't parse. I would like to retain the model somehow, so the getters and setters are retained. Is there a way I can annotate this extra selection so that it matches or casts to my model? Here is my model: class MyModel(Model): class Meta: managed = True db_table = "MyModel_data" id = UUIDField(primary_key=True, default=uuid.uuid4) created_at = DateTimeField(auto_now_add=True, blank=True, null=False) _data = JSONField(db_column="data", blank=False, null=False, encoder=DjangoJSONEncoder) @property def data(self) -> Any: return cast_deep_floats(self._data) @data.setter def data(self, value: Any) -> None: self._data = value And here is my controller: search = MyModel.objects.filter(id=123).order_by('-created_at') excluded_data_points = ['incredibly_large_field', 'another_incredibly_large_field'] excluded_data_query = 'data #- ' + ' #- '.join(["'{%s}'" % f for f in excluded_data_points]) result = search.extra( select={ 'data': excluded_data_query } ).values('data').first() found = None try: found = json.loads(result['data']) except: # pylint: disable=bare-except pass I have tried a ton of variations of .annotate(data=Cast('data', .....) but I keep running into … -
I got a problem runing a django project and got this error DataFrame.drop() takes from 1 to 2 positional arguments but 3 were given
def forecast(request): global graph if request.user.is_authenticated: pass else: return redirect('/login') if request.method == "POST": stock_name = request.POST.get('stock_name') pred_df, df = calPred(stock_name) graph = None plot1(df, pred_df, "Stock Price Prediction of "+str(stock_name), 'Date', 'Price', 'blue') print(pred_df.reset_index().columns) pred_df = pred_df.reset_index() pred_df['index'] = pred_df['index'].astype(str) json_records = pred_df.to_json(orient='records') data = json.loads(json_records) df = df.reset_index() df['Date'] = df['Date'].astype(str) df['Open'] = df['Open'].astype(float) df = df.iloc[::-1] json_records2 = df.head(120).to_json(orient='records') data2 = json.loads(json_records2) context = { 'chart': graph, 'd' : data, 'd2' : data2, 'visible': "visible", } #print('GG :: ',graph) return render(request, 'forecast.html', context) context = {'visible': "invisible"} return render(request, 'forecast.html',context) Internal Server Error: /forecast/ Traceback (most recent call last): File "C:\Users\ngeti\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ngeti\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ngeti\OneDrive\Desktop\c\Stock_price_Prediction-main working\stock\views.py", line 162, in forecast pred_df, df = calPred(stock_name) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\ngeti\OneDrive\Desktop\c\Stock_price_Prediction-main working\stock\views.py", line 201, in calPred x = np.array(df.drop(['Prediction'], 1)) ^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: DataFrame.drop() takes from 1 to 2 positional arguments but 3 were givenDD -
NoReverseMatch at / Reverse for 'category_posts' with arguments '('',)' not found
im currently working on website, which can show posts written by people. For this posts i have a database. On the main i need to show all the posts which i have in database. There should be some link which will go to page with posts information. I have trouble with all pages - there is error NoReverseMatch at / Reverse for 'category_posts' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category_slug>[-a-zA-Z0-9_]+)/\\Z']. When i open my website locally it shows that the error in <a class="text-muted" href="{% url 'blog:category_posts' post.category.slug %}"> There is the code: views.py def category_posts(request, category_slug): template = 'blog/category.html' posts = Post.objects.select_related( 'author', 'category', 'location', ).filter( category__slug=category_slug, is_published=True, pub_date__lte=now()) category = get_object_or_404( Category.objects.select_related('title', 'description', 'slug') .filter(is_published=True), slug=category_slug ) context = {'posts': posts, 'category': category} return render(request, template, context) urls.py from blog import views from django.urls import path app_name = 'blog' urlpatterns = [ path('', views.index, name='index'), path('post/<int:pk>/', views.post_detail, name='post_detail'), path('category/<slug:category_slug>/', views.category_posts, name='category_posts'), ] category_link.html <a class="text-muted" href="{% url 'blog:category_posts' post.category.slug %}"> «{{ post.category.title }}» </a> -
request.session.clear() vs request.session.flush() in Django
I tried both request.session.clear() and request.session.flush() and they deleted all session data and logged a user out. Actually, there is the explanation for request.session.flush() as shown below while there isn't for request.session.clear(): Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it). My questions: What is the difference between request.session.clear() and request.session.flush()? Which should I use basically? -
Configuration of Django-admin fields
I’m trying to adjust the following logic: there is field 1 - BooleanField and field 2 - CharField, if field 1 = True, then field 2 is open for enter information. Otherwise the information in field 2 is erased and the field is closed for input. Now it is realized only at the level of the form of product creation through JS. If you save the product and open it for editing, the field state is reset. To save the status it is written as follows: Admin.py class SmartPhoneAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not kwargs.get('instance').sd: self.fields['sd_value'].widget.attrs.update({ 'readonly': True, 'style': 'background: #050505;' }) def clean(self): if not self.cleaned_data['sd']: self.cleaned_data['sd_value'] = None return self.cleaned_data The problem is that the expression kwargs.get('instance') returns None and I get an error. attributeerror: 'nonetype' object has no attribute 'sd' and i don't understand why instance = None. Full code: Admin.py class SmartPhoneAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not kwargs.get('instance').sd: self.fields['sd_value'].widget.attrs.update({ 'readonly': True, 'style': 'background: #050505;' }) def clean(self): if not self.cleaned_data['sd']: self.cleaned_data['sd_value'] = None return self.cleaned_data class SmartPhoneAdmin(admin.ModelAdmin): change_form_template = 'admin.html' form = SmartPhoneAdminForm prepopulated_fields = {'slug':('title',)} def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'category': return ModelChoiceField(Category.objects.filter(slug = 'smartphone')) return … -
pipenv failed to lock when trying to install mysqlclient in a django project
I tried running pipenv install mysqlclient in terminal here is the error message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Resolving mysqlclient... Adding mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock (a01621) out of date, updating to (b35795)... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ⠹ Locking... ERROR:pip.subprocessor:[present-rich] Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/resolver.py", line 811, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/resolver.py", line 759, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/resolver.py", line 738, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 1165, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 964, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 701, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv run pip install <requirement_name> to bypass this mechanism, then run … -
ImportError: cannot import name 'Movie' from partially initialized module 'movie.models' (most likely due to a circular import)
I have two apps, crew and movie, i've put the Movie table as a foreignkey to models on crew like actor,director etc so that i can access filmography of each of them. Also i did the same on Movie table to select each crew member while adding a movie details. but after entering python manage.py makemigrations iam getting the above error. crew/models.py This is where the error is showing from django.db import models from movie.models import Movie # Create your models here. class Crew_Temp(models.Model): name=models.CharField(max_length=30,blank=True,null=True) about=models.TextField(max_length=2000,blank=True,null=True) class Actor(models.Model): name=models.CharField(max_length=30,blank=True,null=True) photo=models.ImageField(upload_to='crew/actor') slug=models.SlugField(max_length=50,unique=True,blank=True) about=models.TextField(max_length=2000,blank=True) def __str__(self): return self.name class Director(models.Model): name=models.CharField(max_length=30,blank=True,null=True) photo=models.ImageField(upload_to='crew/director') slug=models.SlugField(max_length=50,unique=True,blank=True) about=models.TextField(max_length=2000,blank=True) def __str__(self): return self.name class Writer(models.Model): name=models.CharField(max_length=30,blank=True,null=True) photo=models.ImageField(upload_to='crew/writer') slug=models.SlugField(max_length=50,unique=True,blank=True) about=models.TextField(max_length=2000,blank=True) def __str__(self): return self.name class Cinematographer(models.Model): name=models.CharField(max_length=50, blank=True,null=True) photo=models.ImageField(upload_to='crew/cinematographer') slug=models.SlugField(max_length=50,unique=True,blank=True) about=models.TextField(max_length=2000,blank=True) def __str__(self): return self.name class Genre(models.Model): genre=models.CharField(max_length=10,blank=True) movies=models.Foreignkey(Movie,on_delete=models.CASCADE,null=True) def __str__(self): return self.genre class Certification(models.Model): certification=models.CharField(max_length=10,blank=True) movies=models.Foreignkey(Movie,on_delete=models.CASCADE,null=True) def __str__(self): return self.certification class Streaming(models.Model): logo=models.ImageField(upload_to='streaming/logo',blank=True,null=True) name=models.CharField(max_length=30,blank=True,null=True) def __str__(self): return self.name movie\models.py I haven't put the actor field yet because i dont know how to add more than one values to a field. from django.db import models from django.contrib.auth.models import User from crew.models import * from review_awards.models import * # Create your models here. class Movie(models.Model): name=models.CharField(max_length=100,unique=True,blank=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) … -
Django Static txt file not loading
This is my template file in blog app {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> </head> <body> <h1>Hello, world! Blog</h1> <a href="{% static 'blog/mystatic.txt'%}">Click Me</a> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script> </body> </html> There is a static file in blog app 'mystatic.txt', which I am trying to load using anchor tag in above code, which is giving me error. I want to know why this is happening and what can I do to resolve it. -
Django with fetch any template [closed]
I created a Django project that uses RestframeWork but the END front of the project is outside the premises. So from a simple HTML file I can make Get and post with JavaScript using fetch. I manage to recover data from Django and make a registration but I cannot connect a user with the end point of Django which uses the login function, function to use by the administration panel. With a template I receive the session but apart from Localhost I cannot have a session, can I have your opinions? -
Sendig data from view.py to forms.py
I am working on a django-project for practice arithmetics. In a form the users may choice different difficulty levels. The options depends on the grade (in German "Jahrgang" = "jg"). In my view.py I can show the grade of the user ("print(user.jg)") ... and in the forms.py I can filter by the grade ("...filter(bis_jg__gte= 8") ... but how can I send the data (user.jg) to the filter (..filter(bis_jg__gte= user.jg)? the forms.py: def optionen(req, slug): kategorie = get_object_or_404(Kategorie, slug = slug) form = AuswahlForm(kategorie = kategorie) user = get_user(req.user) print(user.jg) zaehler = get_object_or_404(Zaehler, kategorie = kategorie, user = user) if req.method == 'POST': form = AuswahlForm(req.POST, kategorie = kategorie) if form.is_valid(): optionen_text = ';'.join(map(str, form.cleaned_data['optionen'])) if optionen_text == "": optionen_text = "keine" else: optionen_text = "keine" else: anzahl = kategorie.auswahl_set.all().count() if anzahl>0: anzahl = Auswahl.objects.filter(bis_jg__gte = user.jg, bis_stufe__gte = user.stufe, kategorie = kategorie).count() if anzahl>0: return render(req, 'core/optionen.html', {'kategorie': kategorie, 'auswahl_form':form}) and the relevant part in views.py: def optionen(req, slug): kategorie = get_object_or_404(Kategorie, slug = slug) form = AuswahlForm(kategorie = kategorie) user = get_user(req.user) print(user.jg) ... if req.method == 'POST': form = AuswahlForm(req.POST, kategorie = kategorie) When I add "form = AuswahlForm(req.POST, kategorie = kategorie , jg = user.jg)" to views.py … -
Display encoded video frames using React and Django
I'm new to web development and have been trying to solve a problem for some time but no luck. I'm using React and Django The thing is, there is a 3rd party application that performs some image processing using opencv on video frames and I've to display those encoded frames on the web browser. I want to receive those frames using Django API, decode them, and display them using React JS, also returning a response with every frame to that 3rd party app. I've prepared a flowchart of how things should work but haven't been able to start at all. Flowchart: The outcome on the browser should appear something like this. Outcome: Need to know how to approach this, shall I use WebSockets or can I send the encoded frames directly to React taking Django out of the picture. -
I need Barcode and QR code generating at the same time need printing through printer using django framwork
Multiple barcodes or QR codes I am unable to print dynamically from the front-end by selecting the number of barcodes/QR codes per Row and Number of rows and dynamic Height and width and space between and Row width and Height and padding all are dynamically selected from the front-end after submitting the form I need direct printing required through the printer. Actually, we have different types of stickers and their own sizes of multiple sizes, selection of each input from the front-end only. I mean that Barcode or QR code width and height, padding, margin, Number of rows, and each row how many barcodes or QR codes need to print with a label and sometimes without a label and how many rows I need and some times serial numbers following based on some serial numbers needed the barcode and QR code which selected from front-end. Dynamically I need to generate barcode/QR codes and at the same time, I need printing from a given printer. -
Django: How do I use a composite key as USERNAME_FIELD for django.contrip.auth.models.AbstractUser?
I have a custom user model extending django.contrip.auth.models.AbstractUser. The code model is as follows: class User(AbstractUser): name = "user" ROLE_CHOICES = [ # ...role choices ] email = models.EmailField() username = None role = models.CharField(choices=ROLE_CHOICES, default="CONSUMER", max_length=255) profile_picture = models.URLField(blank=True, null=True) dob = models.DateField(null=True, blank=True) country = models.CharField(blank=True, max_length=255) EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = ['email'] class Meta: verbose_name = "user" verbose_name_plural = "users" constraints = [ models.UniqueConstraint(fields=['email', 'role'], name='unique_email_per_role') ] Now I am getting error on USERNAME_FIELD because username has to be unique, but for my use case I want to keep the email unique per role. I have seen in django.contrib.auth.model.User there is is_staff column to identify staff role but in that way I do not want to keep on adding columns for every role. how do I define username for my model then? So that I can login to the django admin panel. -
Docker-compose with django and postgresql could not translate host name "db" to address: Name or service not known
I built a system using docker compose with 2 container, one for django and the other one for my database postgresql. I have this error django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution when I am trying the create a django superuser My docker-compose.yml : version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres networks: - mynetwork web: build: . command: bash -c "sleep 10 && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - DB_HOST=db # Définir DB_HOST pour correspondre au nom du service db dans docker-compose.yml depends_on: - db networks: - mynetwork networks: mynetwork: driver: bridge My Dockerfile : # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ In the seeting.py file of my project : import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'dbdo', 'PORT': 5432, #default port you don't need to mention in docker-compose } } The containeurs seem to work correctly, I can see my django app page and navigate. But … -
How to create a button to add items to cart?
This is the page I have created This is the views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import Pizza # Create your views here. def index(request): pizzas = Pizza.objects.all().order_by('price') context = { 'pizzas': pizzas } return render(request, 'menu/index.html', context) And this is the index.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> <link rel="stylesheet" href="{% static 'menu/style.css' %}"> </head> <body> <a href="{% url 'main:index' %}"><img id='logo' src="{% static 'menu/images/small_logo.png' %}"></a> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <table> <tr> <td id="one" ><b>{{pizza.name}}</b></td><td id="two">{{pizza.price | floatformat:2}}$</td> </tr> </table> <li id="ing">{{pizza.ingredients}}</li> {% if pizza.vegetarian %} <li style="background-color:#DD7835; padding:3px; width:90px; font-size:13px; text-align:center; border-radius:10px; font-weight:bold; " >VEGETARIAN</li> {% endif %} {% endfor %} </ul> </body> </html> How can I add buttons on my page where the user can add the pizzas to cart and the data is stored in the /admin page? this is my admin.py: from django.contrib import admin from .models import Pizza class PizzaAdmin(admin.ModelAdmin): list_display = ('name','ingredients','vegetarian','price') search_fields = ['name'] admin.site.register(Pizza, PizzaAdmin) # Register your models here. At the backend, the quantity of pizzas that the customer has ordered should be visible. -
How do I use HTMX with Django class based views?
I'm fairly new to htmx and django. I can implement htmx through function-based views OK, as I just call the function and return a partial.html file into the page. Howeverm I don't understand how to make it work with class-based views I'm now using in Django. I'd like to load comments on a blog post when a user clicks the Load comments button. My thought is that I'd need to use htmx to do a swap or insertion into a point on my page where I want the comments loaded. Here is my DetailView where I load the detail of an individual post. class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get(self, request, **kwargs): print("method is being called") return render(request, "partial.html") Here is my partial.html file that I'd like to be loaded into the page once the button on my post_detail.html page is clicked: <h2 class="mt-2 mb-2">Comments:</h2> {% if post.comments.all %} {% for comment in post.comments.all %} <div class="relative grid grid-cols-1 gap-4 p-4 mb-8 border rounded-lg bg-white shadow-lg"> <div class="relative flex gap-4"> <div class="flex flex-col w-full"> <div class="flex flex-row justify-between"> <p class="relative text-xl whitespace-nowrap truncate overflow-hidden">{{ comment.commenter }}</p> <a class="text-gray-500 text-xl" href="#"><i class="fa-solid fa-trash"></i></a> </div> <p class="text-gray-400 text-sm">{{ comment.date_added … -
Column Foreign key is of type bigint but expression is of type uuid in Django
I want to use UUIDField for primary key. This is my model: class Organization(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=124) All things is good. But when I want to use id of Organization model for ForeignKey in this model: class Member(models.Model): reference = models.ForeignKey('Organization', null=True, on_delete=models.PROTECT) name = models.CharField(max_length=124) I got this error: django.db.utils.ProgrammingError: column "reference" is of type bigint but expression is of type uuid LINE 1: "reference" = 'af104709-... ^ HINT: You will need to rewrite or cast the expression. What can I do? -
Django starts with another view endpoint before finishing the process in the first view endpoint
What I'm trying to do is create a User object first and then another Team Leader object in which the user attribute is linked to the same User object created. However, what happens is the Create Team Leader is being called BEFORE the Create User is done processing. Here is the Team Leader Model: class TeamLeader(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=100,blank=True) lastName = models.CharField(max_length=100,blank=True) email = models.CharField(max_length=100,blank=True) username = models.CharField(max_length=100,blank=True) employeeRole = models.CharField(max_length=100,blank=True) bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blankprofile.png') location = models.CharField(max_length=100,blank=True) def __str__(self): return self.user.username I'm sending two post requests to my APIs using fetch in Javascript. Below is my code for the post requests. The first one creates the User object first, then the next one for the Team Leader object. let userUrl = homeUrl + 'api/createuser/' fetch(userUrl,{ method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({"username": username, "first_name": firstname, "last_name": lastname, "email": email, "password": password1, "employeeRole": employeeRole, "teamLeader": teamLeader, }), } ) if (employeeRole == 'Member') { var regisUrl = homeUrl + 'api/createMember/'; } else { var regisUrl = homeUrl + 'api/createTeamLeader/'; } fetch(regisUrl,{ method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({"username": username, "first_name": firstname, "last_name": lastname, "email": email, "password": password1, "employeeRole": employeeRole, "teamLeader": teamLeader, }), } … -
Django Error - Product Does Not Exist when clicking Buy button for first item in cart (If you have more than one product it works)
I'm a Django beginner working on a Django shopping website. When a user clicks the "Buy" button for a product, it should create an order and remove the product from the cart. However, I'm encountering an issue where I get a DoesNotExist error when trying to buy the first product that is added to the cart (If i add two products then it works). The error says "No Product matches the given query." and it is raised by the placeOrder view. This error only occurs for the first product that is added to the cart. If I add more products to the cart, I can buy them without any issues. I've checked the database and the product IDs are correct. I've also tried clearing the session and cache but it didn't resolve the issue. views.py from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth import login, logout, authenticate from .forms import * from .models import Product, Cart from django.http import HttpResponse from django.urls import reverse # Create your views here. def home(request): products = Product.objects.all() context = { 'products': products } return render(request, 'website/home.html', context) # def placeOrder(request, i): # customer = Customer.objects.get(id=i) # form = createorderform(instance=customer) # if request.method == … -
django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name
I want to obtain the password_reset_done page when user has forgotten the password or username.On the login page there is a link written "forgot password or username", when a user clicks that link he will be directed to the password_reset page where an email address is entered.After the user has entered the email,he is supposed to be directed to the password_reset_done page but the above error pops out My urls.py file looks like this from django.contrib import admin from django.urls import path from app1.views import profile, welcome_view urlpatterns = [ path('accounts/', include(('django.contrib.auth.urls', 'auth'), namespace='accounts')), path('accounts/profile/', profile, name ='profile'), path('admin/', admin.site.urls), path('', views.welcome_view, name ="welcome_view"), ] -
I am trying to deploy docker image in to Aws lightsail Container
The problem is related to the Invalid HTTP_HOST header error in Django application. This error occurs when the HTTP_HOST header of an incoming request does not match any of the values specified in the ALLOWED_HOSTS setting in Django application. the error message indicates that the HTTP_HOST header received was '172.26.43.151:8000', and it suggests adding '172.26.43.151' to the ALLOWED_HOSTS list. To address the issue, I made the following changes: In my Django settings file (settings.py), i modified the ALLOWED_HOSTS setting to ALLOWED_HOSTS = ['*'], allowing any host to access your application. This change was made to accommodate the dynamic IP address of the Lightsail container. i updated the Nginx configuration file (default.conf) to listen on port 80 and forward requests to the Django application running on port 8000. i built the Docker image based on the provided Dockerfile, which sets up the necessary dependencies, installs the required packages, and configures Gunicorn as the application server. In Docker Compose configuration file (docker-compose.yml), i specified the port mapping as "80:8000", which maps port 80 of the host machine to port 8000 of the Docker container, allowing incoming requests to reach the Django application. Despite these changes, i still encountered the Invalid HTTP_HOST header … -
Django + Vue.js app: CORS blocks requests from getting to the backend
I am trying to deploy a Django + Vue.js app to an EC2 instance, after confirming that everything works correctly when running locally. Inside my Vue.js components, I have requests that look like this (using axios): const response = await this.$http.get('http://localhost:8000/api/foo'); However, firefox shows the following error in the console: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/foo/. (Reason: CORS request did not succeed). Status code: (null). When looking at the Django logs, there is no log of ever getting a GET request, so I believe that the request is being blocked before ever getting to the backend. I am sure that the django backend is listening on port 8000, since I can use wget inside the EC2 instance and get correct results back. The Django backend is configured to allow all CORS origins, I think having the whitelist is overkill but I'm trying to make sure that's not the issue: INSTALLED_APPS = [ ... 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] ALLOWED_HOSTS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = "*" CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', 'http://127.0.0.1:8000' ] Since the request is not getting to the backend, I figured that maybe nginx is responsible …