Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use pop-up notifications in Django with Bulma?
I am making an app using Django, and I want to implement Bulma alerts, like this: But, I can't figure out how. I need them to inform the user if they filled out a form correctly. Does anyone know how to implement this? -
Cannot display a comment on a blog page - django
I have been trying to create a comment section for a blog site. Comments should only be made by the site's users. I am able to make comments and display them in the comment section from the admin panel, but when the users submit comments they don't display in the webpage. Here are my models.py: class Sight(models.Model): CATEGORY_MAX_LEN = 25 NAME_MAX_LEN = 30 LOCATION_MAX_LEN = 100 IMAGE_UPLOAD_TO_DIR = 'destinations/' name_of_sight = models.CharField( verbose_name='Name of Sight', max_length=NAME_MAX_LEN, unique=True, ) location = models.CharField( verbose_name='Location', max_length=LOCATION_MAX_LEN, ) category = models.ForeignKey( Category, on_delete=models.CASCADE, # choices=CATEGORIES ) description = models.TextField( verbose_name='Description', ) post_date = models.DateTimeField( auto_now_add=True, ) pros = models.TextField( verbose_name='Pros', null=True, blank=True, ) cons = models.TextField( verbose_name='Cons', null=True, blank=True, ) image = models.ImageField( upload_to=IMAGE_UPLOAD_TO_DIR, verbose_name='Image', ) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def __str__(self): return '%s - %s' % (self.name_of_sight, self.user) class SightComment(models.Model): MAX_BODY_LENGTH = 500 sight = models.ForeignKey( Sight, related_name='sight_comments', on_delete=models.CASCADE, blank=True, null=False, ) body = models.TextField() publication_date_and_time = models.DateTimeField( auto_now_add=True, blank=True, null=False, ) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def __str__(self): return '%s - %s' % (self.sight.name_of_sight, self.user) My form.py: class SightCommentForm(forms.ModelForm): class Meta: model = SightComment fields = ('body',) widgets = {'body': forms.Textarea(attrs={'class': 'form-control', 'cols': 30, 'rows': 4})} labels = { … -
ImportError: cannot import name 'Ingredient' from 'inventory.models' (C:\Users\mcarl\OneDrive\Desktop\VirtualEnvs\djangodelights\inventory\models.py)
So I am at a point in my project where I need to create instances of my models inside of the python shell. The problem is when I go to import my Ingredient model (which I've checked probably a hundred times now to find out if it was correct), I get this message - ImportError: cannot import name 'Ingredient' from 'inventory.models' (C:\Users\mcarl\OneDrive\Desktop\VirtualEnvs\djangodelights\inventory\models.py) The file structure is correct and everything.. How are they saying there is no Ingredient when there is a model called Ingredient inside the file..? Any idea how to fix.? Thanks My models.py file: from django.db import models import datetime class Ingredient(models.Model): name = models.CharField(max_length=100) available_quantity = models.DecimalField(max_digits=10, decimal_places=2) price_per_unit = models.DecimalField(max_digits=10, decimal_place=2) class MenuItem(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) class RecipeRequirement(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity_required = models.DecimalField(max_digits=10, decimal_places=2) class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) purchase_date = models.DateTimeField(auto_now_add=True) quantity_purchased = models.DecimalField(max_digits=10, decimal_places=2) total_cost = models.DecimalField(max_digits=10, decimal_place=2) File structure, fixing typos, clearing python cache.. -
Connect django-server which are hosted by railway.app to react-server, also hosted by railway.app
I'm trying to connect my running Django-server to my running react-"server", but I don't know how... I have done the task with my apache-server, but can't manage to do it in railways.app. Any helpful minds out there who can guide me to my goal? -
Using JS to update profile photo
I'm trying to write a Django application where there is a button to change the profile photo and when clicked, a file selection screen appears. After selecting the file, I see the upload successful message, but the new image I selected is not written to the database. I can't pass this step for days. template js code: <script> // JavaScript document.addEventListener("DOMContentLoaded", function () { const uploadButton = document.getElementById("uploadButton"); const fileInput = document.getElementById("fileInput"); uploadButton.addEventListener("click", function () { fileInput.click(); }); fileInput.addEventListener("change", function () { const formData = new FormData(document.getElementById("profileForm")); fetch("{% url 'update_profil_photo' %}", { method: "POST", body: formData, headers: { "X-CSRFToken": '{{ csrf_token }}' } }) .then(response => response.json()) .then(data => { if (data.success) { alert("Sucessfully updated!"); } else { alert("An error occured, please try again."); } }) .catch(error => { alert("an error occured, please try again."); }); }); }); </script> template html: <form method="post" enctype="multipart/form-data" action='{% url "update" %}' id="profileForm"> {% csrf_token %} <button class="btn btn-info" type="button" id="uploadButton"> <i class="fa fa-fw fa-camera"></i> <span>Change Photo</span> </button><input id="fileInput" type="file" style="display: none;"> </div> </div> view: @login_required def update_profil_photo(request): user_profile = get_object_or_404(UserProfile, user=request.user) user = request.user if request.method == 'POST': profile_form = UserProfilePictureUpdateForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Update is successful') return JsonResponse({'success': True}) … -
NGINX not serving django static files after ssl certificate was installed
After building my django app, I got it to work over http. The issue started after installing ssl certificate using certbot. Now, static files are no longer being served. This is my nginx configuration server { server_name pythonyard.com www.pythonyard.com *.pythonyard.com; location /static/ { alias /home/kenechukwu_webapp/allpython/backend/; } location / { proxy_pass http://localhost:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/pythonyard.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/pythonyard.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name pythonyard.com www.pythonyard.com *.pythonyard.com; return 404; # managed by Certbot } I have read through lots of similar problems here on stackoverflow but none has worked for me. Please what could be wrong? This is my first time using it -
how to Filter two models values in query sets
hi I'm Django rest framework in my I want to search filter 2 models at once class SearchViewSet(generics.ListAPIView): queryset = Profile.objects.all() serializer_class = SearchSerializer authentication_classes = [TokenAuthentication] filter_backends = [SearchFilter] search_fields = ["user__username", "caption", "post_text"] def get_queryset(self): search_query = self.request.GET.get("search") queryset = super().get_queryset() if search_query: # Filter the queryset based on the search query queryset = queryset.filter(user__username__icontains=search_query) # Get the related Post objects that match the search query post_queryset = Post.objects.filter( caption__icontains=search_query) | Post.objects.filter( post_text__icontains=search_query) # Get the distinct Profile objects that have related matching Post objects queryset = queryset.filter(posts__in=post_queryset).distinct() return queryset this is my serilizers. py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = "__all__" depth = 1 class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" class SearchSerializer(serializers.Serializer): profile = ProfileSerializer() posts = PostSerializer(many=True) I want to filter results by username as well as post description and post caption but the username belongs to ProfileSerilizers and the post description and post caption belongs to Post Sterilizers how can I achieve this I'm getting this error raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'posts' into field. Choices are: bio, id, id_user, location, profileimg, user, user_id -
S3 image URL to a python string and swap the backslashes
In my Django web app I use a function that takes the web request and goes to get the image URL from an S3 bucket and stores it into a variable. So I have a 2 part question I need to take that variable (which is holding the string) and turn forward slashes into back slashes Ultimately I am trying to verify that AWS has a path that exists, because right now it keeps telling me its false. def testPage(request, pk): photo = Photo.objects.get(id=pk) photo_url = str(photo.image.url) photo_path = str(request.build_absolute_uri()) print(photo_url) # "https://myBucketname.s3.amazonaws.com/Profile_pic_-_Copy.jpg" path_exists = os.path.exists(photo_url) # FALSE print(photo_path) # http://localhost:8000/prediction/68/ path_exists = os.path.exists(photo_path) # FALSE I have tried getting the raw string of the variable. I have tried to apply os.path.normpath() but it removes the double slash from the beginning of the URL. Any help on this would be great -
Django rest_framework serializer throwing an error
in the serializers.py from rest_framework import serializers from .models import Book ,MenuItem class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id','title','author','price'] class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem fields = ['id','title','price','inventory'] extra_kwargs = { 'price': {'min_value': 2}, 'inventory':{'min_value':0} } my model class MenuItem(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=6,decimal_places=2) inventory = models.SmallIntegerField Tried to send get request to my view , im facing the issue . Applying littlelemonapi.0002_menuitem... OK (API) rustemaisariyev@MacBook-Pro-Rustem littlelemon % python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 28, 2023 - 16:20:24 Django version 4.2.3, using settings 'littlelemon.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /api/menu-items Traceback (most recent call last): File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() ^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content ^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/renderers.py", line 723, in render context = self.get_context(data, accepted_media_type, renderer_context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/renderers.py", line 654, in get_context raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/renderers.py", line 562, in get_raw_data_form data = serializer.data.copy() ^^^^^^^^^^^^^^^ … -
Uncaught ReferenceError: Swal is not defined
Iam using swwetify on Djnago so I set all the parameter on settings , but send me this error Uncaught ReferenceError: Swal is not defined enter image description here Well I set the css and Js on Main Page. have to send me the message -
POST method of request returns the name whose value has been truncated after spaces
I am trying to create a calories app in which the user will select from a list of values (dropdown list) and then total calories consumed will be returned. Now I have a form in which there are certain food items and the user can select them and they will be added to food items consumed by the user in the database. The index.html file responsible for this action is as under: <div class="container"> <form method="POST"> {% csrf_token %} <select class="form-control" id="food_consumed" name="food_consumed"> {% for item in items %} <option value={{item.item_name}}> {{item.item_name}} </option> {% endfor %} </select> <button type="submit" class="btn btn-success m-3"> Add </button> </form> </div> The following view processes the data and stores it in the database: def index(request): if request.method == "POST": food_item_name = request.POST.get('food_consumed') food_item = FoodModel.objects.filter(item_name = food_item_name) food_consumer = request.user food_item_consumed = Consumer(food_consumer = food_consumer, food_consumed = food_item) food_item_consumed.save() food_items = FoodModel.objects.all() return render(request, 'CaloriesApp/index.html', context={'items':food_items}) However, I am encountering a weird error. The value of the food_item_name gets truncated after spaces, that is to say that for instance I have a food item called Egg, raw (147g), the name returned will be: "Egg,". However, when there are no spaces in food items names, there … -
Use django auth with WordPress
I want to make a website with Django as backend for most of the task, but for the frontend I want to use WordPress for page management and also to use Elementor as GUI page builder. But problem is that I want to make a single login system for both WordPress and Django with of course Django default user table. I have read a lot of articles about it they all somehow revolve wp-api but I don't require this in my case. I just want to sign-in into WordPress with Django table. And also if user is logged in into Django it must be logged into WordPress with same session (I am using same domain). -
Limit field permissions on Graphene Django
Lets say I got a user Type class UserType(DjangoObjectType): class Meta: model = User fields = [ "fieldA", "fieldB", "relationshipA", "relationshipB" ] And I want fieldB and relationshipB to be visible only to the owner (user). What is the best strategy to do this? Initially Ive created a PublicUserType excluding private fields, but quickly I realized that it might not be scalable because not only I'll have to create private representation for UserType I'll might also create private representation for any relationship (relationshipA etc), and proper resolvers, and duplicate fragments etc. Is there a best practice here? -
How to have a page/view have a different session duration in django?
I have a django project for which I must set the SESSION_COOKIE_AGE setting to 15 minutes, and I can not change that. In this project there also is a JS editor on a page: users can use the editor to make modification to something, and then hit the "save" button to save the result. The page is handled by a view. The editing can be time-consuming, so often happens that when the user clicks save, his session is already ended. How can I make that page and only that page have an unlimited session duration? Will a <script> making like a request each 5 min refresh the session successfully and keep it alive? -
Unable to create websockets with django
I have a django server that at the moment i am running on my local machine, the django server handles WSGI requests at the moment via http but i would also like to connect with websockets.i have tried many guides online but they all result with the websocket connection returning a 404. Any help would be appreciated. Project Structure: myProject myApp myProject.urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("server/", include("myApp.urls")), ] myProject.asgi import os import django from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") django.setup() application = get_default_application() myProject.routing from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from myApp.consumers import PracticeConsumer from django.urls import path application = ProtocolTypeRouter( { "websocket": AllowedHostsOriginValidator( URLRouter([path("five/", PracticeConsumer())]) ) } ) myProject.settings (relevant parts) ASGI_APPLICATION = "myProject.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } WSGI_APPLICATION = "myProject.wsgi.application" INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "storages", "channels", "myApp", ] ALLOWED_HOSTS = ["*"] myApp.consumers import asyncio from channels.generic.websocket import AsyncWebsocketConsumer class PracticeConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): # Handle received WebSocket message here await self.send(text_data=text_data) let me know if there is anything … -
How to serialize the many-to-many fields in DRF?
I have three tables in models.py: class literature_info(models.Model): pmid = models.CharField(primary_key=True,max_length=25) publication = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.pmid class dataset_info(models.Model): dataset_id = models.CharField(primary_key=True,max_length=25) literature = models.ManyToManyField(literature_info, through='literature_dataset', blank=True) def __str__(self): return self.dataset_id class literature_dataset(models.Model): literature_info = models.ForeignKey(literature_info, on_delete=models.CASCADE) dataset_info = models.ForeignKey(dataset_info, on_delete=models.CASCADE) When I try to access the literature id from dataset_info table, I serialize the fields like this: class literature_info_serializer(serializers.ModelSerializer): class Meta: model = literature_info fields = "__all__" class dataset_literature_serializer(serializers.ModelSerializer): literature = literature_info_serializer(many=True) class Meta: model = dataset_info fields = ('dataset_id','literature',) It works well, and i get the literature info via dataset. Now I want to get the literature's datatset from literature_info table, i try to serialize the filed like this: class dataset_info_serializer(serializers.ModelSerializer): class Meta: model = dataset_info fields = ('dataset_id',) class literature_dataset_serializer(serializers.ModelSerializer): dataset_info = dataset_info_serializer(many=True) class Meta: model = literature_info fields = ('pmid', 'dataset_info',) However, it doesn't work this time. So how can i solve this problem? -
Django POSTing from react app issue, CSFR issue
I am creating a simple Django backend, react frontend app, and am trying to get login working, however I get a couple of errors. My views function is: # @csrf_exempt def login_user(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) print(data, type(data)) print('username' in data) # return JsonResponse({'status':'success'}, safe=False) if 'username' not in data or 'password' not in data: return JsonResponse({'status':'error'}, safe=False) # print(data.username) username = data['username'] password = data['password'] print(username, password) user=authenticate(request, username=username, password=password) if user is not None: login(request, user) print('yay') return JsonResponse({'status':'success'}) My settings are: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS=True # CSRF_COOKIE_SECURE = False # CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] # CSRF_TRUSTED_ORIGINS = ['http://localhost:3000'] The frontend: const login_link = 'http://127.0.0.1:8000/logint' const login_link2 = 'http://127.0.0.1:8000' const handleSubmit = async (event) => { event.preventDefault(); // console.log(event) // console.log(event.nativeEvent.target) const data = await axios.post(login_link, {username:username, password:password}); // var csrf = document.querySelector('meta[name="csrf-token"]').content; // // var csrftoken = getCookie('csrftoken'); // var headers = new Headers(); // var payload = {username:username, password:password} // headers.append('X-CSRFToken', csrf); // const data = await fetch('/api/upload', { // method: 'POST', // body: payload, // headers: headers, // credentials: 'include' // }) console.log(data) } The current error is: Forbidden (Origin checking failed - http://localhost:3000 … -
The script launched by the apscheduler does not update the sqlite3 database on the server, but everything works ok on the localhost
I have a django application in which apschaduler periodically runs scripts that receive data from several emails and insert it into the sqlite3 database. When I run the project on localhost, everything is OK, but when I run it on the server, only the update_db_html function works. The scheduler runs update_db_sbd and update_db_gonets scripts, mail is read, but the database is not updated. What could be the problem? Sorry if this is a dumb question. Functions that update the database import csv import requests from bs4 import BeautifulSoup from .models import * from .parse_email import * def update_db_sbd(): imap_data = iridium_sbd_email("imap.mail.ru", "test.marlin-yug@mail.ru", "...") msg_list_bin = imap_data[0] IMEI_list = imap_data[1] data_list = zip(msg_list_bin, IMEI_list) for data in data_list: if data[1] in ('300234069704440', '300234069704480', '300234069705500'): data_format = 'IceBTC' Table = TableIceBTC elif data[1] == '300234069701970': data_format = 'IceBTC11' Table = TableIceBTC11 elif data[1] == '300234069704960': data_format = 'IceST' Table = TableIceST else: data_format = 'permafrost-32T' Table = TablePermafrost table_data = {} with open(f"tables/formats/{data_format}.csv") as f: reader = csv.reader(f) for row in reader: if 'GNSS' in row[0]: row[0] = row[0][4:] table_data[row[0]] = parse2float(data[0], int(row[1]), int(row[2]), float(row[3]), float(row[4])) try: table_data['mdatetime'] = datetime.strptime(f'{int(table_data["Year"])} {int(table_data["Month"])} ' f'{int(table_data["Day"])} {int(table_data["Hour"])} ' f'{int(table_data["Minute"])} {int(table_data["Second"])}', '%Y %m %d %H %M … -
ReactDOM not rendering in Django template
I am trying to integrate a React frontend into my Django project. I'm using Babel (ver 7.22) and webpack to bundle everything into index-bundle.js Currently, the index-bundle.js file is being fetched (according to the GET requests in terminal), but nothing is being loaded into the actual Django template. When I inspect the page, there is nothing from the js file being loaded. Everything was working until I tried adding in react components, but now nothing is working at all. File structure: -myproject --frontend ---index.js ---App.js --static ---css ---js ---index-bundle.js --templates my idex.js is literally just ReactDOM.render(<h1>help</h1>, document.getElementById("root")) I've already ensured that the template is loading the index-bundle.js file and has <div id="root"></div> -
Django unable to load css and icons from nextjs project
The problem: django is unable to load css, svgs and other files from nextjs project here is the error: Not Found: /_next/static/css/app/layout.css Not Found: /vercel.svg [28/Jul/2023 16:31:55] "GET /_next/static/css/app/layout.css?v=1690542114858 HTTP/1.1" 404 2541 Not Found: /_next/static/css/app/page.css [28/Jul/2023 16:31:55] "GET /vercel.svg HTTP/1.1" 404 2462 [28/Jul/2023 16:31:55] "GET /_next/static/css/app/page.css?v=1690542114859 HTTP/1.1" 404 2535 Not Found: /_next/static/chunks/main-app.js [28/Jul/2023 16:31:55] "GET /_next/static/chunks/main-app.js HTTP/1.1" 404 2525 Not Found: /next.svg Not Found: /_next/static/chunks/webpack.js [28/Jul/2023 16:31:55] "GET /next.svg HTTP/1.1" 404 2456 [28/Jul/2023 16:31:55] "GET /_next/static/chunks/webpack.js HTTP/1.1" 404 2522 Not Found: /_next/static/chunks/webpack.js [28/Jul/2023 16:32:21] "GET /_next/static/chunks/webpack.js HTTP/1.1" 404 2522 So, i was trying to integrate django with nextjs, and after trying everything i could, there is one problem remaining. django being unable to load css, svgs and other files from nextjs project. here's the code: project.urls.py """ URL configuration for django_with_nextjs project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a … -
Where is my blocking code? I do not receive WebSocket message - Django Channels
So I have setup a simple web app with Django Channels, that handles some WebSocket connections. It works almost perfect, however it does not receive messages, after I send messages initiated by another connection. This is my consumers: class CPConsumer(AsyncWebsocketConsumer): async def connect(self): self.cp_id = self.scope["url_route"]["kwargs"]["cp_id"] self.cp = charge_point(self.cp_id, self) await self.channel_layer.group_add(self.cp_id, self.channel_name) await self.accept() async def disconnect(self, _): await self.channel_layer.group_discard(self.cp_id, self.channel_name) async def receive(self, text_data): print(f"CP {self.cp_id} sent: {text_data}") await self.cp.route_message(text_data) async def get_config(self, _): print(f"CP {self.cp_id} updates firmware") await self.cp.call(call.GetConfigurationPayload()) print(f"CP {self.cp_id} sent response") class CPUserConsumer(AsyncWebsocketConsumer): async def connect(self): self.cp_id = self.scope["url_route"]["kwargs"]["cp_id"] await self.accept() async def disconnect(self, _): pass async def receive(self, text_data): print(f"User {self.cp_id} sent: {text_data}") await self.channel_layer.group_send(self.cp_id, {"type": "get.config"}) The CPConsumer isolated works perfect. It receives the messages, and routes them through the charge_point class. The charge_point object returns a message (it calls the consumers send method), and it is received by the client. So far so good. Now I want the CPUserConsumer to initiate a message to the connection in the CPConsumer. The charge_point object needs to handle sending that messages. So when the CPUserConsumer client sends a message, I can se that it is forward to the get_config method in the CPConsumer. The first … -
FullResultSet error during migration with mssql (sql server)
I am trying to connect a SQL Server database with Django. But when I do "migration", I have this error : File "...\Python311\Lib\site-packages\django\db\models\sql\where.py", line 174, in as_sql raise FullResultSet django.core.exceptions.FullResultSet My tables are created in database but when I want to do another migration or make migration, I have this error. I am using pyodbc and mssql-django packages settings.py : DATABASES = { 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_HEALTH_CHECKS': False, 'CONN_MAX_AGE': 0, 'ENGINE': 'sql_server.pyodbc', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***', 'PORT': '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', "setdecoding": [ {"sqltype": pyodbc.SQL_CHAR, "encoding": 'utf-8'}, {"sqltype": pyodbc.SQL_WCHAR, "encoding": 'utf-8'}], "setencoding": [ {"encoding": "utf-8"}], }, 'TIME_ZONE': None, } When I drop django.migrations table in the database, I no longer have the error for 'makemigration' but there is the "table already exists" error. This recreates the 'django.migrations' table and the error appears again. -
TemplateDoesNotExist at /post/3
I have a template that should show the details of a post when you request it, but when you request it, there is a TemplateDoesNotExist error in /post/3. It shows me, but the rest of the templates are working correctly except for this one I feel that somewhere I should have used ., but instead I used / or vice versa models.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField(Category) title = models.CharField(max_length=100) body = models.TextField() img = models.ImageField(upload_to='img/post') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.title} - {self.body[:30]}..." urls.py: from django.urls import path from . import views urlpatterns = [ path('post/<int:pk>', views.detalis, name='post') ] urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_app.urls')), path('',include('account.urls')), path('',include('blog.urls')), ] urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_URL) views.py: from django.shortcuts import render from .models import Post def detalis(request, pk): post = Post.objects.get(id=pk) return render(request, 'blog/post-detalis.html', {'post': post}) setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], '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', ], … -
Django: GET request is working correctly, but sending the data in the POST request is not working
I sent a POST to this url http://127.0.0.1:8000/user_ques_management/add_favorite_question/ again with this JSON body: { "idname": "aallen", "question_id": 201 } Got response: { "error": "User not found." } And also got this in the terminal: Received POST data: <QueryDict: {}> Received idname: None Not Found: /user_ques_management/add_favorite_question/ But when I sent a GET request with the same users user id to this url http://127.0.0.1:8000/user_ques_management/favorite_read_questions/3486/: I got successful response: { "user_id": 3486, "display_name": "Dustin Rodriguez", "favorite_questions": [], "read_questions": [] } I see the user information is there in the Database too. Here is my model for UserProfile: class UserProfile(models.Model): idname = models.CharField(max_length=250, unique=True) display_name = models.CharField(max_length=250) email = models.EmailField() phone = models.CharField(max_length=20) def __str__(self): return self.display_name Views.py for both of the urls: View to Insert Favorite Question for a User @csrf_exempt def add_favorite_question(request): if request.method == 'POST': print("Received POST data:", request.POST) idname = request.POST.get('idname') # Use 'idname' instead of 'user_id' question_id = request.POST.get('question_id') print("Received idname:", idname) # Print the received idname try: user = UserProfile.objects.get(idname=idname) question = Question.objects.get(id=question_id) FavoriteQuestion.objects.create(user_id=user, question_id=question) return JsonResponse({'message': 'Favorite question added successfully.'}) except UserProfile.DoesNotExist: return JsonResponse({'error': 'User not found.'}, status=404) except Question.DoesNotExist: return JsonResponse({'error': 'Question not found.'}, status=404) View to Retrieve Favorite and Read Questions for a User def … -
How add to ajax request additional GET params in django-ajax-select?
I need sent parametr region with ajax request in select. Select sending ajax without additional parameter `@register('address') class TagsLookup(LookupChannel): model = Address def get_query(self, q, request): **region = request.GET.get('region')** region_null = '__'.join([region, 'isnull']) return list(self.model.objects .filter(**{region_null: False}) .exclude(**{f'{region}': ''}) .exclude(**{f'{region}': ' '}) .order_by(f'{region}') .values_list(f'{region}', flat=True).distinct()) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.city` Send region GET parametw with django-ajax-select request. Their documentation says the following: django-ajax-select documentation