Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django edit_post view not prepopulating form fields with existing data
I'm developing a Django blog application and I have a view to edit a post. However, when I click the Edit button, the form fields do not appear prepopulated with the existing data. Here's my edit_post view code: def edit_post(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect("main_page") else: form = PostForm(instance=post) context_dict = { "form": form, "post": post, } return render(request, "blog/edit_post.html", context_dict) I have verified that the PostForm is correctly configured with the required fields from the Post model. I also tried using the @never_cache decorator, but it didn't resolve the issue. I'm not sure why the form fields are not prepopulated with the existing data after submitting the form. It only works when I manually reload the page. Any suggestions or insights on how to fix this issue would be greatly appreciated. -
Deadlock with Django and MYSQL
I am getting some deadlocks in my project where I have multiple processes altering the same objects in the database. I have an endpoint whose point is to fetch the most recent unfinished play and then proceed to alter it if one exists, if not then it should create one. I need to make sure that if I receive 2 concurrent requests in this endpoint one of them creates the object and the other one blocks execution until that one is created and then the second one will alter the object created. In my django application I have the following query for that inside transaction.atomic() context: # Use list to force evaluation play = list(Play.objects.select_for_update().filter( game=self.game, user=self.user, discard=False, finished=False, ) ) It used to be .last() but I read that the ORDER BY it performs in the database query would sometimes raise problems with deadlocks so I tried this instead. From my understanding (which is probably flawed) MYSQL should acquire an exclusive record lock on the finished index (I have that as index in my database) which would not allow for an object to be created while this transaction is occurring and any transaction that tries to would be blocked … -
Django WSGI: no module named 'my_app.settings'
I've looked carefully through all similar questions on stackoverflow but found no working solution. I have a problem running wsgi.py file due to the ModuleNotFoundError: No module named 'magic_orb.settings' (I'm creating a magic orb with predictions based on AstroGPT). My wsgi.py file looks like this: import os import sys proj_path = ("../magic_orb") sys.path.append(proj_path) os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "magic_orb.settings") os.chdir(proj_path) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() As you may see, I've already tried changing the path and adding get_wsgi_application. Moreover, I've added django.setup() to the manage.py file as my main problem is with app loading. My project's structure is the following: magic_orb ├── db.sqlite3 ├── frontpage │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_frontpage.py │ │ ├── 0002_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ └── views.py ├── magic_orb │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── magic_orb_model │ ├── pretrained_model.py │ └── __pycache__ ├── manage.py └── user_data_form ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_user_data_form.py │ ├── __init__.py │ └── __pycache__ ├── models.py ├── __pycache__ ├── … -
DevTools failed to load source map: Could not load content for ..../bootstrap.min.css.map: Unexpected token '<', "<!doctype "... is not valid JSON
i am using react and django for my web app. it works fine on local machine but shows this warning on server. the file it showing in the warning was not here so i copy it from the asset folder but still not working. Permissions are given to the file -
graphene multible queries and mutation
I try to update my schema.py. This is previous code: from graphene import Schema, Field, ObjectType from .basic_objects.queries import BasicQuery from .basic_objects.mutations import BasicMutation schema = Schema(query=BasicQuery, mutation=BasicMutation) Updated code: from graphene import Schema, Field, ObjectType from .basic_objects.queries import BasicQuery from .basic_objects.mutations import BasicMutation class Query(ObjectType): BasicQuery = Field(BasicQuery) #otherQuery class Mutation(ObjectType): BasicMutation = Field(BasicMutation) schema = Schema(query=Query, mutation=Mutation) I will have many Queries and mutations so I want to handle the problem like this. But while I try to send request it look like this: query MyQuery { BasicQueryData { oneNode(id: 1) { comment coordinateY } } } from query oneNode directly working and graphene find the method and it is working. how can I make that this time from query first go to BasicQueryData and then call oneNode method? -
Why email is not shown as a Json response in django rest api
View class UserRegistrationView(APIView): def post(self, request): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() token = Token.objects.create(user=user) response_data = { 'token': token.key, 'message': 'User registration successful.' } return Response(response_data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'] ) user.set_password(validated_data['password']) user.save() return user def validate_username(self, data): if User.objects.filter(username=data).exists(): raise serializers.ValidationError("Username already exists.") return data def validate_email(self, data): if User.objects.filter(email=data).exists(): raise serializers.ValidationError("Email already exists.") return data url path('reg/',UserRegistrationView.as_view(), name='userreg' ) in my post request i got only { "username": [ "This field is required." ], "password": [ "This field is required." ] } In this serializer i passed the fields such as username password and email.. but i got only email and username as a json response why email is not showing as a json response. -
Page not found (404) django problem!What to do?
My project "mysite" has one app "polls" in it When i run my server i receive 404 error: Here is my code: mysite/settings.py INSTALLED_APPS = [ 'polls', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") polls/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] How can I fix this problem? -
Django admin request got values for both 'fields' and 'body' error when trying to save entry with CloudinaryField attribute
I am working on a Django project and suddenly I have found that when user tries to save a new entry with an image there is an exception: request got values for both 'fields' and 'body', can only specify one I am using the Django Admin in conjunction with the Cloudinary library where I am using the CloudinaryField on the specific table. In addition, I have one to many relationship between MainEntity and Picture. The Picture model holds a CloudinaryField. When I am trying to use traceback to get a detailed error I am getting another error related with database: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The problem arises when I am calling the save method manually after the overridden that I have made in Picture model: def save(self, *args, **kwargs): if not self.order: self.order = self.mainEntity.number_of_pictures() + 1 try: super(Picture, self).save(*args, **kwargs) except BaseException: traceback.print_exc() What I have found is that the exception happens in request_encode_body method that you can find in this url. Although, I cannot understand why this is happening and what causes this issue! Thank you! What I have tried in detail I have … -
How to fetch Data from Database into angular form select?
I am working on a CRUD App. I want to display values in <select> from Database table instead of specifying them in the <option>. I have manually created a country table in DataBase, I want the values from the DB to displayed as dropdown instead of <select>, <option>) I have created the webapp with frontend, DataBase (PostgreSQl) and backend (Django). Here is the Repository: GitHub app.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Tax } from './Tax'; @Injectable({ providedIn: 'root' }) export class TaxService { private url: string = 'http://localhost:8000/api/taxapp/'; constructor(private http: HttpClient) { } addTax(tax: Tax): Observable<Tax> { return this.http.post<Tax>(this.url, tax); } getTaxes(): Observable<Tax[]> { return this.http.get<Tax[]>(this.url); } getTax(id: number): Observable<Tax> { return this.http.get<Tax>(`${this.url}${id}`); } getCountry(): Observable<Tax[]> { return this.http.get<Tax[]>(this.url); // Need modification here } updateTax(id: number, tax: Tax): Observable<Tax> { return this.http.put<Tax>(`${this.url}${id}/`, tax); } deleteTax(id: number): Observable<Tax> { return this.http.delete<Tax>(`${this.url}${id}/`); } } add-tax.component.html snippet <!--Country Name--> <!-- <div class="col form-group"> <label for="taxtype" class="form-label">Country Name</label> <select class="form-select" data-style="btn-primary" formControlName="country" name="country" id="country"> <option value="India">India</option> // Old HTML Template <option value="USA">USA</option> </select> </div> --> <div class="col form-group"> <<mat-form-field appearance="fill"> <mat-label>Country Name</mat-label> <mat-select> <mat-option *ngFor="let Country of Country"> // … -
What factors should I consider choosing a web app development company for my project?
I have Cubet in mind as I search for recommendations on the right web app development company to build a web app for my company. I'm seeking suggestions related to technology, design, and user experience, particularly with a focus on Cubet's expertise and capabilities. Any advice or recommendations are highly valued and appreciated in making an informed decision I have Cubet in mind as I search for recommendations on the right web app development company to build a web app for my company. I'm seeking suggestions related to technology, design, and user experience, particularly with a focus on Cubet's expertise and capabilities. Any advice or recommendations are highly valued and appreciated in making an informed decision -
why am i not able to open the admin page before migration?
while you are creating a project and starting an app, you will run the server and get an appropriate page. and adding an /admin to the 8000 will show the admin page, but is it possible to get the admin page before migration?i tried to open the admin page by adding, /admin to the url before migrating. -
django-constance CONSTANCE_ADDITIONAL_FIELDS from model
I have User table, I need to implement the dropdown list to admin panel, where you can choose only one user. I installed django-constance, and add this code to my settings.py file: ... CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_ADDITIONAL_FIELDS = { 'users_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': ( (None, "-----"), User.objects.all().split(",")) ) }], } CONSTANCE_CONFIG = { 'DEFAULT_USER': ('', 'default user', 'users_select'), } I faced with the problem, that I couldn't use Model import in settngs.py. How can I solve this problem and use model data in Constance list? -
OpenBLAS blas_thread_init: pthread_create failed for thread 1 of 4: Operation not permitted
OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:43:00 OpenBLAS blas_thread_init: pthread_create failed for thread 2 of 4: Operation not permitted 2023-06-26 15:42:59 [2023-06-26 10:42:59 +0000] [21] [INFO] Booting worker with pid: 21 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [20] [INFO] Booting worker with pid: 20 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [19] [INFO] Booting worker with pid: 19 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [16] [INFO] Worker exiting (pid: 16) 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [15] [INFO] Worker exiting (pid: 15) 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 1 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 2 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 3 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 2 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 3 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 … -
Django api file managment
I was curios what is the best way to store api views in Django in one file or in separate, because my project is quite big. regular views i am storing in different files for managment. -
gettin this error ,TemplateSyntaxError at / Could not parse the remainder: '>=18' from '>=18'
Gettin this error, TemplateSyntaxError at / Could not parse the remainder: '>=18' from '>=18' and my code is written here, <table class="table"> <thead> <tr> <th scope="col">S.No</th> <th scope="col">Name</th> <th scope="col">Age</th> <th scope="col">Can Vote </th> </tr> </thead> <tbody> {% for people in people %} <tr> <td>{{forloop.counter}}</td> <td>{{people.name}}</td> <td>{{people.age}}</td> <td> {% if people.age >=18 %} can Vote {% else %} can't Vote {% endif %} </td> </tr> {% endfor %} </tbody> </table> I am trying to create a django project which detects yu can vote or not -
how to convert list to class 'django.db.models.query.QuerySet'
I want to use django_filter, but my datatype is list. it shows that list has no attribute model myfiler1 = Orderfilter(request.GET, queryset=mylist) I want to use django_filter, but my datatype is list. it shows that list has no attribute model myfiler1 = Orderfilter(request.GET, queryset=mylist) so how to convert my list to django.db.models.query.QuerySet -
ImportError: cannot import name 'Students' from 'django.contrib.auth.models' Django
I am currently trying out python Django version 4.2.2 to do a project for an activity, I would like to ask what seems to be the problem because whenever i run my project file in VSCode terminal I get the following errors Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "C:\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen … -
WebSocket connection to 'ws://127.0.0.1:8000/ws/wdym/' failed: dashboard.js:2
So I'm working on my personal django project to create a real-time web application using channel and websocket. But it shows this error: 'WebSocket connection to 'ws://127.0.0.1:8000/ws/wdym/' failed: dashboard.js:2' in the console and this error: 'Broken pipe from ('127.0.0.1', 50536)' from the terminal. Can you tell me what the issues are and the solution to it? Thanks! I use: python 3.10.11 channels 4.0.0 channels-redis 4.1.0 This is routing.py `from django.urls import re_path from .consumers import DashboardConsumer # websocket url list websocket_urlpatterns = [ re_path('ws/wdym/',DashboardConsumer.as_asgi()), ]` this is urls.py inside the application named game `from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from .consumers import DashboardConsumer urlpatterns = [ path("", views.home, name="home"), path("<int:id>",views.todo, name="todo"), path("list/", views.list, name="list"), path('wdym/', views.dashboard, name="dashboard") ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` this is consumers.py `from channels.generic.websocket import AsyncWebsocketConsumer #import the websocket import json class DashboardConsumer(AsyncWebsocketConsumer): async def connect(self): print('connection') await self.accept() self.send(text_data=json.dumps({ 'type':'connection_established', 'message': 'You are connected' })) async def disconnect(self, close_code): print(f'connection closed with code: {close_code}') async def receive(self, text_data): text_data_json = json.loads(text_data) # get the data in json strings which get loaded to a json object. message = text_data_json["message"] sender = text_data_json["sender"] print("message",message, sender) await self.send(text_data=json.dumps({ # send data … -
How to get SSL-certified django-daphne app?
I am working on deploying dockerized Django app (4.0) with channels and daphne (4.0). I am using pure gunicorn for WSGI and daphne for ASGI both. I have deployed the app and is working fine in http without SSL certified. However, I can't make it work to use HTTPS, because it fails the test. I have now spent many hours without success finding solutions. certbot log certbot | Saving debug log to /var/log/letsencrypt/letsencrypt.log certbot | Skipped user interaction because Certbot doesn't appear to be running in a terminal. You should probably include --non-interactive or --force-interactive on the command line. certbot | Account registered. certbot | Requesting a certificate for codeforkitchen.com certbot | certbot | Certbot failed to authenticate some domains (authenticator: webroot). The Certificate Authority reported these problems: certbot | Domain: codeforkitchen.com certbot | Type: unauthorized certbot | Detail: 23.92.26.102: Invalid response from http://codeforkitchen.com/.well-known/acme-challenge/_yTtIrfLPkCPzyrkDISG3MjSS6a3d2asZAxMUQZIc1Q: 404 certbot | certbot | Hint: The Certificate Authority failed to download the temporary challenge files created by Certbot. Ensure that the listed domains serve their content from the provided --webroot-path/-w and that files created there can be downloaded from the internet. certbot | certbot | Some challenges have failed. certbot | Ask for help or … -
How to run scheduled tasks in django
Lets say that I need to update an array of length 100 at 15th of each month irrespective of whether a URL is accessed or not. The server should be able to handle incoming requests while executing the function that will update the array. How do I do this? -
Django DRF integration with HDFS using a singleton pattern for resource efficiency and performance
I am trying to integrate Django DRF (Django REST Framework) server with HDFS (Hadoop Distributed File System). However, I couldn't find any official libraries that provide direct integration between Django and HDFS. Therefore, I am considering using native Python libraries for HDFS. However, these libraries typically require creating a client and making calls, which could potentially result in resource wastage and performance degradation. To address this concern, I have implemented a singleton pattern as shown in the code snippet below. from django.http import HttpResponse from hdfs import InsecureClient class HDFSClient: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) cls._instance.client = InsecureClient('http://localhost:9870', user='root') return cls._instance def read_file(self, file_path): with self.client.read(file_path) as reader: file_contents = reader.read() return file_contents def read_hdfs_file(request): hdfs_client = HDFSClient() file_path = '/test.txt' file_contents = hdfs_client.read_file(file_path) return HttpResponse(file_contents) I have implemented a singleton pattern to ensure that only one instance of the HDFS client is created and used throughout the Django application. This approach aims to minimize resource wastage and improve performance. However, I am unsure if this solution effectively resolves the resource and performance concerns. I would like to know if there are better alternatives or approaches to address these issues. -
Python: APNs error with pyapns_client3 package: 'check your code and try again later'
Hey guys I am trying to send apple push notification for voip call and I am using this package pyapns-client3==3.0.5. I have setup the voip services and certificates as per the apple developer documentation. But when I try to send notification, I am getting this exception check your code and try again later and I can't find the error in my code. Can someone help with solving this issue? Or is there a better package or code to send apple push notification? alert = IOSPayloadAlert(title=f"Call From {name}", subtitle='Incoming call', body=f'Incoming call from {name}') payload = IOSPayload(alert=alert) notification = IOSNotification( payload=payload, topic='com.company.app', // bundle identifier push_type="voip", ) with APNSClient( mode=APNSClient.MODE_PROD, authentificator=TokenBasedAuth( auth_key_path=f"{settings.APNS_AUTH_KEY}", auth_key_id=settings.APNS_KEY_ID, team_id='XXXXXXXXX' ), root_cert_path=None, ) as client: try: client.push(notification=notification, device_token=apn_token) except UnregisteredException as e: logger.info(f'device is unregistered, compare timestamp {e.timestamp_datetime} and remove from db') except APNSDeviceException: logger.info('flag the device as potentially invalid and remove from db after a few tries') except APNSServerException: logger.info(f"try again later") except APNSProgrammingException: logger.info('check your code and try again later') else: logger.info('everything is ok') Can anyone help with a better approach or help find error in this code? Thanks -
Django form save via jQuery Ajax POST request when I m submit the URL I m redirect to main form page to JSON response page
I'm using Django form and save via jQuery ajax post request. When submit the form I don't know why redirect to JSON response page and also I don't know why I m not getting response on same page in success:funcation urls. path("iEasy/Group-Type/Add/form/masterside/", views.Add_GrpPage, name="add_grp_page_m"), View.py @login_required(login_url='/') def Add_Handle_M(request): if request.method == "POST": try: form = HandleMaster_Form(request.POST) if form.is_valid: forms = form.save(commit=False) forms.create_by = request.user #forms.save() msg_error=messages.success(request,"Added") except: msg_error=messages.error(request,str(form.errors)) return JsonResponse({'msg_error':msg_error}) Html File <form id="handle_add_form" action="{% url 'add_handle_m' %}" method="post"> {% csrf_token %} {{Handle_Form}} <div class="mt-1"> <button type="submit" class="btn btn-primary">Save</button> </div> </form> **jQuery AJAX ** var add_handle_m = $('#add_handle_m'); add_handle_m.submit(function(e){ e.preventDefault(); var form_data = new FormData(this); $.ajax({ type:montadd_handle_mh_add_form.attr('method'), url:add_handle_m.attr('action'), data: serializedData, success: function(data, status){ if (status) { alert("Added") location.reload(true) } else{ alert(data.data) } }, }); }); -
Why does heroku say there is a dyno running after "ps:scale" but then "ps" says no dynos running?
I built a Django app and I'm trying to use heroku to publish it online. I've tried running the app locally and it works fine, but when I try heroku ps:scale web=1 as soon as i try heroku ps it says that there are no dynos running. Why is this? How do I get my app to run from the heroku website? Thank you for your help and understanding! In the image below my CLI was glitching out so it had text where it didn't belong. I did enter heroku ps not herokeroku ps eroku ps. -
Django deployment error in pythonanywhere
After finishing all the steps of deployment in pythonanywhere.com I got the error at wsgi.py file To remove the error and make the django application live. I have got the error at line:31 of wsgi.py file. At the part of DJANGO settings.