Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem customizing search_get_results() method in Django Admin page to get Custom Search
I have an app in Django and I would like to use this template: {% load i18n static %} {% if cl.search_fields %} <div className="form-group"> <div class="search-notes col-md-6 col-sm-12">Para busqueda de terminos exactos poner el texto entre comillas Ej para editorial "VANGUARDIA PICTORICA" o en ISBN "978-959-7126-52-2"</div> </div> <div class="for-group-container row"> <div class="form-group col-md-3"> <input type="text" name="no_reg" class="form-control" placeholder="Número de Registro" /> <br> <input type="text" name="inputTitulo" class="form-control" placeholder="Título" /> <br> <br/> <input type="text" name="inputAutor" class="form-control" placeholder="Autor" /> <br/> </div> <div class="form-group col-md-3"> <input type="text" name="inputEditorial" class="form-control" placeholder="Editorial" /> <br/> <input type="text" name="inputDescriptor" class="form-control" placeholder="Descriptor" /> <br/> <div class="form-group col-md-3"> <input type="text" name="inputResumen" class="form-control" placeholder="Resumen" /> <br/> <input type="submit" value="{% translate 'Search' %}"> </div> {% if show_result_count %} <span class="small quiet">{% blocktranslate count counter=cl.result_count %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktranslate %} (<a href="?{% if cl.is_popup %}{{ is_popup_var }}=1{% endif %}">{% if cl.show_full_result_count %}{% blocktranslate with full_result_count=cl.full_result_count %}{{ full_result_count }} total{% endblocktranslate %}{% else %}{% translate "Show all" %}{% endif %}</a>)</span> {% endif %} {% for pair in cl.params.items %} {% if pair.0 != search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}">{% endif %} {% endfor %} </div> {% if cl.search_help_text %} <br class="clear"> <div class="help" id="searchbar_helptext">{{ … -
Django/Python - How to assign a file path variable in a platform-independent way?
I have a Django project where one of the .env file variables is going to represent an absolute file path. E.g., DEBUG=True SECRET_KEY='blah_blah_blah' MY_STORAGE_PATH = 'D:\\files\\for\\my\\project' Obviously the above would work fine on a Windows machine with a D: drive, but it's no good if there's no D: drive or if the machine is using some other OS. Now I can think of any number of functioning ways to supply this .env string in a platform-independent way, and then use string manipulation and the os.path methods to assemble the actual path. I could break out the drive & path separately, using a 'neutral' path separator of my own choosing: MY_STORAGE_DRIVE_FOR_WIN = 'D:' MY_STORAGE_PATH = '|files|for|my|project' ...I could supply the configuration formatted as a list, convert it to a real list, then feed into os.path.join(): MY_STORAGE_PATH_ELEMENTS = '["files","for","my","project"]' ...and so on, and so on. But before I go roll my own that way, I wanted to know: is there some accepted convention for this kind of use case? (Surely this isn't the first time someone needed to provide an .env value to represent a platform-independent path?) -
Why is my schema execution timing out in python graphene?
I'm using graphene. I was using version 2.1.9. I'm now using version 3.3. This code has not been changed since the upgrade, I'm going to outline the relevant code and then explain the problem further build_schema: neither Query or Mutation are None so this will return graphene.Schema(query=Query, mutation=Mutation) @logf(level='debug') def build_schema(*args, **kwargs) -> graphene.Schema: """Builds the Query and Mutation classes for the given schema name and adds them a schema and returns the schema """ Query, Mutation = None, None qclasses, qprops = _build_props('queries', *args, **kwargs) if qclasses: Query = type('Query', qclasses, qprops) mclasses, mprops = _build_props('mutations', *args, **kwargs) if mclasses: Mutation = type('Mutation', mclasses, mprops) if Query is None and Mutation is None: raise ValueError('No Query or Mutation classes found') elif Query is None: gqlschema = graphene.Schema(mutation=Mutation) elif Mutation is None: gqlschema = graphene.Schema(query=Query) else: gqlschema = graphene.Schema(query=Query, mutation=Mutation) return gqlschema This is the test case that fails, it's not verbose about why it failed, it just hangs for 60 seconds and then says that it timed out def _mock_user(user='test', **kwargs): return MagicMock(username=user, **kwargs) def _mock_info(**kwargs): infomock = MagicMock() infomock.context.user = _mock_user(**kwargs) return infomock class TestSignUrlQuery(TestCase): def setUp(self): self.query = ''' query { signedUrl( gcsUrl: "bucket/path/to/file", method: "PUT", contentType: … -
Django Database Routers "allow_migrate_model" throws the following: "TypeError: allow_migrate() missing 1 required positional argument: 'app_label'"
the "allow_migrate_model" function within my database routers keeps throw the following error when I try to run python manage.py makemigrations: ... File "C:\Users\...\lib\site-packages\django\db\utils.py", line 262, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() missing 1 required positional argument: 'app_label' My Routers look like this: class BaseRouter: route_app_labels = {} db_name = "" def db_for_read(self, model, **hints) -> Union[str, None]: if model._meta.app_label in self.route_app_labels: return self.db_name return None def db_for_write(self, model, **hints) -> Union[str, None]: if model._meta.app_label in self.route_app_labels: return self.db_name return None def allow_relation(self, obj1, obj2, **hints) -> Union[bool, None]: if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate( self, db, app_label, model_name=None, **hints ) -> Union[bool, None]: if app_label in self.route_app_labels: return db == self.db_name return None class DefaultRouter(BaseRouter): route_app_labels = {"auth", "contenttypes", "sessions", "admin", "myapp"} db_name = "default" class LibraryRouter(BaseRouter): """ separate router for backend stuff """ route_app_labels = {"library"} db_name = "library" The above is basically a slightly modified version found on the Django Docs. If I comment out the allow_migrate the makemigrations works, however, I would like to modify the allow_migrate further so that's not a convincing option rn. Ah also for some reason if a rewrite it … -
Google api, self project
I am trying to create a website using the google, place api and geocoding api, I'm am new to using Django as my backend. My get requests work, however i receive a 404 error saying pro access only. I have a pro account for the api, and on the api website it says these are enabled. Any help would be greatly appreciated. To be able to have users input a city (ex. Orlando And receive a list of bars in a radius within the city searched.) `This is my current view.py (omitted my api key and secret key for security but I have them defined in the beginning import requests from django.http import JsonResponse import hmac import hashlib import base64 def get_random_drink(request): try: url = 'https://www.thecocktaildb.com/api/json/v1/1/random.php' response = requests.get(url) response.raise_for_status() drink_data = response.json() return JsonResponse(drink_data) except requests.exceptions.RequestException as e: print(f"Error fetching random drink: {e}") return JsonResponse({'error': 'Failed to fetch random drink'}, status=500) def generate_signature(endpoint): string_to_sign = f"{API_KEY}{endpoint}" signature = hmac.new(SECRET.encode(), string_to_sign.encode(), hashlib.sha256) return base64.b64encode(signature.digest()).decode() def search_nearby_bars(request, city): try: location_data = get_city_coordinates(city) if not location_data: return JsonResponse({'error': 'City not found'}, status=404) lat, lng = location_data radius = 5000 # Set the radius for the nearby search in meters # Prepare the … -
Websocket Connection failing on Deployed Azure web app
I am running a nodeJs server, and serving a ReactApp from it. This is deployed and hosted in an Azure WebApp. I have container running a Django server, hosted on a separate Azure WebApp. I am trying to open a WebSocket connection from my React app directly to my Django server. I have tested this locally by deploying my Django app to azure, and then building my NodeJs & ReactApp LOCALLY and opening the wss:// connection and it works on my machine. But the after deploying the Node/React application to Azure the websocket connection fails with errorcode: 1006 I'm not sure what information settings would give more assistance in solving the issue. I'm completely new to WebSockets as a whole. I'm hoping it's something to do with headers or protocols being stripped/changed as mentioned at the end of this article. But I cannot see anything in my Azure app configuration. I can provide any further information (code or Azure configuration), I just don't know exactly what would help troubleshoot. (My WS connection code, just for transparency) export const awaitWsPing = () => { const socket = new WebSocket('wss://myDjangoApp.azurewebsites.net/my/ws/url'); socket.onmessage = (e) => { const data = JSON.parse(e.data); console.log({data}); notificationContext.setMessage('Received ping … -
How to get authorized in Microsoft AD using curl?
I have a django project which uses Azure Active directory for the authentication and I have set up its API using rest_framework. At the moment, I am trying to access this API using curl. I am able to generate an access token, but when I send a request using it, I get the Microsoft Login Page, as if I do not have any access token. I generated an access token using the following code: curl -X POST https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token -H "Content-Type: application/x-www-form-urlencoded" -d "client_id={client_id}" -d "client_secret={client_secret}" -d "grant_type=client_credentials" -d "redirect_uri=https://{my_domain}/oauth2/callback" -d "scope=api://{tenant_id}/.default openid profile email" Then, using the jwt token that I recieved, I did: curl -X GET -L https://<my_domain>/api/benches/1/status/ -H "Authorization: Bearer <token>" And what I get, is the Microsoft login page, which its first few lines look like this: <!-- Copyright (C) Microsoft Corporation. All rights reserved. --> <!DOCTYPE html> <html dir="ltr" class="" lang="en"> <head> <title>Sign in to your account</title> . . . Also, the result of the -v (verbose) looks like this: Note: Unnecessary use of -X or --request, GET is already inferred. * Host <my_domain>:443 was resolved. * IPv6: (none) * IPv4: ip * Trying ip:443... * Connected to <my_domain> (ip) port 443 * schannel: disabled automatic … -
AWS: How to let a S3 frontend (React, Axios) communicate with an EC2 backend (python3/Django, DjangoREST, corsheaders)
I followed a tutorial for creating a basic To-Do app (so CRUD) with a React+Axios frontend (ServiceWorker, bootstrap) and Django backend (DjangoREST, corsheaders), and would like to put it on AWS's free tier for job-finding purposes. I got the app running fine locally using localhost, and even able to get the server running on EC2 and the frontend hosted on S3 using various other tutorials. Now i'm stuck on how to get them to communicate without them being on the same machine. I had hoped I could just change some lines relating to localhost to their IP's and Ports, but that hasn't worked. Since this is a fairly simple example program I tried to keep security to a minimum throughout setup to help communications, and have allowed HTTP and HTTPS and anything I could * in my security settings. In settings.py I have: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_WHITELIST = ['http://frontend-IP:3000'] and in my frontend package.json I have: "proxy": "http://backend-IP:80", to tunnel the API to the backend so my axios commands look like: axios .get("/api/todos/") Rather than the whole address. I also am not sure how to make React use something other than localhost:3000 or if i need to change that if … -
How to render Markdownx content as HTML in a Django blog project?
I did all the installation of markdownx steps as stated. I've installed the django-markdownx package using pip install django-markdownx. I've added 'markdownx' to my INSTALLED_APPS in settings.py. I've defined a MarkdownxField in my blog post model to store the Markdown content. but my problem is I'm unsure about the correct template tag usage to render the Markdown content as HTML. this is my models.py: from django.db import models from markdownx.models import MarkdownxField class Article(models.Model): title = models.CharField(max_length=200) content = MarkdownxField() def __str__(self): this is my viwes.py: from .models import Article def post_list(request): articles = Article.objects.all() return render(request, 'blog/post_list.html', {'articles': articles}) this is my admins.py: from django.contrib import admin from .models import Article from markdownx.admin import MarkdownxModelAdmin admin.site.register(Article, MarkdownxModelAdmin) this is my urls.py of project(not app): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('markdownx/', include('markdownx.urls')), path('', include("blog.urls")), ] in the admin it shows the preview correctly but I used many tags to convert the markdownx to html but I'm not successfull. I used: {% for article in articles %} <article> <h1>{{ article.title }}</h1> <div>{{ article.content|markdown|safe }}</div> </article> {% endfor %} but I got TemplateSyntaxError. I used: {% for article in articles %} <article> <h1>{{ … -
Where to write validation in django?
Any one can you suggest me about which is the best practise to write the validation in django project. Writing validation in serializer is better or in models is better. I have try both for writing validation but still I am unable to choose where to write validation is more better. Can any one suggest me ? If you guys have a experience of working in real world project then also share where you have written this validation. -
Django - Cannot make a celery worker and test transactions on test file without "You can't execute queries until the end of the 'atomic' block." error
Soo, here's the deal, Im creating a test in order to check if an improvement a made for performance is working or not, the improvements consists in making some signals logic an async task instead of an async process, I wanted to test this out but when I manually create a celery worker I get the django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. To have more context.. I'm avoiding creating a worker from the start because the pipeline does not use redis by default, or at least it avoids the celery creation, so I need to make one manually, but when I create the service I get the error def test_delete_optimal_deletion_time(self): """ Verifies that the `deletion logic` is under an acceptable running time. :return: """ # ... non-relevant code # Start Celery worker in a separate context to avoid nested atomic transactions with start_worker(celery_app, perform_ping_check=False): data_delete_start = time.time() og_org.delete() data_delete_end = time.time() data_total_test_end = time.time() data_total_test_time = data_total_test_end - data_total_test_start data_delete_time = data_delete_end - data_delete_start print("time to create test data: ", data_creation_time) print("time to delete test data: ", data_delete_time) print("time to run all test data: ", data_total_test_time) print("settings.CELERY_TASK_ALWAYS_EAGER: … -
How to test Django models against a DB without manage.py in a standalone package using pytest and GitHub Actions?
Context: I am developing a standalone Django package that is intended to be added to existing Django projects. This package includes Django models with methods that interact directly with a database. I want to write tests for these methods using pytest and pytest-django. I need to run these tests in a CI/CD environment, specifically using GitHub Actions. Problems Encountered: Database Setup: Since this is a standalone package, it does not include a manage.py file. This makes it challenging to run typical Django management commands like migrate to set up the database schema for testing. Table Creation: I encounter errors indicating that the table for my model does not exist because the necessary migrations are not applied. This is problematic because my tests need to interact with the database tables directly. Fixtures and Setup: I need to ensure the database tables are created and populated with initial data before the tests run. My attempts to use pytest fixtures and manually create database tables within the tests have not been successful. What I've Tried: Using pytest fixtures to set up the initial database state. Manually creating database tables within the test setup using direct SQL execution. Using the mixer library to populate … -
How do fetch the real time latitude and longitude in Django and display that as a tracking map in the template? [closed]
I want to fetch the real time latitude and longitude from the Kotlin. I just want to display the real time latitude and longitude as a map in a template by using a Django frame work how do I do this? can anyone solve this? -
getting errors with django templates
I am practicing Django lately and i get this error, can someone assist Invalid block tag on line 17: 'else', expected 'endblock'. Did you forget to register or load this tag? The template {% extends 'base.html' %} {% block content %} {% if not request.user.is_authenticated %} <div> <form method="POST"> {% csrf_token %} {% if error %} <span style="color: red">{{ error }}</span> {% endif %} <div> <input type="text" name="username" placeholder="username" /> </div> <div> <input type="password" name="password" placeholder="password" /> </div> <button type="submit">Login</button> </form> </div> {% else %} <div> <span style="color: red"> Already logged in. Would you like to <a href="/logout">logout?</a> </span> </div> {% endif %} {% endblock %} Everything corrrectly set -
Django Internationalization test error:Couldn't retrieve redirection page
I wrote a blog project in Django,in some pages i used loginrequierdmixin to make sure user is loged in but in test i got error in testing my project test: def test_get_profile_unauthenticated(self): response = self.client.get(self.profile_url) self.assertEqual(response.status_code, 302) expected_url = f"{self.register_url}?next={self.profile_url}" self.assertRedirects(response, expected_url) AssertionError: 302 != 200 : Couldn't retrieve redirection page '/accounts/register/': response code was 302 (expected 200) i print response: <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/register/?next=/en/accounts/profile/1/"> and my exepted url: /en/accounts/register/?next=/en/accounts/profile/1/ i asked chatGPT and here is response: def test_get_profile_unauthenticated(self): self.client.cookies.clear() with translation.override('en'): response = self.client.get(self.profile_url, HTTP_ACCEPT_LANGUAGE='en') self.assertEqual(response.status_code, 302) expected_url = f"{self.register_url}?next={self.profile_url}" self.assertRedirects(response, expected_url) -
When using the command docker-compose exec web python core/manage.py makemigration accountss I see the error "No module named 'accounts"
When using the command docker-compose exec web python core/manage.py makemigration accountss I see the error ModuleNotFoundError: No module named 'accounts' INSTALLED_APPS: enter image description here The error that is observed: Traceback (most recent call last): File "/code/core/manage.py", line 22, in <module> main() File "/code/core/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1310, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named 'accounts' when makemigrations, I saw the above error -
Ajax is not working without refreshing the page
Ajax is not working without refreshig the page to make it work.I am coding an ecommerce website in django and need to show quantity of products in the cart but it dont show quantity without refresh the page. <script> $(document).on("click", "#add_button", function (e) { e.preventDefault(); $.ajax({ type: "POST", url: "{% url "add_cart" %}", data: { product_id: $("#add_button").val(), csrfmiddlewaretoken: "{{ csrf_token }}", action: "post", }, success: function (json) { {#console.log(json)#} document.getElementById("cart_quantity").textContent = json.qty }, error: function (xhr, errmsg, err) { } }); }) </script> class Cart: def __init__(self, request): self.session = request.session cart = self.session.get("cart_key") if cart is None: cart = self.session["cart_key"] = {} self.cart = cart def add(self, product): product_id = str(product.id) if product_id in self.cart: pass else: self.cart[product_id] = {"Price: ": str(product.price)} self.session.modified = True def __len__(self): return len(self.cart) def add_cart(request): cart = Cart(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("product_id")) product = get_object_or_404(Product, id=product_id) cart.add(product=product) cart_quantity = cart.__len__() # response = JsonResponse({"product name: ": product.name}) response = JsonResponse({"qty: ": cart_quantity}) return response <p id="cart_quantity" >{{ cart|length }}</p> -
how can i dockerize my project with two app in seprate services
how can i dockerize my django project So that run two apps run in two diffrent services and one run with port:8000 and other one run with port:8001 sorry for my englisgh lol!! i tried making two dockerfile in each app # Use an official Python runtime as a parent image FROM python:3.8-slim # Set the working directory WORKDIR /usr/src/app # Copy the requirements file into the container COPY app1/requirements.txt ./ # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of the application code COPY app1/ . # Run the application CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and for app2 # Use an official Python runtime as a parent image FROM python:3.8-slim # Set the working directory WORKDIR /usr/src/app # Copy the requirements file into the container COPY app2/requirements.txt ./ # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of the application code COPY app2/ . # Run the application CMD ["python", "manage.py", "runserver", "0.0.0.0:8001"] and one docker-compose.yml in root of project version: '3.8' services: app1: build: context: . dockerfile: app1/Dockerfile volumes: - ./app1:/usr/src/app ports: - "8000:8000" environment: - DJANGO_SETTINGS_MODULE=myproject.settings app2: build: context: … -
django-rest-framework-datatables server side FieldError: Cannot resolve keyword '0' into field
I am getting this error: django.core.exceptions.FieldError: Cannot resolve keyword '0' into field. Choices are: adjustmentsheader, authusergroups, authuseruserpermissions, brand, brand_modified_by_set, brandcategory, brandcategory_modified_by_set, company, company_modified_by_set, customer, customer_modified_by_set, customerbranch, customerbranch_modified_by_set, customerproduct, customerproduct_modified_by_set, customertype, customertype_modified_by_set, damageheader, date_joined, djangoadminlog, drfheader, drfheader_approved_by_set, drfheader_cancelled_by_set, drfheader_modified_by_set, email, first_name, id, is_active, is_staff, is_superuser, last_login, last_name, password, product, product_modified_by_set, productsupplier, productsupplier_modified_by_set, pulloutheader, pulloutheader_approved_by_set, receivingheader, receivingheader_modified_by_set, supplier, supplier_modified_by_set, username But I dont have a keyword '0' in my code: models.py class AuthUser(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) serializers.py: class UsersSerializer(serializers.ModelSerializer): class Meta: model = models.AuthUser fields = ('first_name', 'last_name', 'email') urls.py router = routers.DefaultRouter() router.register(r'user_viewset', views.UsersViewSet) urlpatterns = [ path('api/', include(router.urls)), views.py class UsersViewSet(viewsets.ModelViewSet): queryset = models.AuthUser.objects.all().order_by("last_name") serializer_class = serializers.UsersSerializer template: <div class="table-responsive-xl"> <table class="table table-hover table-striped table-sm" id="table1"> <thead class="sticky-top top-0"> <tr> <th>Item Code</th> <th>Customer Barcode</th> <th>Brand</th> <th>Category</th> <th>Description</th> <th>Customer Price</th> </tr> </thead> </table> </div> </div> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="//cdn.datatables.net/2.0.8/js/dataTables.min.js"></script> <script> $(document).ready(function () { $('#table1').DataTable({ "serverSide": true, "ajax": "../api/product_viewset/?format=datatables" }); }); </script> I dont have a keyword '0' in my model or database. Where could it be coming from? -
WebSocket Channels in Django not connecting
I'm struggling why still insist not being connected my WebSocket using Django, I've used laragon as Mysql and I just used my local database, and I just want to try first before saving to database it if it works or not but I getting an error. Did I forgot something? so I have this format and I have error in my html url on line const chatSocket = new WebSocket(url) html $(document).ready(function () { let url = `ws://${window.location.host}/ws/socket-server/` const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) console.log('Data:', data) if(data.type === 'chat'){ let messages = document.getElementById('messages') messages.insertAdjacentHTML('beforeend', `<div> <p>${data.message}</p></div>`) } } }); main/routing.py from django.urls import re_path from main import consumers websocket_urlpatterns = [ re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi()) ] main/consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':message } ) def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps({ 'type':'chat', 'message':message })) tev/asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import main.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tev.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application(), 'websocket':AuthMiddlewareStack( URLRouter( main.routing.websocket_urlpatterns ) ) }) settings.py … -
Django why is my image refusing to upload
For my website- I implemented a profile pic you can add to your profile which works: models.py class Profileuser(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) tagline = models.CharField(max_length=100) bio = models.TextField(blank=True) website = models.URLField(blank=True) profile_pic = models.ImageField(upload_to="profiles/", blank=True) def __str__(self): return f"{self.id} | {self.name}" views.py class ProfileuserCreateView(LoginRequiredMixin, CreateView): model = Profileuser fields = ['name', 'profile_pic', 'tagline', 'bio', 'website'] success_url = reverse_lazy('recipes-home') def form_valid(self, form): form.instance.owner = self.request.user return super(ProfileuserCreateView, self).form_valid(form) Urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) However- when I tried to implement adding photos to my recipe posts- the images just don't upload, I can see the folder sitting empty models.py class Recipe(models.Model): title = models.CharField(max_length=100) recipe_image = models.ImageField(upload_to="imagerecipes/", blank=True) ingredients = models.TextField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return self.title views.py class RecipeCreateView(LoginRequiredMixin, CreateView): model = models.Recipe fields = ['title', 'recipe_image', 'ingredients', 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I don't understand why one works but the other doesn't as the code is virtually the same- if I upload via admin- it does work, I have also tested profile pictures and it still allows me to upload them. No error … -
How to Avoid Duplicate Validation When Creating Django Model Instances Manually and via Forms?
I’m new to Django and I need some help with model validation. Here’s what I’m trying to figure out: When I create new instances using forms, I know that calling is_valid on the form automatically runs the full_clean method for validation. After that, I just call save on the form. But when I create new instances manually, I need to call full_clean manually before calling save. I saw online that some people suggest overriding the save method in the model to ensure custom validation always runs, like this: def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) This works fine when I’m creating instances manually, but it seems to call full_clean twice when I use forms (once during is_valid and once during save). This feels redundant and probably not efficient. My Question: What’s the best way to make sure my custom validation runs in Django models both when creating instances manually and via forms, without calling full_clean twice? Any advice or best practices would be really appreciated! Thanks a lot! -
python django library project
i have been making libraries with many tutorials and tips but couldnt find one that really suited my project can anybody give me suggestions on it i would really apreciate where to find some proper tutorials that can show me how to make an python django library that allows me to have two roles vendor and librarian, vendor sells books can edit the names of the books and basic things like that and librarian can search up the books and find the one he/she will like well i have tried multiple tutorials which did pretty well but not up to the level i need for -
Problem connecting to BlueStacks from the Django project using ADB
1. Creating a Django project: 2. Preparation of forms (models.py): enter image description here 3. Preparation of presentations (views.py): enter image description here enter image description here enter image description here 4. Set up templates (templates/bot_controller.html): enter image description here ADB settings: adb connect 127.0.0.1:5555 adb devices CSP CORS settings.py: enter image description here The full project link: https://github.com/MoYonsei/AbotZ/tree/master Attempts to solve the problem: Made sure that ADB is working properly and BlueStacks is connected. Updated the CSP and CORS settings to allow loading the emulator inside the framework. Tried using different addresses in the iframe such as localhost and 127.0.0.1. -
Why is my AWS EC2 instance Supervisor failing?
I'm deploying a Django API I've named "ScientistBirthYear" to AWS EC2 following these instructions, including using the gunicorn.conf code, but modifying it to account for my virtual environment's name, project name, and X.wsgi:application from my project. At 24:50, the presenter's instance shows gunicorn running, where mine has failed multiple times. I've come across several solutions online, and none of them have worked. Here's the last several entries of my /var/log/supervisor/supervisord.log: 2024-07-16 22:56:07,174 INFO spawned: 'gunicorn' with pid 1861 2024-07-16 22:56:07,281 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:09,284 INFO spawned: 'gunicorn' with pid 1866 2024-07-16 22:56:09,391 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:12,396 INFO spawned: 'gunicorn' with pid 1871 2024-07-16 22:56:12,502 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:12,503 INFO gave up: gunicorn entered FATAL state, too many start retries too quickly 2024-07-16 22:56:25,588 CRIT Supervisor is running as root. Privileges were not dropped because no user is specified in the config file. If you intend to run as root, you can set user=root in the config file to avoid this message.> 2024-07-16 22:56:25,589 INFO Included extra file "/etc/supervisor/conf.d/gunicorn.conf" during parsing 2024-07-16 22:56:25,589 INFO RPC interface 'supervisor' initialized 2024-07-16 22:56:25,589 CRIT Server 'unix_http_server' …