Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I fix a 'IntegrityError at /admin/orders/order/add/' when FOREIGN KEY constraint failed?
I created the order model for Django rest API, and when I tried to add an order I got an error: django.db.utils.IntegrityError: FOREIGN KEY constraint failed That's the content of models.py : from django.contrib.auth import get_user_model User= get_user_model() class Order(models.Model): SIZES= (('SMALL','small'), ('MEDIUM','medium'), ('LARGE','large')) ORDER_STATUS= (('PENDING','pending'),('IN TRANSIT','in transit'),('DELIVERED','delivered')) customer= models.ForeignKey(User, on_delete = models.CASCADE, null = True, db_constraint=False) size= models.CharField(max_length=20, choices=SIZES, default=SIZES[0][0]) order_status= models.CharField(max_length=20, choices=ORDER_STATUS, default=ORDER_STATUS[0][0]) quantity=models.IntegerField(default=1) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return f"<Order {self.size} by {self.customer.id}" and admin.py : from django.contrib import admin from .models import Order @admin.register(Order) #admin.site.register(Order) class OrderAdmin(admin.ModelAdmin): list_display=['size','order_status','quantity','created_at'] how can I fix it ?? -
django table onlineshop_product has no column named name
I work on my online shopping website with the help of Django. and I'm a beginner in Django The following code provides a table of my database. It helps to add a product class Product(models.Model): category = models.ForeignKey(Category,related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200,db_index=True) slug = models.SlugField(max_length=200,db_index=True) image = models.ImageField(upload_to='products/%y/%m/%d',blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Shows me an error in the browser. This error shows me when I add a product inside the admin panel. when I add the product the following error occurs. OperationalError at /admin/onlineshop/product/add/ table onlineshop_product has no column named name Exception Value: table onlineshop_product has no column named name -
How to solve pre-commit asserttion error on ubuntu 22.04
I am using ubuntu 22.04 and the python version is 3.10.4. I have installed a Django project with the cookie-cutter. and now I have got an error when I want to commit my changes. here is the error: (blog) ➜ blog git:(main) ✗ pre-commit run [INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: AssertionError: BUG: expected environment for python to be healthy() immediately after install, please open an issue describing your environment Check the log at /home/mahdi/.cache/pre-commit/pre-commit.log Content of pre-commit.log: ### version information ``` pre-commit version: 2.18.1 git --version: git version 2.34.1 sys.version: 3.10.4 (main, Apr 2 2022, 09:04:19) [GCC 11.2.0] sys.executable: /home/mahdi/.local/share/virtualenvs/blog-qatotdDy/bin/python os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: AssertionError: BUG: expected environment for python to be healthy() immediately after install, please open an issue describing your environment ``` ``` Traceback (most recent call last): File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/main.py", line 371, in main return run(args.config, store, args) File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/commands/run.py", line 414, in run install_hook_envs(to_install, store) File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/repository.py", line 221, in install_hook_envs _hook_install(hook) File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/repository.py", line 83, in _hook_install raise AssertionError( … -
make infinite scroll works with externals cdn call in the head
my infinite scroll is working but i notice some bugs.when the page loads before the infinite scroll calls everything is working fine but after the infinite scrolls call the fotorama is not working.the first solution i tried is to put the fotorama links to the event onAfterPageLoad but it is not working. html <head> .... <link href="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.js"></script> .... </head> <div class="infinite-container"> {% for post in posts %} ................. <div class="infinite-item"> <div class="fotorama" data-allowfullscreen="native" data-nav="false"> <img src="{{ post.image.url }}" loading="lazy"> </div> </div> ........................... {% endfor %} </div> {% if posts.has_next %} <a class="infinite-more-link" href="?page={{ posts.next_page_number }}"></a> {% endif %} <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> How can i achieve this ? -
I have created Multiple User Type Registration using Django rest-auth by using below article .Now how can i generate login logout for the user?
I follow this article Thanks In advance -
How to save user profile model with image field and user field as OneToOneField variable in django rest framework
User model is as follow. class User(AbstractUser): username = None email = models.EmailField('email address', unique=True) first_name = models.CharField('First Name', max_length=255, blank=True, null=False) last_name = models.CharField('Last Name', max_length=255, blank=True, null=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] User Profile model is as follow. class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) avatar = models.ImageField(upload_to=avatar_image, blank=True, null=True) -
django-rest-framework - How to create seperate profiles for users based on is_staff
I am working on a job portal project. I am using custom user model class UserManager(BaseUserManager): def create_user(self, email, name, password=None, **extra_fields): if not email: raise ValueError('Users must have an email address') if not name: raise ValueError('Users must have a name') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.name = name user.save(using=self._db) return user def create_staffuser(self, email, password, name): user = self.create_user( email, name, password=password ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, name, email, password): user = self.create_user(email, name, password=password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] And I have 2 separate models one for job seekers and other for employers. class SeekerProfile(models.Model): """Seeker profile for job seekers""" MALE = 'M' FEMALE = 'F' OTHERS = 'O' GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHERS, 'Others'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField() gender = models.CharField( max_length=1, choices=GENDER_CHOICES ) address = models.TextField() city = models.CharField(max_length=100) pincode = models.CharField(max_length=50) phone_number = models.CharField( max_length=50, null=False, blank=False, unique=True) disabled = models.BooleanField(default=False) user = models.OneToOneField( settings.AUTH_USER_MODEL, limit_choices_to={'is_staff': False}, on_delete=models.CASCADE ) def __str__(self): return self.first_name+" … -
Date based email notification in django
I am building a simple web application in Django and I wanted to add a reminder functionality to it. I decided to do with emails but the period of notifications must be specified by the user, not the admin. Are there any ways to do this? I checked celery but I am not sure that this can be implemented with it. Thanks in advance. -
Deploy Django site on netlify
I'm trying to upload my full-stack website, done with Django and React on Netlify. I have tried various ways and searched for different tutorials, but unfortunately I did not find them useful ... Many recommend using cactus to launch their own applications consisting of python, but I don't think it can work with Django, does anyone know how to do it or give me some advice? Thanks note: netlify is only for "static" websites, so how can I make my Django application "static"? -
Count number of replies on a particular post in Django
I want to count number of replies on a particular post in Django View.py **POST CODE** def forum(request): profile = Profile.objects.all() if request.method=="POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) REPLY CODE def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect('/forum') return render(request, "discussion.html", {'post':post, 'replies':replies}) model.py class Post(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post_id = models.AutoField post_content = models.CharField(max_length=5000) timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' class Replie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) reply_id = models.AutoField reply_content = models.CharField(max_length=5000) post = models.ForeignKey(Post, on_delete=models.CASCADE, default='') timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' I want to do like where on the place of Number of reply, I want to display the number of replies of the particular post please help me to figure it out -
Need help loading staticfiles with nginx and django to a container
I am having trouble loading the static files from my django project. Here is a picture of my directories: direcctories I have ran docker-compose up and I get the following errors: ERRORS Here is what my nginx (default.conf) file looks like: default.conf http { server { listen 8080; access_log /var/log/nginx/access.log location / { root /frontend/templates/frontend # proxy_pass http://pathfinder_gunicorn; # include /etc/nginx/mime.types; } location /static/ { alias /static/; } location ~ \.(css)$ { root /frontend/static/css; } } } Here is my Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /pathfinder COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY ./entrypoint.sh / ENTRYPOINT ["sh", "entrypoint.sh"] RUN apk update RUN apk add RUN apk add npm COPY ./frontend/package.json /frontend/package.json COPY ./frontend/package-lock.json /frontend/package-lock.json RUN cd frontend/ && npm install RUN cd frontend/ && pwd Here is my docker-compose.yml: version: "3.8" services: pathfinder_gunicorn: build: context: . volumes: - static:/static - ./frontend/static/:/frontend/static/ ports: - "8080:8080" image: pathfinder_gunicorn:v1 container_name: pathfinder_gunicorn nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - pathfinder_gunicorn volumes: static: Here is the path to the directory from my docker-compose and Dockerfile: ./frontend/static/css The directory looks like: DIRECTORY -
How can I add aditional conditions in Django Login
I want my login function to classify If user is an one-to-one field in Alumni or Personel table. If user is related to Alumni table, log the user in and redirect to profile page. If user is related to Personel table, log the user in and redirect to another page. model.py class Alumni(models.Model): Alumni_id = models.IntegerField(primary_key=True) User_id = models.OneToOneField(User,on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=True) Surname = models.CharField(max_length=50 , null=True) image = models.ImageField(default = 'default.jpg',upload_to='profile_pic') LinkedIn = models.CharField(max_length=256 , null=True , blank=True) Line = models.CharField(max_length=50 , null=True , blank=True) Email = models.EmailField(max_length=50 , null=True , blank=True) Province = models.CharField(max_length=50) District = models.CharField(max_length=50) Sub_District = models.CharField(max_length=50) Postal_code = models.IntegerField() Address = models.CharField(max_length=50, null=True , blank=True) PhoneNumber = models.IntegerField( null=True) def __str__(self): return ("Alumni id:%s" %(self.User_id)) def get_absolute_url(self): from django.urls import reverse return reverse('Alumni_detail', args=[str(self.Alumni_id)]) class Personel(models.Model): Personel_id = models.IntegerField(primary_key=True) User_id = models.OneToOneField(User,on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=True) Surname = models.CharField(max_length=50 , null=True) Email = models.EmailField(max_length=50 , null=True , blank=True) view.py def loginpage(request): if request.method =='POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('/profile') else: form = AuthenticationForm() return render(request,'login.html',{'form':form}) -
Add a Non-Model field only for post method on ModelSerializer DRF3
I want to add a custom field that will only be used while creating an object. For example, I have a model serializer and I want to add that field that doesn't present in my model and I want to use this only while post request. -
How to use IF statements with pandas Dataframes and CSV's?
def PandasUpload(request): begin = t.time() if request.method == "POST": csv_file = request.FILES['upload'] reader = pd.read_csv(csv_file) reader.fillna('-', inplace=True) *if reader.Sem == 1 & reader.Sem == 3: do the following code:* result = [] for _, row in reader.iterrows(): result.append(File( reg_no = row['Reg No'], student_name = row['Student Name'], sem = row['Sem'], ex1 = row['EX-1'], ex2 = row['EX-2'], ex3 = row['EX-3'], ex4 = row['EX-4'], ex5 = row['EX-5'], ex6 = row['EX-6'], ex7 = row['EX-7'], ex_total = row['Ex-Total'], ia1 = row['IA-1'], ia2 = row['IA-2'], ia3 = row['IA-3'], ia4 = row['IA-4'], ia5 = row['IA-5'], ia6 = row['IA-6'], ia7 = row['IA-7'], ia_total = row['IA=Total'], total = row['Total'], result = row['Result'], kx1 = row['KX-1'], ki1 = row['KI-1'], k_result = row['K-Result'] )) File.objects.bulk_create(result) end = t.time() print(f"The time taken is {end - begin}") return render(request, "results/base.html") I want to put data into the table if Sem column contains values as 1 and 3 so basically even and odd...how to do it? Please don't suggest documentation I don't understand them... -
Django: How to write fixture files for testing models
I want to test my database and django app via fixtures and Testcases. The problem is, that I cannot find any informations, on how to create fixtures, especially regarding relationships. I tried in the python CLI to create objects and relate them to each other, but it won't execute the dumpdata method afterwards Can you guys give me ressources or a little guide on how to do that, focusing on database models and relationships (1-1,1-n,n-m). Thanks in advance and I'm looking forward to learn as much as I can from you!!! Dennis :) -
How to run multiple terminal sessions (Tabs) in pydroid 3
I am trying to create an app using pydroid 3. When I view if the project is setup properly with python manage.py runserver Everything is set up ok but when it's time to start the app, I have to open another terminal or tab while the terminal with runserver continues running. How do I open another terminal session(or tab) without closing runserver. -
Need help loading staticfiles with nginx
I am having trouble loading the static files from my django project. Here is a picture of my directories: DIRECTORIES I have ran docker-compose up and I get the following errors: ERROR IMAGES ON BROWSER Here is what my nginx (default.conf) file looks like: http { server { listen 8080; access_log /var/log/nginx/access.log location / { root /frontend/templates/frontend # proxy_pass http://pathfinder_gunicorn; # include /etc/nginx/mime.types; } location /static/ { alias /static/; } location ~ \.(css)$ { root /frontend/static/css; } } } This is what the entire directory looks like relative to my nginx (default.conf) file: ALL DIRECTORIES WITH DOCKER FILE -
GMB API upload image returns 'Fetching image failed.'
so I have an issue when using the GMB API for uploading media items. In my code, I am able to successfully request and obtain the resourceName as explained in the API docs. I then use the resourceName to upload an image as bytes. This also works very well and I get a 200 response. After this, I then begin the media upload using the steps documented in the API, however this time is fails and returns --> {'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.mybusiness.v4.ValidationError', 'errorDetails': [{'code': 1000, 'message': 'Fetching image failed.'}]}]}} I have tried the same steps using the Oauth Playground and sending a curl request as well but it always fails in the last step yielding the same error. You can see my code below written in Python using the Django web framework: response = requests.post(f'https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/media:startUpload', headers=HEADERS) if response.status_code == 200: resource_name = response.json()['resourceName'] with open('C:/Users/nevog/Desktop/testimonial-2.jpg', 'rb') as f: data = f.read() params = { 'upload_type': 'media', } response = requests.post(f'https://mybusiness.googleapis.com/upload/v1/media/{resource_name}', data=data, params=params, headers=HEADERS) if response.status_code == 200: print("upload successful") request_body = { "mediaFormat": "PHOTO", "locationAssociation": { "category": "ADDITIONAL" }, "dataRef": { "resourceName": resource_name }, } response = requests.post(f'https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/media', json=request_body, headers=HEADERS) … -
cannot unpack non-iterable int object creating shop and cart in Django with session
I am creating a store and when executing this address http://127.0.0.1:8000/carro/agregar/3/ it has to load the product in the store widget where the cart is. If the car is not in the session, create it. Tried deleting cookies and nothing. But when I press the buy button on any product, in this case on product 3, the button sends to the correct address but the page gives me the following error TypeError at /carro/agregar/3/ cannot unpack non-iterable int object Request Method: GET Request URL: http://127.0.0.1:8000/carro/agregar/3/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: cannot unpack non-iterable int object Exception Location: C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py, line 1374, in build_filter Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 and this C:\Users\HP\Documents\ProyectosDjango\ProyectoWeb\carro\views.py, line 8, in agregar_producto producto = Producto.objects.get(producto_id) views.py from django.shortcuts import redirect from .carro import Carro from tienda.models import Producto # Create your views here. def agregar_producto(request, producto_id): carro= Carro(request) producto = Producto.objects.get(producto_id) carro.agregar(producto=producto) return redirect('Tienda') def eliminar_producto(request, producto_id): carro= Carro(request) producto = Producto.objects.get(producto_id) carro.eliminar(producto=producto) return redirect('Tienda') def restar_producto(request, producto_id): carro= Carro(request) producto = Producto.objects.get(producto_id) carro.restar(producto=producto) return redirect('Tienda') def limpiar_carro(request): carro= Carro(request) carro.limpiar_carro() return redirect('Tienda') context_processor.py def importe_total_carro(request): total = 0 if request.user.is_authenticated: for key, value in request.session["carro"].items(): total = total +(float(value['precio'])*value['cantidad']) return {'importe_total_carro':total} urls.py from … -
Django channels Deploy nginx + uviconr + gunicorn]socket seems to be sending http request
referenced i'm using Reverse Proxy So the https setting is somewhere else. js log WebSocket connection to 'wss://urls/ws/exchange_rate/USD/' failed Dockerfile CMD ["gunicorn", "config.asgi:application", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"] nginx.conf upstream django { server django:8000; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # access_log off; # log_not_found off; # error_log /var/log/nginx/finance/error.log crit; location /ws/ { proxy_pass http://django/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { proxy_pass http://django/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } localhost test There is no log for socket and it works normally. gunicorn config.asgi:application -k uvicorn.workers.UvicornWorker server gunicorn log "GET /exchange_rate/USD/ HTTP/1.1" 404 It seems to be doing http communication. What did I do wrong? -
Django: how to add ckeditor plugins to my project using django
i want to add some plugins to my ckeditor django, i have installed the package using pip, installed it in settings.py and it's working now, but i want to add some more buttons to the ckeditor as all is have now is bold, align, media, emoji and some more , but i need some feature like code-snippets etc. so where should i add these plugins that i copied from the documentation https://django-ckeditor.readthedocs.io/en/latest/#installation a11yhelp, about, adobeair, ajax, autoembed, autogrow, autolink, bbcode, clipboard, codesnippet, codesnippetgeshi, colordialog, devtools, dialog, div, divarea, docprops, embed, embedbase, embedsemantic, filetools, find, flash, forms, iframe, iframedialog, image, image2, language, lineutils, link, liststyle, magicline, mathjax, menubutton, notification, notificationaggregator, pagebreak, pastefromword, placeholder, preview, scayt, sharedspace, showblocks, smiley, sourcedialog, specialchar, stylesheetparser, table, tableresize, tabletools, templates, uicolor, uploadimage, uploadwidget, widget, wsc, xml -
Scaling dynos... ! ▸ Couldn't find that process type (web). ERROR with DEPLOYMENT
I am attempting to deploy a project and have been met with a couple errors. I first checked my logs running: heroku logs --tail which then ran error codes H14. After researching I came to a solution of running heroku ps:scale web=1 which then gives me the error of Scaling dynos... ! ▸ Couldn't find that process type (web). My ProcFile looks like this web: gunicorn takeitorleaveit.wsgi release: python manage.py migrate -
How i can add static files (css) to django web project
I have tested to embedded css style into html template, but it doesn't load css files, my configure as below, could you please help assist ? checkstatic\showstatic\templates\index.html <!DOCTYPE html> <meta charset="UTF-8"> <html lang="en"> <head> {% load static%} <link rel="stylesheet" type="text/css" href="{% static 'css/mystyle.css' %}"> </head> <body> <img src="{% static 'logo1.png' height="200" width="200" class="d-inline-block align-top" %}" alt=""> <h1 class="test">hahahaha</h1> </body> </html> checkstatic\static\css\mystyle.css .test{ color: red; } my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'showstatic' ] ... STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'checkstatic/static/') ] when i access the index site, it only apply h1 tag, it can not load red color as the css config. -
Current time of POST with datetime.now() [duplicate]
I have the date in the model as such but when I POST it always just returns the time of when I ran the server and not the current time of the post class UserPost(models.Model): user = models.ForeignKey(User_profile, on_delete=models.CASCADE) h_body = models.CharField(max_length=140) post_date = models.DateTimeField(default=datetime.now()) -
window.location.replace returns incorrect link
I use window.location.replace(qrMessage) in my Django project, but it add the current page's URL before qrMessage into the searching page's URL and can't open it. Why does it happen and how can I avoid this?