Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found (404) No Invoice matches the given query
I am building a store in django. And I connected the store to a test payment gateway, and I can add products to the shopping cart, and do the test payment locally. But the problem occurs when I do a test payment and I have to be redirected to the callback.html page and I get an error. Image of the error that occurred Error image views.py file in the shop application: # Views.py in shop app import decimal from decimal import Decimal from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, get_object_or_404, redirect from . import models from cart.forms import CartAddProductForm from cart.cart import Cart from zeep import Client, client import requests import json # Index function def index(request): product_list = models.Product.objects.all()[:5] return render(request, 'index.html', {'product_list': product_list}) # Checkout function @login_required def checkout(request): cart = Cart(request) if request.method == 'POST': order = models.Order.objects.create(customer=request.user) for item in cart: models.OrderItem.objects.create(order=order, product=item['product'], product_price=item['price'], product_count=item['product_count'], product_cost=Decimal(item['product_count']) * Decimal(item['price'])) order.customer = request.user order.save() cart.clear() return render(request, 'order_detail.html', {'order': order}) return render(request, 'checkout.html', {'cart': cart}) # Product function def product(request, pk): product_detail = get_object_or_404(models.Product, id=pk) cart_add_product_form = CartAddProductForm() return render(request, 'product.html', {'product_detail': product_detail, 'cart_add_product_form': cart_add_product_form}) # Store function def store(request): return render(request, 'store.html') … -
How can use the ability to limit ip in Django?
I am using django 4.1 and I curious about how can use IP restriction in django .I have some experience about using packages like django-block-ip and Django-ip-restriction and Django-iprestrict . All of these packages old and do not work properly with django 4.1 version.is there any updated package for doing this ? I will appreciate your help very much -
In Django, how one employee could add the event(task) to his work_plan list?
I have an application that allows different organisers to publish their events (job vacancies) to potential workers(children tutors in this case). BTW, one event need only one tutor. A tutor can reserve the event but can not remove it without admin/organiser's permission. Also a tutor could not take another event that happens on the same day. I have already successed to show all published events in a list view. But I've got stuck on how a tutor could reserve that event, then add event to his/her own work plan list. Some codes may have typo as I modified many times. But hopefully you got my idea. Thanks. Here are a couple of pictures for a better understaning: I've tried the following code, after clicked the reserve button, it shows nothing. here is the view @login_required @is_tutor def work_plan(request): user=request.user work_plan=work_plan.objects.all() context={'work_plan':work_plan} return render(request,'work_plan.html',context) @login_required #reserve event @is_tutor def add_to_work_plan(request,pk): event =Summer_event.objects.get(id=pk) if request.method == "POST": if request.session.get("add_to_work_plan"): requst.session['add_to_work_plan'].append(pk) else: requst.session['add_to_work_plan']=[pk] work_plan.save() messages.success(request, "Work plan updated!") return redirect('work_plan') Model: class Work_plan(Summerevent): user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE) reserved_date = models.DateField(null=True,auto_now_add=True) Url: path('work_plan/', views.work_plan, name="work_plan"), path('add_to_work_plan/<str:pk>/', views.add_to_work_plan, name="add_to_work_plan"), html template {% extends "header.html" %} {% block title %}{{section.title}}"{% endblock %} {% block content %} {% if events … -
Cant find out how can I compare two manytomany fields and show the result in context
So, I am doing a project where there are posts of 3 categories (movies(model name="List"), music(model name="MusicList"), books(model name="BookList")) each category is a model. and each model has its own genre set model (Genre, MusicGenre, BookGenre). There is a profile model which has - favourite_music_genre, favourite_movie_genre & favourite_book_genre. So now in my all(homepage) function in views I want to have some codes that will compare current logged in users favourite_music_genre, favourite_movie_genre & favourite_book_genre and show only the List, MusicList & BookList of the matched genres. For example if a users selected fav_genre is Action & Comedy. It will only show the lists which has Action & Comedy genre. Im new to python/django. Been scratching my head for past 4/6 days. couldn't figure out the way. In my Models.py class MusicList(models.Model): title = models.CharField(max_length=120) genre = models.ManyToManyField('MusicGenre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Music") slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return f'{self.title}|{self.creator}' def save(self, *args, **kwargs): self.slug = slugify(self.title + str(self.posted)) super(MusicList,self).save(*args, **kwargs) class MusicGenre(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BookList(models.Model): title = models.CharField(max_length=120) creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) genre = models.ManyToManyField('BookGenre') posted = models.DateTimeField(auto_now_add=True) spoiler_choices = [(False, … -
How to pass a list of tuples in template file from views so I can separately iterate each data member in template?
I'm working on a django project , I got a list of tuples accessed from postgres database using psycopg2. Now I want to pass this list of tuples to my template file in such way that I can access each element of individual tuple. As I have to put this data into a html table. views.py file : def search_owner_prop(request): if request.method == 'POST': o_no = request.POST.get('owner_num') conn = psycopg2.connect(database="dreamhomeproperty", user="postgres", password="****", host="*****", port="****") cur = conn.cursor() cur.execute(f''' SELECT property_for_rent.property_n,private_owner.fname,property_for_rent.street,property_for_rent.rooms,property_for_rent.typee FROM dreamhome_schema.property_for_rent INNER JOIN dreamhome_schema.private_owner ON property_for_rent.owner_number={o_no} AND private_owner.owner_no={o_no}''') rows = cur.fetchall() conn.close() return render(request,'owner_with_prop.html') else: return render(request, 'search_owner_prop.html') -
Django - Automatically Create Model When Creating User
I have a Student Model, which should extend the Base User Model. Now I did this with a One to One Relation, but once my WebApp is done, I'd like to be able to create all the Users fast. Is there a way of adding all the fields of the Student Model into the User Creating Panel in /admin/? Here is my User Model for anyone wondering: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) def return_address(self): address = self.street + ' ' + str(self.street_number) + ' ' + self.city + ' ' + str(self.code) + ' ' + self.province return address def __str__(self): address = self.return_address() return f'Adresse: {address}' -
Configuring django channels
It is my first time working with channels in django. I am trying to establish a websocket connection with my server for a chat application. The javascript code on the html page is <body> <div id="user-hello"></div> {{ room_name|json_script:"room-name" }} <script> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data) console.log(data) document.querySelector('#user-hello').innerHTML =(data.tester) } </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> </body> When javascript tries to establish a connection to the websocket it throws an error, it cant find the url. My settings file is as follows INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat' ] ASGI_APPLICATION = 'config.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } The routing.py file being referenced by ASGI_APPLICATION is from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) Routing.py file in the chat app from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()), ] Finally consumer.py is import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( … -
DjangoDash How to use django pure html with dash callbacks
I was wondering, my team and I are considering using Django with Dash and React to build our application! Django - backend React - frontend Dash - dashboards (also frontend) So one thing I was trying to find out how to do but couldn’t is using pure HTML in a Django template, create an element, give it an id, and use that element inside a dash callback. for example: inside an HTML file I would have: inside the python dash file, we will have a callback returning value to that element Output(“hello”, “children”) Anyone knows a way to do this? / a repo with an example would be awesome! -
DjangoAapp keeps logging out for standard user and admin (staff) - cookies issue
Have a working Django app in production, there are several issues that appear while logging in, moving to sites that are for staff only (using decorators), etc. When logging in, I sometimes need to do it 2x, 3x times, or more, just repeat the username & password, so the user can get inside the portal (no error is thrown) When logging in as "staff", have some sites on the Portal which are restricted, often it asks to enter the password again (and shows the standard Django admin login page although still working on the app) - like the web browser does not remember that "staff" logged in already When already re-logged as the staff (above point), while continuing to do some actions on the page, like adding posts when hitting the "post" button it asks for the password again (note, I created an admin page on the website, to add posts, manage users, etc.) I suspect this is related to either: My Cookie setup Decorators used, restricting access to logged-in users or staff only Appreciate your help! settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_AGE = 24*60*60*7 #1 week SESSION_COOKIE_SECURE = True SESSION_COOKIE_NAME = 'www.mywebsite.com' CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = … -
Django forms: queryset and custom choices in ModelChoiceField
I am trying to create a choice field in a form, where the user will select the location of the item in the list. In the form, user selects one of existing items and places new item before that or the empty_label, which places the item to the end of the list. What I would like is to place the empty_label as a last selection in the choices. Other option is to hide the empty_label (empty_label=None) and add a choice after the queryset with a label 'Add to the end of the list'. I cannot get either one of these to work. Here is a code for the form. class NewItem(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewItem, self).__init__(*args, **kwargs) addbefore = ModelChoiceField( queryset=Items.objects.all().order_by('order'), empty_label='Add to the end of the list', label="Item location in the list / before item:", ) class Meta: model = Item fields = [ 'name', 'description', 'addbefore', ] So with this I get a choices where the 'Add to the end of the list' is the first selection, which is not logical. Is there a way to place the empty_label at the end of the choices or add custom choices after queryset? -
FieldError: Related Field got invalid lookup: contains
I am trying to implement a simple search where the user enters any string in the search input and the entire table is checked for the presence of string. My model class S_Owner_Master(models.Model): User= settings.AUTH_USER_MODEL flat_status = (('0', "Vacant"), ('1', "Occupied")) occupants = (('0', "Vacant"), ('1', "Owner"), ('2', "Tenant")) society = models.ForeignKey(S_Society_Master, related_name='society', null = True, on_delete=models.CASCADE) owner_id = models.AutoField(verbose_name = "Owner ID", primary_key=True, unique=True) owner_name = models.CharField(verbose_name = "Owner Name", max_length=100, blank=True, null=True) owner_email_id = models.EmailField(verbose_name = "Owner Email", max_length=100) owner_contact_number = models.CharField(verbose_name="Phone Number", max_length=15) owner_flat_number = models.CharField(verbose_name="Flat No.", max_length=20) owner_flat_registration_date = models.DateField(verbose_name = "Owner Flat Regn. Date") owner_flat_transfer_date = models.DateField(verbose_name = "Owner Flat Transfer Date") flat_area_in_sqft = models.DecimalField(verbose_name="Flat Area", max_digits=10, decimal_places=2) flat_occupancy_status = models.CharField(verbose_name="Occupancy Status", max_length = 50, choices=flat_status) occupied_by = models.CharField(verbose_name="Occupied By", max_length = 50, choices=occupants) deld_in_src_ind = models.CharField(max_length=20, choices=[("yes", "Yes"), ("no", "No")], default = "no", blank=True, null=True) created_date = models.DateField(verbose_name = "Created Date", auto_now_add = True) created_by = models.ForeignKey(User, related_name = "+", on_delete = models.SET_NULL, verbose_name="Created By", max_length=100, blank=True, null=True) updated_date = models.DateField(verbose_name = "Last Updated Date", auto_now_add = True, blank=True, null=True) updated_by = models.ForeignKey(User, related_name = "+", on_delete = models.SET_NULL, verbose_name="Updated By", max_length=100, blank=True, null=True) views.py def owner_simple_search(request): search_text = request.GET.get('search_field', None) if search_text is … -
How to make sure random string in django python model will unique
I have a question with the random string in python django. I have created a django model class Post(models.Model): slug = models.SlugField(unique=True,blank=True) title = models.CharField(max_length=200) description = models.TextField() def save(self, *args, **kwargs): str_ran = "abcdefghijklmnopqrstuvwxyz" slug = "" for i in range(5) : slug += random.choice(str_ran) self.slug = slug super(Post, self).save(*args, **kwargs) But sometimes that's have some error because the slug field is not unique by python random isn't random a unique string. What should i do? Do you have some recommend for random these string to make sure it will be unique? -
Django JSONField Aggregate and Sum
I have the below JSON saved in PostgreSQL 9.4 DB and running Django 2.2 [{"rating": 6, "companyvalue_id": 188, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 7, "companyvalue_id": 207, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 4, "companyvalue_id": 207, "team_members_name": "xakir tester", "users_teammember_id": 2795}] There is many database entries. I would like to aggregate all instances of team_members_name and Sum to find out the total rating. The JSON data is saved in a model field data = JSONField(null=True, blank=True) The closest I have is def data_rating(self): model = apps.get_model('model', 'ModelName') model_count = rating_tool.objects.all() return model_count.objects.annotate( rating=Cast( KeyTextTransform("rating", "data"), IntegerField(), ) ).values("rating").distinct().aggregate(Sum("rating"))["rating__sum"] The above only works for single JSON object, i.e. {"rating": 6, "companyvalue_id": 188, "team_members_name": "pidofod tester", "users_teammember_id": 2793} however I need KeyTextTransform to work across many JSON objects and in many database rows. I also need to filter/aggregate each user, i.e. what is "team_members_name": "pidofod tester" total rating Sum. End result is to return this result in a DRF endpoint. Have tried many options as below but none work or seem close, feel a model re-work may be needed. Any ideas or suggestions appreciated! #return rating_tool_count.annotate(numbers_len=Func(F('rating_tool_data'), function='jsonb_array_length')).aggregate(rating_total=Sum(F("rating"))) #return rating_tool_count.annotate(single_nested_value=F("rating_tool_data__team_members_name"),array_access=F("rating_tool_data__rating"),) #return rating_tool.objects.aggregate(Sum('rating_tool_data__rating')) #.values('rating_tool_data__rating').annotate(rating_total=Sum(Cast(KeyTextTransform("rating", "rating_tool_data"), models.IntegerField()))) #return rating_tool_count.annotate(team_members_name=Cast(KeyTextTransform( #"team_members_name", "rating_tool_data"), models.TextField())).values("rating_tool_data").annotate(rating_total=Sum(Cast(KeyTextTransform("rating", "rating_tool_data"), #models.IntegerField())),).order_by("-rating_total") #return … -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'mysite.routing'
I am trying to create a webapp using django and while running it on my local system, I am getting stucked here because of this issue.Even though the asgi,wsgi and settings are configured properly.Its showing that it cant import asgi application.Can someone check what's the issue is ? asgi.py """ ASGI config for mysite project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os import sys import django from channels.routing import get_default_application from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') # django.setup() application = get_asgi_application() wsgi.py """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() At first I thought it was about the Base dir not getting initialised, show I tried using pathlib, but still it didnt work setting.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.8. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Adding a url field linking to an action in serializer in DRF
I am using django rest framework. I want to include the url of an action defined in a view in its serializer. My serializers.py: from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): """Serializer for comments.""" class Meta: model = Comment fields = ["id", "item", "author", "content", "date_commented", "parent"] class ItemDetailSerializer(serializers.ModelSerializer): """Serializer for items (for retrieving/detail purpose).""" category = CategorySerializer(many=True, read_only=True) media = MediaSerializer(many=True, read_only=True) brand = BrandSerializer(many=False, read_only=True) specifications = serializers.SerializerMethodField(source="get_specifications") comments = ?????????????????????????????????????????????????? class Meta: model = Item fields = [ "id", "slug", "name", "description", "brand", "show_price", "location", "specifications", "is_visible", "is_blocked", "created_at", "updated_at", "seller", "category", "media", "comments", "users_wishlist", "reported_by", ] read_only = True editable = False lookup_field = "slug" def get_specifications(self, obj): return ItemSpecificationSerializer(obj.item_specification.all(), many=True).data My views.py: from rest_framework import viewsets, mixins, status from ramrobazar.inventory.models import Item, Comment from ramrobazar.drf.serializers ItemSerializer, ItemDetailSerializer, CommentSerializer from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.filters import SearchFilter from django_filters.rest_framework import DjangoFilterBackend class ItemList(viewsets.GenericViewSet, mixins.ListModelMixin): """View for listing and retrieving all items for sale.""" queryset = Item.objects.all() serializer_class = ItemSerializer serializer_action_classes = { "retrieve": ItemDetailSerializer, } permission_classes = [IsAuthenticatedOrReadOnly] lookup_field = "slug" filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = [ "category__slug", "brand__name", ] search_fields = ["name", "description", "category__name", "brand__name", "location"] def get_serializer_class(self): try: return self.serializer_action_classes[self.action] except: return self.serializer_class def … -
raise InvalidSchema("No connection adapters were found for {!r}".format(url) while using requests module
I'm getting this error every time my for-loop makes a call to the API. The curious thing is I'm still getting an json object result for the first query the call has an issue with as such, requests.exceptions.InvalidSchema: No connection adapters were found for '{\'page\': 1, \'results\': [{\'backdrop_path\': \'/c4CSgKL6QfkJxsWcGYDyTxpbzpW.jpg\', \'first_air_date\': \'2017-03-31\', \'genre_ids\': [18, 9648], \'id\': 66788, \' and etc. After doing some research, I'm starting to think somewhere down the line my url added an extra "" or '' or perhaps its confusing the strings data type due it having integers in the title: "12 Monkeys", "90210". How do I check for this and also fix it? Here is my relevant code: from email.mime import base import pprint from pkgutil import get_data from pydoc import pager from unittest import result from django.http import JsonResponse from django.shortcuts import render, HttpResponse, redirect from .models import * import json from django.core.paginator import Paginator from django.db.models import Q import requests from pprint import pp, pprint ... for lists in post: data = requests.get(F'https://api.themoviedb.org/3/search/tv?api_key={api_key}&language=en-US&page=1&include_adult=false&query={lists}') r = data.json() response = requests.get(r) response.raise_for_status() # raises exception when not a 2xx response if response.status_code != 204: return response.json() -
How can I use slugs in Django url like mysite.com/user
I want to create a directory like website.com/user after the user get logged in! And I'm not sure which url pattern should call this myfun def myfun(request, user): user = get_user_model().objects.get(slug=user) return render(request, 'authorization/home.html', {'user' : user}) models.py class TwitterUser(models.Model): screen_name = models.CharField(max_length=255) name = models.CharField(max_length=255) user = models.SlugField('auth.User', unique=True, null=True) app/urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] view.py def twitter_login(request): twitter_api = TwitterAPI() url, oauth_token, oauth_token_secret = twitter_api.twitter_login() if url is None or url == '': messages.add_message(request, messages.ERROR, 'Unable to login. Please try again.') return render(request, 'authorization/error_page.html') else: twitter_auth_token = TwitterAuthToken.objects.filter(oauth_token=oauth_token).first() if twitter_auth_token is None: twitter_auth_token = TwitterAuthToken(oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) twitter_auth_token.save() else: twitter_auth_token.oauth_token_secret = oauth_token_secret twitter_auth_token.save() return redirect(url) def twitter_callback(request): if 'denied' in request.GET: messages.add_message(request, messages.ERROR, 'Unable to login or login canceled. Please try again.') return render(request, 'authorization/error_page.html') twitter_api = TwitterAPI() oauth_verifier = request.GET.get('oauth_verifier') oauth_token = request.GET.get('oauth_token') twitter_auth_token = TwitterAuthToken.objects.filter(oauth_token=oauth_token).first() if twitter_auth_token is not None: access_token, access_token_secret = twitter_api.twitter_callback(oauth_verifier, oauth_token, twitter_auth_token.oauth_token_secret) if access_token is not None and access_token_secret is not None: twitter_auth_token.oauth_token = access_token twitter_auth_token.oauth_token_secret = access_token_secret twitter_auth_token.save() # Create user info = twitter_api.get_me(access_token, access_token_secret) if info is not None: twitter_user_new = TwitterUser(twitter_id=info[0]['id'], screen_name=info[0]['username'], name=info[0]['name'], profile_image_url=info[0]['profile_image_url']) twitter_user_new.twitter_oauth_token = twitter_auth_token user, … -
How to use "\dt" in cursor.execute() to get the tables in PostgreSQL? (Django)
In Django, I'm trying to use \dt in cursor.execute() to get the tables in PostgreSQL as shown below: # "views.py" from django.http import HttpResponse from django.db import connection def test(request): cursor = connection.cursor() cursor.execute('''\dt''') # Here row = cursor.fetchone() print(row) return HttpResponse("Test") But, I got the error below: django.db.utils.ProgrammingError: syntax error at or near "" LINE 1: \dt So, I replaced cursor.execute('''\dt''') with cursor.execute('''\\dt''') as shown below: # "views.py" from django.http import HttpResponse from django.db import connection def test(request): # ... cursor.execute('''\\dt''') # Here # ... return HttpResponse("Test") But, I still got the error below: django.db.utils.ProgrammingError: syntax error at or near "" LINE 1: \dt So, how do I use \dt in cursor.execute() to get the tables in PostgreSQL? -
Generating PDF with filter dates
I am trying to generate pdf with filter dates using modal. If there is no filter dates, I can generate the PDF but if there is a filter date there is an error [22/Oct/2022 08:59:38] "POST /generateinvoicevehicle/ HTTP/1.1" 405 0 Internal Server Error: /generateinvoicevehicle/ If I refresh the page, "UnboundLocalError: local variable 'incident_vehicle' referenced before assignment [22/Oct/2022 08:59:41] "GET /generateinvoicevehicle/ HTTP/1.1" 500 72789" How can I generate the report correctly with filter dates? Thank you Views class GenerateInvoiceVehicle(View): def get(self, request, *args, **kwargs): try: if request.method == 'POST': fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') if fromdate: incident_general = IncidentGeneral.objects.filter(user_report__date__gte=fromdate) incident_vehicle = IncidentVehicle.objects.filter(incident_general__user_report__date__gte=fromdate) if todate: incident_general = IncidentGeneral.objects.filter(user_report__date__lte=todate) incident_vehicle = IncidentVehicle.objects.filter(incident_general__user_report__date__gte=fromdate) # incident_general_accident = IncidentGeneral.objects.filter(user_report__status = 2).values('accident_factor__category').annotate(Count('severity'), filter=Q(severity='Damage to Property')) incident_vehicle = incident_vehicle.filter(incident_general__user_report__status = 2) incident_vehicle1 = incident_vehicle.filter(incident_general__user_report__status = 2,incident_general__severity='Fatal' ).annotate(Count('incident_general__severity')) incident_vehicle2 = incident_vehicle.filter(incident_general__user_report__status = 2,incident_general__severity='Damage to Property' ).annotate(Count('incident_general__severity')) incident_vehicle3 = incident_vehicle.filter(incident_general__user_report__status = 2,incident_general__severity='Non-Fatal' ).annotate(Count('incident_general__severity')) # incident_general_classification = IncidentGeneral.objects.filter(user_report__status = 2, severity="Damage to Property").distinct('accident_factor') except: return HttpResponse("505 Not Found") data = { 'incident_vehicle': incident_vehicle, # 'incident_general_classification': incident_general_classification, 'incident_vehicle1': incident_vehicle1, 'incident_vehicle2': incident_vehicle2, 'incident_vehicle3': incident_vehicle3, # 'incident_general_collision3': incident_general_collision3, # 'amount': order_db.total_amount, } pdf = render_to_pdf('pages/generate_report_pdf_vehicle.html', data) #return HttpResponse(pdf, content_type='application/pdf') # force download if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Vehicle_Classification.pdf" #%(data['incident_general.id']) content … -
"GET / HTTP/1.1" 500 145
Anytime I turn debug to false in my settings.py my site gives a server error. This is what my server shows and the site doesn't work again Performing system checks... System check identified no issues (0 silenced). October 21, 2022 - 23:47:07 Django version 4.1.2, using settings 'dlcfogbomoso.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [21/Oct/2022 23:47:09] "GET / HTTP/1.1" 500 145 [21/Oct/2022 23:54:18] "GET / HTTP/1.1" 500 145 Please any help? -
Cross-Origin Resource Sharing (CORS) headers not being added to responses
Cross-Origin Resource Sharing (CORS) headers not being added to responses, in-browser requests to my Django application from other origins not seeming possible. I have followed the instructions here on PyPi with no help. I have included the console area I receive. https://pypi.org/project/django-cors-headers/ I am looking to fetch a json file. Console errors: Access to fetch at 'http://localhost:8000/api/cats' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. App.vue:59 GET http://localhost:8000/api/cats net::ERR_FAILED 301 fetchcats @ App.vue:59 _createElementVNode.onClick._cache.<computed>._cache.<computed> @ App.vue:29 callWithErrorHandling @ runtime-core.esm-bundler.js:155 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:164 invoker @ runtime-dom.esm-bundler.js:339 runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of native event handler at <App> warn2 @ runtime-core.esm-bundler.js:38 logError @ runtime-core.esm-bundler.js:212 handleError @ runtime-core.esm-bundler.js:204 (anonymous) @ runtime-core.esm-bundler.js:167 Promise.catch (async) callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166 invoker @ runtime-dom.esm-bundler.js:339 App.vue:59 Uncaught (in promise) TypeError: Failed to fetch at Proxy.fetchcats (App.vue:59:28) at _createElementVNode.onClick._cache.<computed>._cache. <computed> (App.vue:29:18) at callWithErrorHandling (runtime-core.esm-bundler.js:155:22) at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21) at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:339:9) fetchcats @ App.vue:59 _createElementVNode.onClick._cache.<computed>._cache.<computed> @ App.vue:29 callWithErrorHandling @ runtime-core.esm-bundler.js:155 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:164 invoker @ runtime-dom.esm-bundler.js:339 Promise.catch (async) callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166 invoker @ runtime-dom.esm-bundler.js:339 -
save() saves all fields except ManyToMany field
I have a model "Contest" with one m2m field called "teams" which is related to a model "Team". I overrided the method save. In my save() function (the one that's overriding), I need a queryset (in my save overrinding function) with all the objects related to my team m2m field. The code is self.teams.all() but it won't work because my models is not yet registered in database right ? So I call super().save(*args, **kwargs) now my models is saved and I can get my queryset ? I can't. The queryset is empty, even if I registered team(s). <QuerySet []> Why does super.save() save immediately all the fields except the m2m ? I use exclusively the django admin web site to create models. No manage.py shell or form. My model : class Contest(models.Model): name = models.CharField(max_length=16, primary_key=True, unique=True, default="InactiveContest", blank=True) # Ex: PSGvMNC_09/2017 id = models.IntegerField(default=1) teams = models.ManyToManyField(Team, verbose_name="opposants") date = models.DateTimeField(blank=True) winner = models.ForeignKey(Team, verbose_name='gagnant', related_name='winner', on_delete=models.SET_NULL, blank=True, null=True) loser = models.ForeignKey(Team, verbose_name='perdant', related_name='loser', on_delete=models.SET_NULL, blank=True, null=True) bet = models.IntegerField(verbose_name='Nombre de paris', default=0, blank=True, null=0) active = models.BooleanField(default=False) def save(self, *args, **kwargs): if self._state.adding: self.active = False # Django's id field immitation last_id = Contest.objects.all().aggregate(Max('id')).get('id__max') if last_id is not … -
What's the best way to desplay list of inons using Django?
I'm working on a small project where I have a table named 'icons' that contains paths for stored icons inside folder 'mydjangoproject/app/icons' and I have an endpoint "mydomainname.com/user/icon/< name >" I want the user to be able to replace with the icon that he wants and he gets in return the icon For example if the user took this link mydomainname/user/icon/car.png and used it in an tag or typed it in the browser it would work and show that specific icon What is the best way to do that? -
POST http://localhost:8000/add_new/ 500 - Django
I have a question about django. In my ecommerce website I am trying to add add to cart function. My code is working and I can add to the cart with AnonymousUser. But, when i try to add to cart when I logged in with account, I am having this error: error: Internal Server Error So, it's adding to the cart, but location.reload is not working. I need to restart manually. What is the problem? Please, help! -
Django DetailView dont show data in template
I am completely new to Django CBV and I don't understand why I can't display data in template with using DetailView. I have no errors, just can't display any data in template. I have spent hours trying to figure it out, but I am slowly giving up This is my model: class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title views.py: class ProjectListView(ListView): model = Project class ProjectView(DetailView): model = Project template_name = 'base/single-project.html' (I have tried with get_context_data() and get_object() but the effect was the same) urls.py: urlpatterns = [ path('', ProjectListView.as_view(), name='projects'), path('project/<str:pk>/', ProjectView.as_view(), name='project'),] and the template: {% extends 'main.html' %} <p>{{ object }}</p> <p>{{ object.title }}</p> <p>{{ project.title }}</p> <p>{{ project }}</p> (Here I just tried to see anything)