Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Asynchrnous WebSocket
I have problem with asychronous WebSocket communication. I have a function yeilding me data for about 3min and during that time my page is not responsing to uras actions, because onmessage is being processed. What's strangest is it sometimes worked when I made onmessage only async, without function part, but only sometimes. How can I make this piece of code really asychronous? Or how can I make page responsive when its processed? <script> ws = new WebSocket('ws://localhost:8000/ws/'); ws.onopen = async function(event) { ws.send("{{ synergy_card }}"); }; ws.onmessage = async function(event) { document.getElementById("synergyBox").innerHTML = event.data; }; </script> -
Update to tables at the same time
Please blow are my code and a screenshot of my error. What I'm not doing right. def UpdateStock(request, pk): stock = Stock.objects.get(id=pk) stock_form = StockForm(instance = stock) history_form = StockHistoryForm(instance = Stock) if request.method == 'POST': stock_form = StockForm(request.POST, instance = stock) history_form = StockHistoryForm(request.POST, instance = Stock) if stock_form.is_valid() and history_form.is_valid(): stock = stock_form.save() history = history_form.save() return redirect('inventory') context = { 'stock_form': stock_form, 'history_form': history_form } return render(request, 'inventory/edit.html', context) -
Why does create_task in testing case for DRF not work?
so I'm very new to writing test cases and I'm confused as to why my test in failing. Here is the view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend #lists, creates and filters tasks class ListTask(generics.ListCreateAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] Here is the test view: from django.test import TestCase from rest_framework.test import APITestCase, APIRequestFactory from rest_framework import status from todo.views import ListTask, DetailTask class ListTaskViewTest(APITestCase): def setUp(self): self.data = {'title':'Any title', 'description': 'Any description', 'Completed':False, 'date':'Any date'} self.factory = APIRequestFactory() def test_create_task(self): response = self.create_task() expected_code = status.HTTP_201_CREATED self.assertEqual(response.status_code, expected_code) response = self.client.get('') expected_data = {'id':1, 'title': 'supermarket', 'description':'buy fruit','completed':False} self.assertEqual(len(response.data), 1) entry = response.data[0] self.assertEqual(entry, expected_data) Why does create_task not work and what should I replace it with? I thought since I had ListCreateAPIView I could use it for my test but it seems I cannot. Any help would be very useful. -
Using default URL value in Django throws 404 error
I am trying to use a default value for url in my views, however, I keep getting a 404 error. I have set the default value both in my view and in my url path settings: This is my url: path('u/<str:username>/<obj>/', views.get_user, kwargs={'obj':None}, name="get_user"), This is my view: def get_user(request, username, obj=None): How can I set the default value of `obj` to none so I can for instance visit `u/jack/posts/` and `u/jack/` using the same URL pattern -
Mongodb, create update in python
Here is my mongodb object. I need to write update function for "graded" field. Sometimes i need to create this field, sometimes update. @api_view(['POST']) def updateGrade(request): db = connect_to_db() data = json.loads(request.body) db.update({ '_id': ObjectId(data["id"])}, { "$set" : { "worksheetSolutions.$[idx]": {"graded": data["status"]} } }, {"arrayFilters":[{"idx":data["answerId"]}]} ) q = db.find_one({'_id': ObjectId(data["id"])}) q['_id'] = str(q['_id']) return JsonResponse(q, safe=False) Here is my python code. (not correct at all as I see now) data.id => _id data.answerId => id of answer data.status => true/false var -
Using serializer how to Create Category in django rest framework
I want to create category in django rest framework with serializer. name will be provided from frontend input field. I'm getting the user_id from user = request.user and cafe_id from request.user.cafe. I need to create category with name, user_id and cafe_id. How can I do this? here is the model class Category(models.Model): user = models.ForeignKey(User, related_name="cat", blank=True, null=True, on_delete=models.CASCADE) cafe = models.ForeignKey(Cafe, related_name="category", blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Meta: verbose_name_plural='Categories' def __str__(self): return self.name Here is the serializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name'] and the views.py @api_view(['POST']) @permission_classes((IsAuthenticated,)) def categoryCreate(request): user = request.user user_id = Category(user = user) cafe = request.user.cafe cafe_id = Category(cafe = cafe) serializer = CategorySerializer(user_id, cafe_id, data=request.data) data={} if serializer.is_valid(): serializer.save() data["success"] = "Category Has Been Created!" return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Thank You In Advance -
Best way to serve large media files on a website
I'm trying to build a website with Django where you can view different 360 videos. The videos are created with a software that generates a web build with some javascript code and other media files, the size is approximately 200 Mb. Since I don't have any experience in deploying websites I don't know if it's better to host the videos on other platforms, like Amazon S3, in terms of costs and performance or I've to keep the videos on the same server that hosts my website? -
Query that excludes irrelevant ManyToMany fields Django
I'm trying to build a reddit clone and want my REST API to return info in my Post model. I have a M2M field 'Votes' where I would like to filter out any fields that don't belong to the user making the request, but still return all of the same info in the Post Model regardless if there are any matches in the vote field. Try except block is commented out just so I can see the error messages at the moment. Thanks Post View: class GetPost(viewsets.ModelViewSet): serializer_class = GetPostSerializer http_method_names = ['get'] def get_queryset(self): name = self.request.GET.get('subreddit', None) post_id = self.request.GET.get('post_id', None) # try: if name is not None and post_id is not None: if Subreddit.objects.filter(name__icontains=name).exists(): votes = Vote.objects.filter(user=self.request.user) post = Post.objects.filter( id=post_id) if len(post) > 0: return post else: pass # raise Http404 # except: # pass # raise Http404 Serializers: class VoteSerializer(serializers.ModelSerializer): updated_value = serializers.IntegerField(required=False, read_only=True) class Meta: model = Vote fields = ('value', 'updated_value', 'user') class GetPostSerializer(serializers.ModelSerializer): comments = GetCommentsSerializer(read_only=True, many=True) votes = VoteSerializer(read_only=True, many=True) class Meta: model = Post fields = ('id', 'author_profile', 'title', 'text', 'created_at', 'score', 'subreddit', 'votes', 'comments') depth = 1 Models: class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) value = models.IntegerField() submission_type … -
Django Application Using GMAIL API, Oauth Token Deleted Error
I am currently trying to create an application in Django that fetches emails from an Inbox using the gmail API. I was able to successfully perform this in Nodejs, but I wanted to switch to using Django. I used the Python Gmail API quickstart: https://developers.google.com/gmail/api/quickstart/python. I created a view for the function found in the tutorial and the first issue I encountered was "invalid redirect uri" which is an issue I encountered in the past, which I still don't understand. I tried editing the redirect uris in the Oauth Token to fix this issue, but it didn't work (I probably was doing it wrong). Eventually, I deleted the Oauth Token and tried creating a new GCP project but it said "Oauth Token deleted". I kept trying to create new ones (I updated the credentials.json everytime). I even tried starting a new Django project with a new GCP Project+ Oauth token, but I'm still getting the same "Oauth Token Deleted" error. I'm not sure whats going wrong and was wondering if someone with experience using the API would know what to do. Thanks! -
How to save data in django models taken from bootstrap form?
I'm new in Django and now I'm working on my first project. I created model 'nom' to store data and also bootstrap form in html temlplate. My question is how can I save data in my model after clicking submit button in my form in html. All answers i have found recommended me to create Form as class. Is any easy way to use data from my form? Thanks home.html <!DOCTYPE html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Title</title> <style> body { margin: 40px } .my-container { border: 1px solid green} .my-row { border: 2px solid blue} .my-col { border: 2px solid red} btn-primary { margin-left: 50px} .align-right { text-align: center; border: 0; } </style> </head> <body> <div class="container my-container"> <form action="{% url 'home' %}" method="Post"> {% csrf_token %} <div class= "row my-row"> <div class="col-3 my-col"> <input type="number" placeholder="0" name="nom200" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba %} {{ liczba }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls %} {{ ls }} {% endif %} </span></h3> </div> </div> <div class= "row my-row"> <div class="col-3 my-col"> <input type="number" placeholder="0" name="nom100" size="1" /> </div> <div class="col my-col"> <h3><span … -
django-elasticsearch-dsl-drf with JSONfield
I'm using django-elasticsearch-dsl-drf package and I have Postgres jsonField which I want to index. I tried to use Nestedfield in the document but without any properties since the json field is arbitrary, But I'm not able to search on that field, and I don't see anything related to that on their documentation. Any idea how can I achieve this? -
Python Django Templates ( For Loops ) add always 2 elements to a div
Hi guys i want to add always 2 elements to a new div container in a django template. has anyone a solution wich works? :D my code is this in the template... <center> <div class="groups-container"> {% for group in featured_groups %} {% if forloop.counter|divisibleby:2 %} <center> <div class="row"> {% endif %} <div class="col-sm-6"> <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="btn btn-success" href="/groups/join/{{ group.uuid }}">Beitreten <i class="fab fa-{{ group.type }}" aria-hidden="true"></i></a> </li> <li class="nav-item"> <a class="btn btn-primary" href="/groups/info/{{ group.uuid }}">Mehr</a> </li> </ul> <div class="group-category">Kategorie: {{ group.category }}</div> </div> <div class="card-body"> <h5 class="card-title">{{ group.name }}</h5> </div> <div class="card-body"> <p class="card-text">{{ group.short_description }}</p> </div> </div> </div> {% if forloop.counter|divisibleby:3 %} </div> </center> {% endif %} {% endfor %} </div> But the result is wrong :D its like this at the end <center> <div class="groups-container"> <div class="col-sm-6"> <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="btn btn-success" href="/groups/join/uuid.randomv4">Beitreten <i class="fab fa-whatsapp" aria-hidden="true"></i></a> </li> <li class="nav-item"> <a class="btn btn-primary" href="/groups/info/uuid.randomv4">Mehr</a> </li> </ul> <div class="group-category">Kategorie: 18+</div> </div> <div class="card-body"> <h5 class="card-title">Tolle gruppe</h5> </div> <div class="card-body"> <p class="card-text">Meine tolle Gruppe</p> </div> </div> </div> <center> <div class="row"> <div class="col-sm-6"> <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a … -
Getting a response.POST from on click Google Charts to update a Django view
This type of question has been asked several times before on SO, but I can't seem to find a correct answer for my situation. I want to sent a variable from a Google Charts Library to a Django view, I want to use this variable to update my Django Model and View to set initial values in a form and remove a record from a model. and sent it back to my HTML template to render again. I have the following Model form defined in forms.py class PlanningForm(ModelForm): class Meta: model = Planning fields = [ 'persoon', 'project', 'projecttaak', 'datum', 'begintijd', 'eindtijd', 'status', ] widgets = {'datum':DateInput(), 'begintijd':TimeInput(),'eindtijd':TimeInput()} When the form is submitted it adds a new record to the Model I use the Model to draw a Google Charts timeline as following: in views.py def planning(response, persoon, jaar, maand, dag): datum = datetime.date(jaar, maand, dag) persoon = Persoon.objects.get(id=persoon) planning = Planning.objects.all() #filter(datum=datum) planning_form = PlanningForm() planning_form = PlanningForm(initial={'persoon': persoon, 'status':'Actief'}) planning_form.fields['datum'].initial = (str(jaar)+"-"+str(maand)+"-"+str(dag)) planning_form.fields['persoon'].widget = forms.HiddenInput() planning_form.fields['status'].widget = forms.HiddenInput() planning_form.fields['datum'].widget = forms.HiddenInput() if response.method == 'POST': if 'save' in response.POST: planning_form = PlanningForm(response.POST) planning_form.save() #https://docs.djangoproject.com/en/3.1/ref/forms/api/#django.forms.Form.cleaned_data cleaned_data = planning_form.cleaned_data planning_form = PlanningForm(initial={'persoon': persoon, 'status':'Actief'}) planning_form.fields['datum'].initial = (str(jaar)+"-"+str(maand)+"-"+str(dag)) planning_form.fields['persoon'].widget = forms.HiddenInput() … -
Using the object in DetailView
Lets say i have a model named City, which has a name attribute. In my DetailView i want to use that name of the specific city it was clicked on to make some api requests and then send it to the detailview.html. Is there a way to access it? -
How to set up my Django view to GET an external API
trying to set up my Django Rest View to properly pass an external API call. class BucketData(APIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): external_api_url = "http://localhost:3000/security?select=symbol,company" res = urllib.urlopen(external_api_url).read() data = json.loads(res) print(data) return Response(data, status=HTTP_200_OK) This doesn't seem to work and I get a: { "detail": "Not found." } error when I test out the URL: api url: urlpatterns = [ path('bucket-data/', BucketData.as_view(), name='bucket-data') ] The localhost:3000 API works, I've tested it using curl, and as well using django shell using the requests library. Also, the data avaiable through localhost:3000 is already packaged in JSON. How can I solve my error? Been trying to for a couple of days and I don't think I'm close. -
It there a way to render a partial(div) only in django and then return a html json reponse
I'm looking for a way to return a JSON response for HTML div located on Django partial template. All I want to update a div section, not the entire HTML page. Similarly to the Laravel PHP framework, they are doing this for rendering the view: if ($request->ajax()) { return \Response::json(\View::make('partial_users_table', array('users' => $users))->render()); } return view('users.index', array('users' => $users)); and in javascript: $.ajax({ url : '/users', dataType: 'json', }).done(function (data) { $('.ajax-box').html(data); location.hash = page; }).fail(function (xhr) { alert('List could not be loaded.'); }); This is what I have tried for far views.py if request.is_ajax: return render(request, 'auth_app/users.html', {'users':users}) return render(request, 'auth_app/users.html', { 'users': users }) and I'm getting just a table without the full page. -
Django not able to load static file
I am trying to make a paint web app in django. My settings.py STATIC_ROOT = '' STATIC_URL = '/static/' When i try the above The project shows no errors . But my project is not able to load the css and javascript file in static folder. If the add static file finders STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) It gives following error raise ImproperlyConfigured("The storage backend of the " django.core.exceptions.ImproperlyConfigured: The storage backend of the staticfiles finder <class 'django.contrib.staticfiles.finders.DefaultStorageFinder'> doesn't have a valid location. -
Unable to intercept 404 error by mail in production (debug=False)
I try to configure django app to receive trace of error (404 and 500) when my app will be in production. I've read Django documentation and configure settings accordingly. I generate 404 error in my code, but receive no email with settings below. ADMINS = [('John', 'john@example.com'), ] MANAGERS = [('John', 'john@example.com'), ] SEND_BROKEN_LINK_EMAILS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' LOGGING = { 'version': 1, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } }, } -
Can Import Dash from dash
I am working on a django_plotly_dash project. However, after I installed the django_plotly_dash, the django setting shows an error: lib\site-pakages\django_plotly_dash\dash_wrapper.py can't load Dash from dash. I have the dash package installed. I tried to use a python shell and have no problem from dash import Dash. It appears that somehow the lib\site-pakages\django_plotly_dash\dash_wrapper.py can't import Dash only. -
contact form developed in html css and run in django and i got these much error what is the solution ?? I am a amateur trying to learn from youtube
"GET / HTTP/1.1" 200 1938 Not Found: /contactform.css "GET /contactform.css HTTP/1.1" 404 1978 Not Found: /favicon.ico "GET /favicon.ico HTTP/1.1" 404 1966 Forbidden (CSRF cookie not set.): / "POST / HTTP/1.1" 403 2864 "GET / HTTP/1.1" 200 1938 Not Found: /contactform.css "GET /contactform.css HTTP/1.1" 404 1978 List item -
django channels race condition
I'm using django channels to handle websocket connections. If two clients send two messages at the same time I get a race condition using channel's WebsocketConsumer. I'm assuming this happens because every connection to this consumer starts its own thread which is then handled in parallel with the other ones. So I thought I'd switch to AsyncWebsocketConsumer. I put async, await, database_sync_to_async and so on where necessary and everything works, but the race condition issue persists. I thought by using AsyncWebsocketConsumer, every connection would be handled in the same thread and calling async def receive(...) would block the thread so that every received message gets handled in sequence. What am I doing wrong? -
'Connection refused' when running django/postgres project in docker
I'm working on a Django/Postgres project and currently trying to dockerize. Postgresql has always worked fine on my pc, but now I'm having trouble spinning it up on docker. I get this error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I've tried a lot of solutions suggested online, but none have solved my problem. Here's all the relevant code: .yml file version: '3.8' services: web: build: context: ./web network: host command: python manage.py runserver 0.0.0.0:8000 volumes: - ./web/:/usr/src/web/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - web_db web_db: image: postgres:12.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=username - POSTGRES_PASSWORD=password - POSTGRES_DB=database volumes: postgres_data: env file SECRET_KEY=secret DEBUG=1 DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql_psycopg2 SQL_DATABASE=db_name SQL_USER=username SQL_PASSWORD=password SQL_HOST=localhost SQL_PORT=5432 settings.py DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql_psycopg2"), "NAME": os.environ.get("SQL_DATABASE", "db_name"), "USER": os.environ.get("SQL_USER", "username"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", ""), } } And here are my configs: sudo nano /var/lib/docker/volumes/project_postgres_data/_data/pg_hba.conf #TYPE DATABASE USER ADDRESS METHOD local all all trust #IPv4 local connections: host all all 127.0.0.1/32 trust #IPv6 local connections: host all all ::1/128 trust local replication all trust host replication all 127.0.0.1/32 … -
How to create views to download mulitple files?(Django)
I want to create views to download multiple files. This view downloads a single file. def submit(request): # converts files and make new output files. paths = [# list of files] base_names = [os.path.basename(path) for path in paths] path = paths[0] # paths, path both are in context def download(request): path = request.GET.get('path') base_name1 = os.path.basename(path) context = {'path': path, 'base_name1': base_name1} with open(path, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name1 return response The following template downloads a single file that is in the paths list. I want to create a template view that lists all the files in the paths list and download them. Any ideas or suggestions for this. template code: <p>You have successfully converted the file. </p> <p>Code : {{ code }} </p> #values returned from context <p>Number : {{ number }}</p> #values returned from context <p> <a href ="{% url 'download' %}?path={{ path|urlencode }} " download>{{ base_name }} </a> </p> -
unable to authenticate my django application urls
I am new to Django, I am trying to use jwt for my rest-framework API using djano simple jwt, I have an application named data_table which is having some defined urls in its urls.py as below. router = DefaultRouter() router.register('op' , views.op_ViewSet , basename='op-api') router.register('org' , views.org_ViewSet , basename='org') .... .... .... urlpatterns =router.urls as an example, my org serializer, its model and view looks like below, I am using permission_class inside my view. class Organization(models.Model): name = models.CharField(unique=True , max_length=200) class Meta: db_table = "organization" def __str__(self): return self.name class organization_Serializer(serializers.ModelSerializer) : class Meta : model = Organization fields = ['id' , 'name'] class org_ViewSet(viewsets.ModelViewSet) : serializer_class = organization_Serializer permission_classes = [IsAuthenticated] def get_queryset(self) : all_org = Organization.objects.all() return all_org I have registered this application url in the main urls.py as below, it is the main application urlpatterns. urlpatterns = [ ..... path('op-api/', include('data_table.urls')) ] my rest-framework settings is like this. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } the main problem is that http://127.0.0.1:8000/op-api/ ask me to provide token instead of http://127.0.0.1:8000/op-api/org/ if I provide a token to http://127.0.0.1:8000/op-api/ it gets authenticate, and as response it shows all the urls present in … -
Embedded BPMN editor needs a working download button with django
Currently I have a HTML Page which is embedding a BPMN Modeler via https://bpmn.io/. They way it works is that I've an empty .bpmn file in my media directory and everytime I visit my page e.g. it loads the empty .bpmn file and the user is free to model his own diagram from there. Now I'd like for the user to be able to download his .bpmn file which he created on the page. I've never worked with JS and Django before. I don't really know how to pass my modified .bpmn diagram back to my django view downlad function. Let me show the code I've so far, starting with the bpmn.io script which enables the user to work with the diagram(modeler.html): <link rel="stylesheet" href="https://unpkg.com/bpmn-js@8.0.0/dist/assets/diagram-js.css"/> <link rel="stylesheet" href="https://unpkg.com/bpmn-js@8.0.0/dist/assets/bpmn-font/css/bpmn.css"/> <script src="https://unpkg.com/bpmn-js@8.0.0/dist/bpmn-modeler.development.js"></script> <script> function fetchDiagram(url) { return fetch(url).then(response => response.text()); } var bpmnJS = new BpmnJS({ container: '#canvas', width: '100%', height: '600px', }); async function openDiagram() { const diagram = await fetchDiagram('static/bpmn/empty_bpmn.bpmn'); try { await bpmnJS.importXML(diagram); viewer.get('canvas').zoom('fit-viewport'); } catch (err) { console.error('something went wrong:', err); } } openDiagram(); </script> and the belonging view functions to this(views.py): def modeler(request): return render(request, 'core/modeler.html') def download_bpmn(request): response = HttpResponse(content_type='application/bpmn') response['Content-Disposition'] = 'attachment; filename="your_diagram.bpmn"' return response …