Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Supervisorctl refused connection
I am running Django-huey as a background task using a supervisor. Once the supervisor is started, I get a ConnectionRefusedError: [Errno 111] Connection refused task.conf [program:encryption] command=/home/user/apps/venv/bin/python /home/user/apps/project-dir/manage.py djangohuey --queue encryption user=user autostart=true autorestart=true redirect_stderr = true stdout_logfile = /etc/supervisor/realtime.log supervisord.conf [unix_http_server] file=/var/run/supervisor.sock chmod=0700 [supervisord] logfile=/var/log/supervisor/supervisord.log pidfile=/var/run/supervisord.pid childlogdir=/var/log/supervisor [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///var/run/supervisor.sock [include] files = /etc/supervisor/conf.d/*.conf [inet_http_server] port=127.0.0.1:9001 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface -
ValueError: Cannot assign "(<SimpleLazyObject: <User: bhavna>>,)": "cart.user" must be a "User" instance
i am just learning to add ForeignKey instance in table ValueError: Cannot assign "(<SimpleLazyObject: <User: bhavna>>,)": "cart.user" must be a "User" instance. this is model file from django.conf import settings User = settings.AUTH_USER_MODEL class cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) stock = models.ForeignKey(Stock,on_delete=models.CASCADE) qty = models.IntegerField() class Stock(models.Model): product_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE) size_id = models.ForeignKey(Size, null=True,on_delete=models.CASCADE) colour_id = models.ForeignKey(Colour,null=True,on_delete=models.CASCADE) qty = models.IntegerField() views.py @login_required def add_cart(request): if request.method == 'POST': p_id = request.POST.get('product_id') s_id = request.POST.get('size_name') c_id = request.POST.get('col_name') qs = Product.objects.get(id=p_id) qtty = 0 print(p_id) print(s_id) print(c_id) object_stock = Stock.objects.filter(product_id=p_id,size_id=s_id,colour_id=c_id, qty__gte=1).values() object_stock1 = Stock.objects.get(product_id=p_id,size_id=s_id,colour_id=c_id, qty__gte=1) print(object_stock1) for ob in object_stock: qtty += ob['qty'] if qtty >= 1: b = cart(qty=1) b.stock = object_stock1 b.user=request.user, b.save() return HttpResponse("Inserted") else: return HttpResponse("Not inserted") i am trying add to cart functionality for study purpose but it is giving me error -
Django many-to-many formset for books and authors: only books added to database
My aim is to have a form where users can enter a book and its authors into the database using an 'Add Author' button if there's more than one author. I use a many-to-many relationship so all of these authors can be added (or in most cases, just 1 author). Currently the book is getting added to the table but not the author. I think it has to do with the multiple forms aspect. Originally I tried CreateView until I realised that doesn't work with more than one model at a time. I am new to programming and to Django and only have a few CRUD apps under my belt at this point. models.py: class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField('Author', through='Authored') def __str__(self): return self.title class Author(models.Model): name = models.CharField(max_length=200) books = models.ManyToManyField('Book', through='Authored') def __str__(self): return self.name class Authored(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE) views.py: class BookCreate(View): template_name = 'bookmany/book_form.html' form_class = BookForm formset_class = AuthorFormSet def get(self, request, *args, **kwargs): form = self.form_class() formset = self.formset_class() return render(request, self.template_name, {'form': form, 'formset': formset}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) formset = self.formset_class(request.POST) success_url = reverse_lazy('bookmany:book_list') if form.is_valid(): book = form.save() if … -
Keep getting a CORS error for put requests in Django from browser
I keep getting a CORS error when I make a put request to my Django server from my frontend application (Fetch API) but not from Postman. Here is the error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://q72y0iroi2.execute-api.us-west-2.amazonaws.com/weightsheets/636. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 503. Somehow GET, POST and DELETE requests are working fine. I have tried all the settings suggested in the documentation for django-cors-headers but to no avail! Any advice would be highly appreciated Here is my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) DEBUG = os.getenv("DEBUG", "False") ALLOWED_HOSTS = ['*'] DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'weighttrackingapi', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } # List of allowed origins CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = ( "accept", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'weighttracking.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, … -
Python Django and React: CSRF Authtification failing, HTTP 403
I have the following Django-Setup to ensure CORS between my React Frontend and my Django Backend: views.py: import json from django.http import JsonResponse, HttpResponseBadRequest from django.middleware.csrf import get_token from django.views.decorators.http import require_http_methods from .models import FavouriteLocation from .utils import get_and_save_forecast def get_forecast(request, latitude, longitude): forecast = get_and_save_forecast(latitude, longitude) data = { 'latitude': str(forecast.latitude), 'longitude': str(forecast.longitude), 'generation_time_ms': str(forecast.generation_time_ms), 'utc_offset_seconds': forecast.utc_offset_seconds, 'timezone': forecast.timezone, 'timezone_abbreviation': forecast.timezone_abbreviation, 'elevation': str(forecast.elevation), 'temperature': str(forecast.temperature), 'windspeed': str(forecast.windspeed), 'winddirection': str(forecast.winddirection), 'weathercode': forecast.weathercode, 'is_day': forecast.is_day, 'time': forecast.time.isoformat(), # convert datetime to string 'hourly_time': forecast.hourly_time, 'temperature_2m': forecast.temperature_2m, 'relativehumidity_2m': forecast.relativehumidity_2m, 'windspeed_10m': forecast.windspeed_10m, } return JsonResponse(data) def get_favourites(request): favourites = FavouriteLocation.objects.all() data = [{'id': fav.id, 'name': fav.name, 'latitude': fav.latitude, 'longitude': fav.longitude} for fav in favourites] return JsonResponse(data, safe=False) @require_http_methods(["POST"]) def add_favourite(request): try: data = json.loads(request.body) name = data['name'] latitude = data['latitude'] longitude = data['longitude'] FavouriteLocation.objects.create(name=name, latitude=latitude, longitude=longitude) return JsonResponse({'status': 'success'}) except (KeyError, ValueError): return HttpResponseBadRequest() @require_http_methods(["DELETE"]) def delete_favourite(request, favourite_id): try: fav = FavouriteLocation.objects.get(id=favourite_id) fav.delete() return JsonResponse({'status': 'success'}) except FavouriteLocation.DoesNotExist: return HttpResponseBadRequest() def csrf(request): token = get_token(request) return JsonResponse({'csrfToken': token}) settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
The class name with or without quotes in a Django model field to have foreign key relationship
I can set Category with or without quotes to ForeignKey() as shown below: class Category(models.Model): name = models.CharField(max_length=50) class Product(models.Model): # Here category = models.ForeignKey("Category", on_delete=models.CASCADE) name = models.CharField(max_length=50) Or: class Category(models.Model): name = models.CharField(max_length=50) class Product(models.Model): # Here category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) And, I know that I can set Category with quotes to ForeignKey() before Category class is defined as shown below: class Product(models.Model): # Here category = models.ForeignKey("Category", on_delete=models.CASCADE) name = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=50) And, I know that I cannot set Category without quotes to ForeignKey() before Category class is defined as shown below: class Product(models.Model): # Error category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=50) Then, I got the error below: NameError: name 'Category' is not defined My questions: What is the difference between the class name with or without quotes in a Django model field to have foreign key relationship? Which should I use, the class name with or without quotes in a Django model field to have foreign key relationship? -
How to display product stock information in a single line per product with varying columns based on store count in Django?
I have 3 tables: Product, Store, Stock. Stock contains the product's quantity and price. Every Product has a Stock entry per store. If there 3 stores, each product will have 2 stock entry with their own price and quantity. I want to display these records on a single line per product where the columns will depend on how many stores there is. Like this: Product Name Store1 Quantity Store1 Price Store2 Quantity Store2 Price Flathead Screw 10 60 20 70 How can I do this? All I can give you now are my models: class ProductCategory(models.Model): categoryid = models.AutoField(primary_key=True) shortcode = models.CharField(max_length=10) categoryname = models.CharField(max_length=50,unique=True) isactive= models.BooleanField(default=True) class Meta: db_table="tblProductCategory" class Product(models.Model): productid = models.AutoField(primary_key=True) sku = models.CharField(max_length=20,unique=True) shortcode = models.CharField(max_length=10) category = models.ForeignKey(ProductCategory, on_delete=models.SET_DEFAULT,null=False,default=0) productname = models.CharField(max_length=50) description = models.CharField(max_length=50) barcode = models.CharField(max_length=20) isactive= models.BooleanField(default=True) class Meta: db_table="tblProduct" class Store(models.Model): storeid = models.AutoField(primary_key=True) storename = models.CharField(max_length=50) class Meta: db_table="tblStore" class Stock(models.Model): stockid = models.AutoField(primary_key=True) store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT,null=False,default=0) product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT,null=False,default=0) threshold = models.IntegerField(default=0) cost = models.FloatField(default=0) price = models.FloatField(default=0) discountprice = models.FloatField(default=0) stock = models.FloatField(default=0) class Meta: db_table="tblProductStock" and my current view: def get_product(request): recordsTotal = 0 draw = int(request.GET['draw']) start = int(request.GET['start']) length = int(request.GET['length']) products … -
''404 Not Found'' Django media files
I'm trying to serve an image from a docker volume, but I can't quite get a hang of it. error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/fergana_api/files/36/movies/movie.mp4 Using the URLconf defined in fergana_api.urls, Django tried these URL patterns, in this order: admin/ api/schema/ [name='api-schema'] api/docs/ [name='api-docs'] api/ [name='all-runs'] tests/<slug:test_session_id> [name='single-run'] tests/<slug:test_session_id>/<slug:test_name> [name='single-test'] ^static/(?P<path>.*)$ ^files/(?P<path>.*)$ The current path, fergana_api/files/36/movies/movie.mp4, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py STATIC_URL = 'static/' MEDIA_URL = 'files/' MEDIA_ROOT = '/var/web/media/' STATIC_ROOT = BASE_DIR / 'static_files' # location of static files STATICFILES_DIRS = [ BASE_DIR / 'static' ] app/views.py class SingleTestView(View): def get(self, request, test_session_id, test_name): run = Runner.objects.get(id=test_session_id) path_to_session = to_file('files/', f'{test_session_id}') movies_dir_path = to_file(path_to_session, 'movies') movie_path = to_file(movies_dir_path, test_name.replace('-', '_') + '.mp4') context = { 'movie_path': movie_path } return render(request, "presenter/single_test.html", context) project/url.py if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) single_test.html <video width="320" height="240" controls> <source src="{{ movie_path }}" type="video/mp4"> </video> It seems like the app uses the correct URL to serve files, but it doesn't seem like … -
Django static files in k8s
i have my djanog app and its not working when im doing DEBUG = False this is my ingress.yaml: {{- $ingress := .Values.ingress -}} {{- if $ingress.enabled -}} apiVersion: {{ include "service.ingressAPIVersion" . }} kind: Ingress metadata: name: "{{ include "service.fullname" . }}" namespace: {{ .Release.Namespace }} {{- with $ingress.annotations }} annotations: {{- range $key, $value := . }} {{- printf "%s: %s" $key (tpl $value $ | quote) | nindent 4 }} {{- end }} {{- end }} labels: {{- include "service.labels" . | nindent 4 }} {{- range $key, $value := $ingress.labels }} {{- printf "%s: %s" $key (tpl $value $ | quote) | nindent 4 }} {{- end }} spec: {{- if .Values.ingress.tls }} tls: {{- with $ingress.tls }} {{- toYaml . | nindent 4 }} {{- end }} {{- end }} ingressClassName: {{ $ingress.ingressClassName }} rules: {{- with $ingress.rules }} {{- toYaml . | nindent 4 }} {{- end }} - host: website.net http: paths: - path: /static/ pathType: Prefix backend: serviceName: my-app servicePort: 80 {{- end }} this is in my settings.py: STATIC_URL = "/static/" STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) CONTENT_TYPES = [ ('text/css', '.css'), ('application/javascript', '.js'), … -
Django Python: Infinite Scroll Feed
I am working on a Social Media Website. My Feed has images and Videos uploaded by Users but after like the 6th Content a Bar with Buttons to the next Site appears (a Paginator). I would like to create an Infite Scroll, so if the User reached the end of the Feed of the first Page it automaticly loads the next Feed Page under the other. That's what appears I would be nice if someone could help me. I will upload my Feed.html and my Views.py feed.html {% extends "blog/base.html" %} {% block title %}Feeds{% endblock %} {% block content %} <link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> <div class="col-8"> {% if posts|length == 0 %} <span class="no-feed-text"> <p>You need to follow someone to see their Posts<br>Meanwhile you can give look at your <a class="trending-page" href="{% url 'blog-trends' %}">Search</a> page</p> </span> <br><br> {% endif %} {% for post in posts %} <article class="content-section" style="overflow: auto;"> <div class="mediacontent"> {% if post.extension == '.mp4'%} <video loop controls disablePictureInPicture controlsList="nodownload noplaybackrate" class="video-context" width="500px" height="500px"> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% elif post.extension == '.jpg' or post.extension == '.jpeg' %} <a href="{% url 'post-detail' post.id %}"> <img class="image-context" src="{{ post.file.url }}"> </a> … -
Cannot proceed with multiform view in class based views
I need to create a class based view that: will display one form based on the input from the first form will create another one: the first input is a JSON file that contains the name of the files that need to be passed to the next. I'm stuck - I cannot get the view to act on saving the first form (called initial in the code). I minimized the initial_form_valid function to just one print and it still doesn't run (before it was an attempt to check if the form is valid or not and print the result to the console). And yes, unfortunately for now I must keep putting the CBV in a function to preserve the original urls.py structure. views.py def firmware_cbv(request): class Firmware_view(MultiFormsView, TemplateView): template_name = 'path/firmware_cbv.html' form_classes = {'initial': forms.InitialFirmwareForm, 'details': forms.DetailsFirmwareForm} def get_success_url(self): return self.request.path def get_context_data(self, **kwargs): context = super(Firmware_view, self).get_context_data(**kwargs) forms = self.get_forms(self.form_classes) context["initialSent"] = False context['forms'] = forms context.update({"key1": "val1", "key2": "val2"}) print("the context is now", context) return context def initial_form_valid(self): print("the self in initial form valid is", self) def details_form_valid(self, form): new_firmware = form.save(self.request) return form.details(self.request, new_firmware, self.get_success_url()) fw_view = Firmware_view.as_view()(request) return fw_view forms.py class InitialFirmwareForm(forms.Form): file = forms.FileField() def … -
Django-RQ API_TOKEN configuration to access to stats endpoint
I'm trying to retrieve some statistics from the django-rq queues and I'm having some difficulties to access to the provided URL from the Django-Rq documentation These statistics are also available in JSON format via /django-rq/stats.json, which is accessible to staff members. If you need to access this view via other HTTP clients (for monitoring purposes), you can define RQ_API_TOKEN and access it via /django-rq/stats.json/<API_TOKEN>. Well, I have defined a simple RQ_API_TOKEN just for testing purposes in my settings.py RQ_API_TOKEN = "AAABBBCCC" And I'm trying to access it via Postman but I keep receiving the following response: {"error": true, "description": "Please configure API_TOKEN in settings.py before accessing this view."} I've tried to send the token in the headers o even a query param, but it still doesn't work as is intended to work. Example URLS that I've tried with query params: django-rq/stats.json/?token=AAABBBCCC django-rq/stats.json/?api_token=AAABBBCCC django-rq/stats.json/?API-TOKEN=AAABBBCCC django-rq/stats.json/?API_TOKEN=AAABBBCCC The same I've tried, but leaving no query param and inserting the token as a header with the same keys. Nothing works. -
SynchronousOnlyOperation from celery task using gevent execution pool on django orm
I found this question that describes exactly what happens to my software, but I haven't found any answers to this problem. SynchronousOnlyOperation from celery task using gevent execution pool is there any update on how to use gevent and celery in combination with django orm? I've opened quite a few issues from all sides but I'm not getting replies. https://forum.djangoproject.com/t/synchronousonlyoperation-from-celery-task-using-gevent-execution-pool/21105 https://forum.djangoproject.com/t/synchronousonlyoperation-django-gunicorn-gevent/21182 https://github.com/celery/celery/issues/8262 https://github.com/gevent/gevent/issues/1955 https://github.com/benoitc/gunicorn/issues/3000 monkey.patch_all() and https://github.com/psycopg/psycogreen -
Site 127.0.0.1 does not allow connection
please help me understand. I have a separate html page on which I display certain information in the form of a table. In my main page, I am displaying this page through an iframe, but instead of displaying the page, it shows me a gray page that says "Site 127.0.0.1 does not allow connection". What could be the problem? main.html: <a href="{% url 'units' rack.pk %}" target="temp"><button>test</button></a> <iframe name="temp" src="units.html"></iframe> That is result: -
The default value with or without "()" in a Django model field and "ValueError: Cannot serialize function" error
<The 1st case>: I can use timezone.now() with or without () as a default value in DateTimeField() as shown below: from django.utils import timezone # Here datetime = models.DateTimeField(default=timezone.now()) Or: from django.utils import timezone # Here datetime = models.DateTimeField(default=timezone.now) So, what is the difference between now() and now? <The 2nd case>: I can use timezone.now().date() with () as a default value in DateField() as shown below: from django.utils import timezone # Here date = models.DateField(default=timezone.now().date()) But I cannot use timezone.now().date() without () as a default value in DateField() as shown below: from django.utils import timezone # Here date = models.DateField(default=timezone.now().date) Then, I got the error below: ValueError: Cannot serialize function <built-in method date of datetime.datetime object at 0x0000019D077B70F0>: No module So, what is the difference between now().date() and now().date? -
How to solve "Preparing metadata (setup.py): finished with status 'error'" when deploy django + mysqlclient in railway.app
I'm trying to deploy my Django website on the railway.app host. It works out smoothly without the "MySQL" database. It works smoothly with "MySQL" at localhost too, but when I upload it to railway it fails. I wonder if there are some unfinished dependencies. How does i fix this? My database code looks like this:`DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': os.environ.get('MYSQLHOST'), 'PORT': os.environ.get('MYSQLPORT'), 'NAME': os.environ.get('MYSQLDATABASE'), 'USER': os.environ.get('MYSQLUSER'), 'PASSWORD': os.environ.get('MYSQLPASSWORD'), } }` I'm programming on a windows desktop. -
File upload using Django Forms
I have a file field in MissFormModel model: file = models.FileField(upload_to ='uploads/') My forms.py looks like: class SendNewRequest(ModelForm): class Meta: model = MissFormModel fields = ("sender", "file") labels = { 'sender':'', 'file':'', } widgets = {} My index view: def index(request): context ={} forms = MissFormModel.objects.all() if forms.exists(): return render(request, 'app/index.html', {'forms':forms,'context':context}) else: return render(request, 'app/index.html', {'forms':None,'context':context}) I am trying to implement file upload forms: def send_new_request(request): form = SendNewRequest() if request.method == 'POST': form = SendNewRequest(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('index') return render(request, 'forms/new_request.html', {'form':form}) My template: {% for i in forms %} <tr> <th scope="row">{{i.id}}</th> <th>{{i.sender}}</th> <th> {% if i.file %} <a href="{{ i.file.url }}" class="btn btn-primary btn-sm" target="_blank"> Download </a> {% endif %} </th> </tr> {% endfor %} My new_request.html: <form action="" method="POST" encytpe="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> But when I've created new forms with attachment at my index page i see nothing. The same situation in admin page. Could you explain what i am doing wrong? -
Django ORM get object based on many-to-many field
I have model with m2m field users: class SomeModel(models.Model): objects = SomeModelManager() users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) My goal is to get instance of this model where set of instance users matches given queryset (it means that every user from queryset should be in m2m relation and no other users). If I do obj = SomeModel.objects.get(users=qs) I get ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. And I totaly understand the reason of such error, so the next thing I did was creating a custom Queryset class for this model to override .get() behavior: class SomeModelQueryset(QuerySet): def get(self, *args, **kwargs): qs = super() # Prevent recursion if (users := kwargs.pop('users', None)) is not None: qs = qs.annotate(count=Count('users__id')).filter(users__in=users, count=users.count()**2) return qs.get(*args, **kwargs) class SomeModelManager(models.Manager.from_queryset(SomeModelQueryset)): ... So what I try to do is to filter only objects with matching users and make sure that amount of users is the same as in queryset. But I don't like current version of code. users__in adds instance to queryset each time it finds match, so it results in n occurrences for each object (n - number of m2m users for specific object). Count in .annotate() counts unique users … -
Why am I getting a Forbidden (403) CSRF cookie not set error when trying to login after deploying my Django project?
Django project works locally, but when I deployed it and tried to login I got Forbidden (403) CSRF cookie not set. My settings.py have this code MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # template stuff TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': PROJECT_TEMPLATES, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages' ], }, }, ] # Internationalization USE_I18N = False SECURE_CROSS_ORIGIN_OPENER_POLICY = None #SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_NAME = 'new_session_id' CSRF_COOKIE_NAME = 'new_csrf_token' SESSION_COOKIE_SECURE=False #CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True CSRF_TRUSTED_ORIGINS =["http://34.118.121.194:8000","https://34.118.121.194:8000",'http://34.118.121.194:8000/','https://34.118.121.194:8000/'] #SESSION_COOKIE_AGE = 7200 CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' #SESSION_COOKIE_DOMAIN = 'localhost:8000' ALLOWED_HOSTS = ['*'] I have the csrf tag in my form. I tried mutliple things, but nothing helped. I also inspected it and noticed that the set-cookie is present in the login get request, but not in the post. The cookie in the get request looks like this: Set-Cookie: new_session_id=7hdqxannws6eakk1ayc8at3dldustjrj; expires=Mon, 12 Jun 2023 09:28:14 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None I have deployed it with google cloud, not sure whether it can affect it or not. The connection to the site is not secure also. Please give suggetions what the problem might be. -
Handling 'Object of type SimpleUploadedFile is not JSON serializable' error in Django DRF tests
If you're working with nested parameters in Django and experiencing difficulties while testing, you can pass the data for the nested structure using dictionaries or JSON objects. Here's an example of how you can do it: serializer.py class ProductImageCreateSerializer(serializers.ModelSerializer): class Meta: model = AlProductImage fields = [ 'image_name', 'image_src' ] class ProductOptionCreateSerializer(serializers.ModelSerializer): option_length = serializers.IntegerField(default=0) is_active = serializers.CharField(default='y') is_direct_delivery = serializers.CharField(default='n') is_custom = serializers.CharField(default='n') class ProductCreateSerializer(serializers.ModelSerializer): name = serializers.CharField() brand_id = serializers.CharField(write_only=True) purchase_count = serializers.IntegerField(default=0) custom_yn = serializers.CharField(default='n') is_active = serializers.CharField(default='y') options = serializers.ListSerializer( child=ProductOptionCreateSerializer(), write_only=True, required=False, ) images = serializers.ListSerializer( child=ProductImageCreateSerializer(), write_only=True, required=False, ) tests.py class ProductTest(MainScenarioTest): def create_product(self, data): res = self.client.post( path='/product/product/', data=data, content_type='application/json', ) return res def test_product_create(self): brand = 1 input_data = dict( name='test product', brand_id=brand, options=[ { 'options': "test_option", 'option_length': 100, 'price': 500, 'delivery_fee': 300, 'direct_delivery_fee': 300, 'quantity': 300, }, { 'options': "test_option", 'option_length': 100, 'price': 500, 'delivery_fee': 300, 'direct_delivery_fee': 300, 'quantity': 300, } ], images=[ { 'image_name': 'test_image_1.jpg', 'image_src': SimpleUploadedFile( 'test_image_1.jpg', open(os.path.join('test_imgs', 'hanssem.jpg'), 'rb').read() ) } ] ) res = self.create_product(input_data) print(res) I have an error [Object of type SimpleUploadedFile is not JSON serializable] I tried encoding it in base64, but it failed because the image_src field is of type FileField. I also … -
How to add firebase google login method to a django app
I am developing a Django web application and I would like to integrate Firebase Google Login for user authentication. I have gone through the Firebase documentation, but I couldn't find a direct approach for implementing Google Login in Django. I would like to know how I can add Firebase Google Login to my Django app. Specifically, I would like to achieve the following: Allow users to sign in to my Django app using their Google accounts. Retrieve user information such as email, name, and profile picture from Google after successful authentication. Save the authenticated user to Firebase Authentication for further authentication and authorization. I have already set up Firebase for my project and obtained the necessary service account JSON file. I have also installed the required packages like firebase-admin, -
How to make django-filter depend on another django-filter
I'm using package django-filter and i have some fields which i want to be depend on another field like i have field name and field car and if i choose name Michael in name filter, filter car will show me only cars that Michael has This looks like a big problem and i dont know how to solve that filters.py import django_filters from django_filters import DateTimeFromToRangeFilter from django.db.models import Q from common.filters import CustomDateRangeWidget from common.models import CounterParty, ObjectList from .models import OpenPointList class OpenPointFilter(django_filters.FilterSet): """ Django-filter class to filter OpenPointList model by date, CounterParty name and Object name """ CHOICES = ( ('Closed', 'Closed'), ('Open', 'Open') ) status = django_filters.ChoiceFilter(choices=CHOICES) category_choice = django_filters.ModelChoiceFilter(label='Категория', queryset=OpenPointList.objects.values_list('category', flat=True).distinct()) category = django_filters.CharFilter(method='custom_category_filter') class Meta: model = OpenPointList fields = ( 'open_point_object', 'status', 'category', ) -
Django - CrispyForms - DecimalField - Validation Error Message
I have the following model and would like to ensure that a) either the user is able to enter only numbers and a decimal point or b) a custom validation error is displayed to the user to enter a decimal value only. I am using the init method and would like to include such validation in this method. Is it possible?. The CurrencyCode is a ForeignKey field so it has to appear as a dropdown on the rendered form. Below is the code and screenshots: MODELS.PY: class Forex(models.Model): currency_code = models.ForeignKey(Currency, on_delete=models.CASCADE) forex_rate = models.DecimalField(max_digits=8, decimal_places=4) last_updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Forex Rates" def __str__(self): return self.currency_code.currency_code FORMS.PY: class ForexForm(forms.ModelForm): class Meta: model = Forex fields = ['currency_code', 'forex_rate'] def __init__(self, *args, **kwargs): super(ForexForm, self).__init__(*args, **kwargs) self.fields['currency_code'].error_messages = {'required': 'Currency Code Cannot Be Blank', 'unique': 'Forex Rate Already Exists!' } self.fields['forex_rate'].error_messages = {'required': 'Forex Rate Cannot Be Blank'} VIEWS.PY: def forex_add(request): form = ForexForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, msg_add) return redirect('forex_list_page') context = { 'form': form } return render(request, 'main/forex_add.html', context) FOREX_ADD/HTML: <form action="" method="POST" novalidate> {% csrf_token %} <div class="row"> <div class="col-4"> {{ form.currency_code|as_crispy_field }} </div> <div class="col-8"> {{ form.forex_rate|as_crispy_field }} </div> </div> <div class="col-12"> … -
Why is django TestCase not connecting to test database?
1 I am writing a Django test inheriting from django.test.TestCase. Everywhere, in the docs, it says a test db will be automatically created. Here I am using the very standard approach but the test_get_opportunity class method is using my production db. Even tough a test db is created the objects.create doesnot populate it with data and the datas are fetched from my production db Please see my code bellow. from django.test import TestCase import request from core.models import Opportunity class OpportunityViewTest(TestCase): def test_get_opportunity(self): # Create a test opportunity opportunity = Opportunity.objects.create(name='TestOpportunity', created_by='postgres') print(opportunity.id) # Set up the request url = "http://127.0.0.1:8000/pure-protect/opportunity/" data = {'opportunity_id': opportunity.id} response = requests.get(url, data) print(response.json()) # Assert the response self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()['status'], 'success') I have used --keepdb to verify id the data is updated in the table but its not updated When i hard code the opportunity_id in request. I see the datas are fetched from production db What do I do wrong and what has to be done so a test db is used for the test? -
Iterate over a list in a template from a dictionary generated in View file
I am creating a table in Django with columns of static and dynamic data. The dynamic data is easy to call from the database and loop through. The static data has been stored in the View as a dictionary. The problem I'm facing is when I need to iterate over a list in the template that comes via the dictionary. Here is the template code: <thead> <tr> <th>Amino acid</th> <th>Common</th> <th>Example species</th> <th>All consumers</th> <th>Text</th> <th>Image</th> </tr> </thead> <tbody> {% for amino_acid, use, text, image in amino_acids %} <tr> <td>{{ amino_acid }}</td> <td>{{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'count' }}</td> <td> {{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'example_list' }} </td> <td> {{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'total_count' }} </td> <td> {{ text }} </td> <td><img src="{{ image }}" style="width: 200px; height: 150px;"> </td> </tr> {% endfor %} </tbody> This works fine, except for {{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'example_list' }} which just displays the list like this: ['bacteria1', 'bacteria2' etc.]. Ideally, I'd like to iterate over this list and link urls to each list item, e.g.: {% for bug in example_list.items %} <i><a href="/bacteria/{{ bug.slug }}" target="_blank">{{bug}};</a></i> {% endfor %} Is there a way to do this either in the template or in the view?