Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Sitemap for multiple domain and same site
I have a Django website with a domain www.example.com hosted on a VPS. The same Website can be accessed from different domains like www.example.xyz and www.example.one I already made a sitemap for www.example.com which is working well. Using Django contrib sitemap function. But now the problem is how to generate the sitemap for www.example.xyz and www.example.one. Sitemap from www.example.xyz and www.example.one shows me a link to www.example.com -
404 Not Found nginx/1.18.0 (Ubuntu) in django application on ec2
I was able to deploy my first django application on EC2 ubuntu 20.04 through the help of this community. After deployment, I'm not able to assess all the pages on the browser but in development all the pages are being displayed. I don't know where to start debugging because every page is displaying 404 Not Found nginx/1.18.0 on the browser. The gunicorn is running properly guni:gunicorn RUNNING pid 121305, uptime 0:54:04.. The content of /etc/nginx/sites-available/default is server { listen 80 default_server; listen [::]:80 default_server; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name ip-address; Please how do I go about this because I know little about nginx -
Django media files get 403 forbidden
I have an app running on a Digital Ocean Droplet. I'm using Ubuntu, Nginx and Gunicorn The admin can upload media files, the upload is working fine. The problem is that when a user visits the site, the media files that the admin uploaded are not displayed due to a 403 (forbidden) error. -
Django Url for default image leads to 404
Currently working on a Django project with two Apps; projects and users. Both a user and a project can have an image; a user has a profile picture and a project has a featured image. If no image is uploaded a default image is used. Here is my problem What I want: A default image to show if no image is uploaded What I get: An incorrect link for the default profile image resulting in a 404 error (the default project image link works just fine) What I've tried: Reading old stack overflow threads, Django docs and googling it. From what I can tell it is not an incorrect media directory, a hard coded url, a jinja formatting error or a misspelled variable. The issues seems to be with the profile image url. From the top: I have my media urls/dirs configured for both local development and for production: In settings.py: MEDIA_URL = '/img/' ... MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img') In my-django-project/urls.py: imports... urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('projects/', include('projects.urls')), path('profiles/', include('users.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My static directory looks like this: css/ js/ img/--|-featured_images/ |-profile_images/ | default.jpeg (this is the default project … -
How can I filter This in django?
I am working on a Django project (like LMS) and I want to filter Lectures by Subject in the template, I do it once but now I forgot how to do it. How can I do this?! I want to filter it by foreign-key Subject in Lecture Here is my models.py from django.db import models from django.utils.text import slugify # Create your models here. class Subject(models.Model): Title = models.CharField(max_length=150) Pic = models.ImageField(upload_to='media/') Test = models.CharField(max_length=300, null=True, blank=True) Slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.Slug = slugify(self.Title, allow_unicode=True) super(Subject, self).save(*args, **kwargs) def __str__(self): return self.Title class Lecture(models.Model): Subject = models.ForeignKey(Subject, on_delete=models.CASCADE) Title = models.CharField(max_length=150) Video = models.CharField(max_length=300) More_Info = models.TextField() Audio_Lecture = models.CharField(max_length=300) Lecture_Files = models.CharField(max_length=300) Sheet = models.CharField(max_length=300) Slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.Slug = slugify(self.Title, allow_unicode=True) super(Lecture, self).save(*args, **kwargs) def __str__(self): return self.Title and here is my views.py from Diploma.models import Lecture, Subject from django.shortcuts import render # Create your views here. def Diploma(request): return render(request, 'Diploma/diploma.html', context={ 'sub' : Subject.objects.all(), }) def Diploma_Subject(request, slug): subject_Lecture = Subject.objects.all() return render(request, 'Diploma/subject.html', context={ 'subj' : subject_Lecture, 'lect' : Lecture.objects.filter(I do not know what I should write here) }) -
How do you configure your settings.py file to upload files to Amazon S3 database instead of local folders?
I have an issue with a Django/Python project currently where I can't seem to upload pictures to the amazon s3 database I have set up when making a new recipe for my cookbook app. The recipe will be created, however the picture file does not send to the S3 db and instead is sent to a local folder in my app folder instead. Would anyone know what I am doing wrong? class Recipe(models.Model): id = models.AutoField(auto_created=True, primary_key=True, verbose_name='title') title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True) image = models.ImageField(null=True, blank=True) serving_size = models.CharField(max_length=10, null=True, blank=True) prep_time = models.CharField(max_length=30, blank=True) cook_time = models.CharField(max_length=30, blank=True) ingredients = models.TextField(blank=True) directions = models.TextField(blank=True) class AddRecipeForm(ModelForm): class Meta: model = Recipe fields = '__all__' exclude = ['id', 'author'] from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<secret key here>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['<heroku app url here>', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
How to Activate Venv with venv/bin Folder Missing (Django and PyCharm on Ubuntu OS)
I have a Django project I've been working on for awhile and don't remember exactly how it started. It's possible I may have started it on Windows and transferred it over to my laptop running Ubuntu, but I can't say for sure. Looking at my project directory, I can't find the bin folder to activate my venv. I have the following: projectname/venv ls within venv: include, lib, pyvenv.cfg The confusing part is, I have been working on the site this way without issue for several months. Since it's within PyCharm the venv always activated automatically, until now. Terminal settings are still correct. But, I recently ran a different script through PyCharm and can't get back into the venv automatically or manually for this django project. It seems like I also have a second venv via: projectname/sitename/django/bin/activate When activating that venv I get a module not found error (crispy_forms) when trying to run the site. So that's not the environment I was using when building the site and installing packages/modules. My terminal always had (venv) It's possible I started the project on Ubuntu, I really don't remember. But, if that's the case I'm not sure why the bin folder would be … -
How to filter in Django-graphene?
I use graphene-Django to build a GraphQL API. I have successfully created this API, but I can't pass an argument to filter my response. I want to filter with the forging key from my model. model.py: class TodoList(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) date = models.DateField(auto_now=True) text = models.TextField() schema.py: class TodoView(DjangoObjectType): class Meta: model = TodoList fields = ('id', 'title', 'date', 'text') class UserType(DjangoObjectType): class Meta: model = User class TodoQuery(graphene.ObjectType): todoList = DjangoListField(TodoView) def resolve_all_todo(root, info): return TodoList.objects.filter(userId=2) But when I do filter it show all object in the result When I send this request: { todoList { id title date text } } I've got this response: { "data": { "todoList": [ { "id": "1", "title": "test", "date": "2021-09-13", "text": "test todo" }, { "id": "2", "title": "test2", "date": "2021-09-13", "text": "test2" }, { "id": "3", "title": "admin2 test", "date": "2021-09-13", "text": "admin2 test" }, { "id": "4", "title": "admin2 test2", "date": "2021-09-14", "text": "admin2 test2" } ] } } What I have missed? Or maybe I do something wrong? -
ModuleNotFoundError: No module named 'cvsbehaviour' AWS Elastic Beanstalk Django
I have spent way to long on this and been looking everywhere but cant seem to find the cause of my issue. I am trying to deploy a Django app on my ElasticBeanstalk via the web panel and the app is not working once deployed, the health is Severe and 100.0 % of the requests are failing with HTTP 5xx. From the logs, the error I see is the following: web.stdout.log Sep 14 00:47:05 ip-172-31-5-163 web: Traceback (most recent call last): Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Sep 14 00:47:05 ip-172-31-5-163 web: worker.init_process() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Sep 14 00:47:05 ip-172-31-5-163 web: super().init_process() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Sep 14 00:47:05 ip-172-31-5-163 web: self.load_wsgi() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Sep 14 00:47:05 ip-172-31-5-163 web: self.wsgi = self.app.wsgi() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Sep 14 00:47:05 ip-172-31-5-163 web: self.callable = self.load() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Sep 14 00:47:05 ip-172-31-5-163 web: return self.load_wsgiapp() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Sep … -
Django - Static Images are not rendering from JavaScript file
On my Django project, I keep receiving a not found error for a few images. When running the project without Django (using live server), everything works fine. I have loaded static at the beginning of the html document and added all of the correct static tags. I believe it has something to do with my JavaScript File (where the image is used). For Example the html code where it pulls the JavaScript file <script src="{% static '/js/project.js'%}"></script> And the JavaScript File (project.js) const projects = [ { title: "Discord App", cardImage: "/images/project-page/download.png", description: "A Discord app.", tagimg: "https://cdn.iconscout.com/icon/free/png-512/react-1-282599.png", Previewlink: "", }, ]; I have a few images that are not on the JS file (only html) that work fine. Was wondering if anyone ran into the same problem and could help me out. Let me know if you need more information. -
save image in django template
I know that this question have been asked many times and I already checked many solutions but can not find an explanation to the weird behavior of saving form in this case as in production saving image is working on my pc and not in my colleagues, in local as well it is working if I change the position of the form save (more below, if more up it does not work) here the related forms to the template I am working with: class ProfilePageTitleForm(ModelForm): class Meta: model = ProfilePage fields = [ "title", ] class ProfilePageDetailsForm(ModelForm): intro = forms.CharField( required=True, widget=forms.Textarea( attrs={ "class": "max-w-md w-full bg-gray-100 border border-gray-200 " "rounded-lg text-base outline-none focus:border-blue-600 p-4" } ), label=_("Personal introduction"), help_text=_("maximum number of characters: 80 characters"), max_length=80, ) class Meta: model = ProfilePage fields = [ "avatar", "school", "location", "intro", ] here they are separated as I used the title in another template separately related views @login_required def profile_details(request: HttpRequest, pk: int = None) -> HttpResponse: profile = ProfilePage.objects.get(pk=pk) user = profile.user titleprofilepage_form = ProfilePageTitleForm(instance=profile) profilepage_form = ProfilePageDetailsForm(instance=profile) if user == request.user or request.user.has_perm("userprofile.manager_permissions"): if request.method == "POST": profilepage_form = ProfilePageDetailsForm( request.POST, request.FILES, instance=profile ) titleprofilepage_form = ProfilePageTitleForm(request.POST, instance=profile) if ( … -
Django form submit without refreshing
thanks in advance. I know this has been asked a few times. But after reading the previous questions, reading and understanding JSON and AJAX forms tutorials, I still can't find a way to not having the website refreshed after submitting a form. I would really appreciate it if any of you with a higher knowledge of JavaScript is able to give a hand. This is a newsletter at the bottom part of the Home page that just asks for a name and an email and it keeps the information in the database, it works perfect and I just would like to reply to the confirmation message without refreshing, because it replies to a message but the user has to go to the bottom, of the page again to see it which is not practical at all. The HTML is <div id="contact_form"> <div class="Newsletter"> <form id="form" enctype="multipart/form-data" method="POST" action="" style="text-align: left;"> {% csrf_token %} <div class="fields"> <div class="fields"> <label for="name" id="name_label">Name</label> <input type="text" name="name" minlength="3" placeholder="e.g. John Smith" id="name" required> </div> <div class="fields"> <label for="email" id="email_label">Email</label> <input type="email" name="email" placeholder="e.g. john@example.com" id="email" required> </div> </div> <div class="submit"> <button type='submit' id="submit" >Subscribe</button> </div> {% include 'messages.html' %} </form> </div> </div> The index … -
Django set request.GET, i.e. set url args server side for a GET
When a user GETs a form, I would like to change the url query parameters e.g. if they request: /foo/bar/1/ I would like to reply with /foo/bar/1/?caz=7, without a redirect. I tried some answers on SO, but the browser always shows the same url, i.e. /foo/bar/1/ The recommend ways of changing request.GET: request.GET = request.GET.copy() request.GET['caz'] = 7 I imagine I am changing the request, and not the response. I looked at the response docs and don't see anyway there either. I could have a hidden widget or session middle but I am trying to avoid that. -
Can I use django orm with a database that was not set up with django
I have a database that I set up manually using raw sql and alembic. I want to now use this database in a Django app. Will the Django ORM work as expected with this DB? Would I have to set up all the models? Thanks. -
How to run a django test on an empty database outside of the test runner?
Our database accepts user-submitted load files, and for the time being, our admins are going to load the submitted files manually to resolve data issues. There are 2 types of files. For the second file to load successfully, the first file must load successfully. Since we are going to handle this ourselves, I'm writing a data validation page that does a load of the first file in debug mode so that the user can resolve simple things like unique fields and controlled vocabulary issues. But in order for me to test the second file, I need to temporarily load that first file. I decided to do this by creating a TestCase class that is not a part of our unit test suite. (Maybe there's a better way to do this than the strategy I've selected - so I'm open to suggestions.) When I run the tests from the validation view in views.py, the tests work and the data does not persist in the database - however, I'm not getting a clean/empty test database to work from. In order for this code to be guaranteed to work, I need to figure out how to create a fresh empty copy of a … -
How do i get access to a db, so i can get the organizations id?
I am working on creating notices for a particular app. And I need to make the API for this dynamic as I am collecting information from the db, not the models.py file. Right now, I'm using dummy data so it works, but I need to get the organizations id from the db so it is dynamic. Any ideas how? ANY help would be appreciated! class CreateNoticeAPIView(views.APIView): def post(self,request): serializer = CreateNotice(data=request.data) if serializer.is_valid(): db.save("noticeboard", "613a1a3b59842c7444fb0220", serializer.data) return Response( { "success":True, "data":serializer.data, "message":"Successfully created" }, status=status.HTTP_201_CREATED) return Response( { "success":False, "message":"Try again!" }, status=status.HTTP_400_BAD_REQUEST) That's the view in the views.py file for creating the notices. The second parameter in db.save is the dummy data for organization id (i.e "613a1a3b59842c7444fb0220"). Thanks in advance! -
Refrain Django from translating dates
I have a django app where I'm using translations. My problem is that django is translating the dates as well, and I want to keep the dates in the same format for all languages. Is there a solution to this? It is making other problems for me, forms are not validating dates because of this. I'm getting the date picker in english as shown in the following image, whereas I need it in French if the language is set to french. Here are my language settings USE_I18N = True # use internationalization USE_L10N = True # use localization from django.utils.translation import gettext_lazy as _ LANGUAGES =[ ('en', _('English')), ('fr', _('French')), ('ar', _('Arabic')),] Thank you. -
Django why is this code blocking http requests
Here is the module: import threading import time import pandas as pd from binance.client import Client import json from api_create_alert.models import Alerts from service_get_data.get_api_secret import get_secret alerts = Alerts.objects.all().values() df = pd.DataFrame(alerts) data = get_secret() data = json.loads(data) client = Client(data['BINANCE_PUBLIC_API'], data['BINANCE_SECRET_API']) def price_watch(): interval = 10 while True: coins = client.get_all_tickers() for coin in coins: symbol = coin['symbol'] price = float(coin['price']) rows = df[((df.symbol == symbol) & (df.direction == 'ABOVE') & (price > df.price)) | ((df.symbol == symbol) & (df.direction == 'BELOW') & (price < df.price))] if len(rows) > 0: print(rows) time.sleep(interval) thread = threading.Thread(target=price_watch) thread.start() Importing it from apps.py: def ready(self): if os.environ.get("RUN_MAIN") == "true": import service_price_watch.price_watch So it's a loop that runs every 10 seconds, each time the loop starts running the Django app is blocked no response is received until the loop is done, now why is that happening when I'm using the threading module, isn't the purpose of threading module is to make Async operations? -
Deploy Django app on AWS EC2 behind firewall
This article here shows how to deploy a Django app on AWS EC2 on a public domain (i.e. having a public IPv4 DNS) I am trying to deploy a Django app within a confined network of AWS behind a firewall, where each AWS account only has a private IPv4 DNS and not a public one. The article above only works for an AWS EC2 that has public access (and hence a public IPv4 DNS). Specifically, this paragraph of instruction: Note: Add instance’s DNS name/IP to “Allowed Hosts” in settings.py ALLOWED_HOSTS=['EC2_DNS_NAME'] ... In a browser, navigate to public DNS of the instance, make sure to append port “8000” at the end and if everything was properly configured, it will show the index page of the application. For example: www.ec2dnsname.com:8000 If I follow all the steps in that article up the paragraph above, when I do this in my EC2: curl http://xxx.xxx.xx.xxx:8000 I am able to get the HTTP request of the standard Django index page in HTML form. This means that my app is successfully deployed. But where exactly ? What should be the address to enter in a browser to access this index page? Accessing the following address in a … -
Sending emails through django SMTP without form data being sent through on refresh?
Hi I'm trying to build a contact form where the user submits the form and then it is sent via email to the client. Everything is working fine but I noticed that the form data is sent through to the email even by refreshing the page. Any ideas on how to fix this? //views.py file def contact(request): if request.method == "POST": name = request.POST.get('full-name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') data = { "name": name, "email": email, "subject": subject, "message": message, } message = ''' New message: {} From: {} '''.format(data['message'], data['email']) send_mail(data["subject"], message, '', ['email@gmail.com']) return render(request, "contact.html", {}) /// settings.py file env = environ.Env() environ.Env.read_env() EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = env('EMAIL_HOST') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False -
NoReverseMatch in Django, i can't access to details of the order each customers
I am trying to see the orders of each customer, but I get this error views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import OrderForm def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request): form_value = OrderForm() if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == 'POST': form_value = OrderForm(request.POST, instance=order) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method == 'POST': order.delete() return redirect('/') context={'item':order} return render (request, 'accounts/delete.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/', views.createOrder, name='create_order'), … -
Django-apscheduer - Error getting due jobs from job store 'default': connection already closed
I use django-apscheduler and Postgresql in my project. After several hours of running, I start to get this error "Error getting due jobs from job store 'default': connection already closed". I'm new to django, so if anyone who faced the same issue could share with a solution or ideas, I would be extremely grateful. I have seen people had the same problem, but with no solution. -
How to link two models with one being a question and the other the answers
I have a model Poller that contains a question and two related answer options (poller_choice_one and two) and another model Vote for checking if a user voted for choice one or two. So here is the problem: How can I best structure and render the forms/logic so any user can vote Foo or Bar for a certain question? Right now I tried to render a Poller object with its choice fields as div. But how would I then enable a user to vote for one of the two choices? (simple submit button or via a form?) And does it make sense to separate the Models as I did or could I even build this logic using a single model? Poller model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(Account, on_delete=models.CASCADE) # Shall the choices be isolated as well into the Vote model? poller_choice_one = models.CharField(max_length=30) poller_choice_two = models.CharField(max_length=30) Vote Model class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='user') poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) -
'Meal' object is not iterable django rest framework
I'm making an api with the ability to add a product to the cart, when I receive an empty basket, everything works, but as soon as the product gets into the basket, it gives me an error 'Meal' object is not iterable It's models.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField() class CartMeal(models.Model): """Cart Meal""" user = models.ForeignKey('Customer', on_delete=models.CASCADE) cart = models.ForeignKey('Cart', verbose_name='Cart', on_delete=models.CASCADE, related_name='related_meals') meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE) qty = models.IntegerField(default=1) final_price = models.DecimalField(max_digits=9, decimal_places=2) class Cart(models.Model): """Cart""" owner = models.ForeignKey('Customer', on_delete=models.CASCADE) meals = models.ManyToManyField(CartMeal, related_name='related_cart', blank=True) total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0) in_orders = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) It's serializers.py class CartMealSerializer(serializers.ModelSerializer): meal = MealSerializer(many=True) class Meta: model = CartMeal fields = ['id', 'meal', 'qty', 'final_price'] class CustomerSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = Customer fields = '__all__' class CartSerializer(serializers.ModelSerializer): meals = CartMealSerializer(many=True) owner = CustomerSerializer() class Meta: model = Cart fields = '__all__' It's views.py Here I call the get method, after which I get an error class CartViewSet(viewsets.ModelViewSet): serializer_class = CartSerializer queryset = Cart.objects.all() @staticmethod def get_cart(user): if user.is_authenticated: return Cart.objects.get(owner=user.customer, for_anonymous_user=False) return Cart.objects.get(for_anonymous_user=True) … -
UniqueConstraint throwing an IntegrityError on the deleted row
I have a model with UniqueContraint class UserChallenge(models.Model): id = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4) member = models.ForeignKey('people.Person', on_delete=models.PROTECT, related_name='challenges', null=False) challenge = models.ForeignKey(Challenge, on_delete=models.PROTECT, related_name='user_challenges', null=False) recurring = models.BooleanField(default=False) class Meta: constraints = [ models.UniqueConstraint(fields=['member', 'challenge'], condition=Q(recurring=False), name='unique_member_and_challenge') ] By this I want to prevent of row dublications with the same challenge and member and it works fine. However, when I am trying to create a UserChallenge after a deletion of one existing, it still throws an IntegrityError. What I mean is that I deleted a row of UserChallenge with certain member and challenge, and when I am trying to add new record with this data, it still throws an error. File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/modelcluster/forms.py", line 348, in save instance = super(ClusterForm, self).save(commit=(commit and not save_m2m_now)) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/forms/models.py", line 468, in save self.instance.save() File "/Users/islom/projects/pyHomebase/homebase/challenges/models.py", line 258, in save super().save(*args, **kwargs) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql …