Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Some of my api data validations, built with rest_framework serializers, are not working
I'm using django and rest_framework and I'm trying to build an api for creating applications in oauth2_provider. So I have written an ApplicationRegistrationView: class ApplicationRegistrationView(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ApplicationSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) and I have written a Serializer: class ApplicationSerializer(serializers.Serializer): CLIENT_CONFIDENTIAL = "confidential" CLIENT_PUBLIC = "public" CLIENT_TYPES = ( (CLIENT_CONFIDENTIAL, _("Confidential")), (CLIENT_PUBLIC, _("Public")), ) GRANT_AUTHORIZATION_CODE = "authorization-code" GRANT_IMPLICIT = "implicit" GRANT_PASSWORD = "password" GRANT_CLIENT_CREDENTIALS = "client-credentials" GRANT_TYPES = ( (GRANT_AUTHORIZATION_CODE, _("Authorization code")), (GRANT_IMPLICIT, _("Implicit")), (GRANT_PASSWORD, _("Resource owner password-based")), (GRANT_CLIENT_CREDENTIALS, _("Client credentials")), ) name = serializers.CharField(max_length=100) client_id = serializers.CharField(min_length=40, max_length=40) client_type = serializers.ChoiceField(choices=CLIENT_TYPES) authorization_grant_type = serializers.ChoiceField(choices=GRANT_TYPES) client_secret = serializers.CharField(min_length=128, max_length=128, allow_null=False) redirect_uris = serializers.URLField() def create(self, validated_data): self.run_validation() app = Application.objects.create(**validated_data) app.save() and a ModelSerializer for application as well: class ApplicationSerializer(serializers.ModelSerializer): class Meta: model = Application fields = ('name', 'client_id', 'client_type', 'authorization_grant_type', 'client_secret', 'redirect_uris') The problem is that the only validation working here is ChoiseField! For example if I send a request with a 4-digit characters as client_id and some normal string for redirect_uris and nothing for client_secret but valid values for client_type and authorization_grant_type, it does not response me with errors and instead it saves my requested application to the database! Did I miss something? -
Python: Creating a list of dicts, where keys don't have quotes?
I'm using the visjs plugin to create a timeline on my page. The timeline code requires me to give it multiple dicts in a list which look like this: var items = new vis.DataSet([ {id: 1, content: 'item 1', start: '2013-04-20'}, {id: 2, content: 'item 2', start: '2013-04-14'}, {id: 3, content: 'item 3', start: '2013-04-16', end: '2013-04-19'}, ]); Now I'm trying to create something like this for my Index View by using a for loop and adding my dicts to a list, which I then put in my context and use it in my template. My code looks like this: class ItemIndex(SingleTableMixin, FilterView): model = Item context_object_name = 'items' template_name = 'accounting/item/item_index.html' def get_context_data(self, **kwargs): items = Item.objects.all() context = super().get_context_data(**kwargs) dict_list = [] for item in items: dict = { "id": item.pk, "content": Item (# {item.pk})', "start": str(item.start), #DateField "end": str(item.end), #DateField } dict_list.append(dict) context.update({ "dict_list": dict_list, }) return context Now I don't find this is the prettiest solution, but I don't know anything better (maybe someone has a better idea). In my html I'm calling the dict_list like this: var items = new vis.DataSet( "{{dict_list}}" ); My problem is that the list I'm getting back looks like this: … -
how to return image binary using multipart/form-data encoding in django
In my web site, a submitted image is sent to Django view. In Django, the image is processed for reducing the size and returned using JsonResponse. What I want to do is to return the data(binary image) as 'multipart/form-data'format. My previous code already works well with the data, multipart/form-date format from html. So I want to use the previous code. How Can I return the data as 'multipart/form-data' in django view? Here is code. view.py def receipt_reduce_size(request): if request.method == 'POST': from django.core.files.uploadedfile import InMemoryUploadedFile from io import BytesIO from PIL import Image as pil import base64 import sys # get image file imageFile = request.FILES.get("file") input_file = BytesIO(imageFile.read()) # as binary img = pil.open(input_file) image_file = BytesIO() img.save(image_file, format="jpeg", quality=80, optimize=True) contents = image_file.getvalue() encoded = base64.b64encode(contents) data = encoded.decode('ascii') # now string return JsonResponse({'status':'success', 'data':data}) I'm using Django 1.1, jQuery and ajax for request and get the response. -
Create a rest api that checks User balance before paying for orders using django rest framework
I have created the models & views for an e-commerce store using Django rest framework. For my checkout api, i want it to check my user table for the balance and then deduct the total order price before returning a response or return "insufficient balance" if the total order price is greater I tried creating a checkout request in my views.py linking a user and his balance but i couldn't decide what fields will be needed in my serializer class models.py from django.db import models from django.conf import settings from django.core.validators import MaxValueValidator # Create your models here. class User(models.Model): user_name = models.CharField(max_length=40) email = models.EmailField(max_length=40) balance = models.IntegerField(default=500000) def __str__(self): return '{0}'.format(self.user_name) class Supplier(models.Model): vendor_name = models.CharField(max_length=30) vendor_quantity = models.IntegerField() def __str__(self): return self.vendor_name class Category(models.Model): group_name = models.CharField(max_length=30) group_desc = models.CharField(max_length=200) group_quantity = models.IntegerField() def __str__(self): return self.group_name class Product(models.Model): product_name = models.CharField(max_length=30) product_desc = models.CharField(max_length=200) product_rate = models.IntegerField() product_quantity = models.IntegerField() product_supplier = models.ManyToManyField(Supplier) product_category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) def __str__(self): return self.product_name class OrderItem(models.Model): item = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_ordered = models.DateTimeField(null=True) quantity = models.IntegerField(default=1) def __str__(self): return self.item.product_name def get_total_item_price(self): return self.quantity * self.item.product_rate class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(User, … -
Multiple POST request is not working after submit
I am trying to use 2 post method in a single page one is for login and other one is for contact us login is working fine but after submitting contact us the content of login and contact us page is gone I tried to pass various type of dictionary but still, it's not working app/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from homePage.forms import SignInForm,DropUsaMessage # Create your views here. def homePage(request): if request.method == 'POST' and 'SignIn' in request.POST: sign_in_detail = SignInForm(request.POST) if sign_in_detail.is_valid(): return render(request, "index2.html",{}) elif request.method == 'POST' and 'SendMessage' in request.POST: message_detail = DropUsaMessage(request.POST) if message_detail.is_valid(): return render(request, "index.html",{}) else: sign_in_detail = SignInForm() message_detail = DropUsaMessage() context={ "form":sign_in_detail, "forms":message_detail } return render(request, "index.html",context) index.html <div class="container contact-form"> <form method="post"> <h3>Drop Us a Message</h3> {% csrf_token %} {{ forms }}<br><br> <div class="form-group"> <input type="submit" name="SendMessage" class="btnContact" value="Send Message" /> </div> </form> </div> <div class="container-fluid"> <div class="row"> <div class="col-md-8"> <img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt=""> </div> <div class="col-md-4"> <form method="POST"> {% csrf_token %} {{ form }} <div class="form-check"> <span class="fpswd">Forgot <a href="#">password?</a></span> </div> <button type="submit" class="btn btn-primary" name="SignIn">Submit</button> </form> </div> </div> </div> app/forms.py from django import forms from django.core … -
How to store and read common data in redis from python and rust?
I have some data being stored in redis cache which will be read by my application in Rust. The data is being stored by python. Whenever I am storing a string or an array, it stores it in a weird form which I was not able to read into Rust. Vice versa, I want to write from Rust and be able to read it in python. Using django shell: In [0]: cache.set("test","abc") In [1]: cache.get("test") Out[1]:'abc' Using redis-cli: 127.0.0.1:6379> GET :1:test "\x80\x04\x95\a\x00\x00\x00\x00\x00\x00\x00\x8c\x03abc\x94." Output from Rust: Err(Invalid UTF-8) Rust code read data using redis-rs library: let client = redis::Client::open("redis://127.0.0.1:6379")?; let mut con = client.get_connection()?; let q:Result<String, redis::RedisError> = con.get(":1:test"); println!("{:?}",q); I want to be able to read a string or array into Rust as it was written in Python and vice-versa. Also, data in one key will only be ever written by either Rust or Python, not both. -
Send recorded audio from browser to django server and save as .wav
I'm trying to build a web app that would record the audio from browser and send the recorded audio to django API after every 3 seconds for analysis(emotion recognition from voice). I'm using MediaRecorder for recording audio. But only noise is saved in the wave file. I'm trying to send the recorded audio(as a blob) to the django api. And then on receiving it at backend, I save it as a wav file. I'm sending the recorded audio like this: navigator.mediaDevices.getUserMedia({audio:true}).then(stream => {audio_handler(stream)}); var audio_chunks = []; audio_handler = function(stream){ rec = new MediaRecorder(stream, {mimeType : 'audio/webm', codecs : "opus"}); rec.ondataavailable = function(e){ audio_chunks.push(e.data); } } //on rec.stop() var blob = new Blob(audio_chunks, {'type':'audio/wav; codecs=opus'}); console.log(blob); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "http://localhost:8000/er/", true); var data = new FormData(); data.append('data', blob, 'audio_blob'); xhttp.send(data); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; Saving on django backend as: from django.http import JsonResponse import wave def get_emotion(request): print(request.FILES.get('data')) audio_data = request.FILES.get('data') print(type(audio_data)) print(audio_data.size) audio = wave.open('test.wav', 'wb') audio.setnchannels(1) audio.setnframes(1) audio.setsampwidth(1) audio.setframerate(16000) blob = audio_data.read() audio.writeframes(blob) //on playing 'test.wav' only noise can be heard return JsonResponse({}) I expect the wave audio file saved to have same … -
I am not able to retrive OneToOneField data from backend Django
i can get data from backend from User e.g user.id but when i want to get data from OneToOneField e.g user.checkAdmin.isAdmin its not displaying any data in html page views.py def registerView(request): if request.method == "POST": form = UserCreationForm(request.POST) isAdminForm = checkAdminForm(request.POST) # if form.is_valid() and isAdminForm.is_valid(): user = form.save() isAdminFormObject = isAdminForm.save(commit=False) isAdminFormObject.user = user isAdminFormObject.save() return redirect('login_url') else: form = UserCreationForm() isAdminForm = checkAdminForm() return render(request, 'registration/register.html',{'form':form,'isAdminForm':isAdminForm}) Forms.py from django import forms from .models import checkAdmin class checkAdminForm(forms.ModelForm): class Meta: model = checkAdmin fields = ['isAdmin'] models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class checkAdmin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isAdmin = models.BooleanField(default=False) def __str__(self): return self.user.username dashboard.html {% extends 'index.html' %} {% block content %} <h1>Welcome, {{ user.id }}</h1> <h1>check?,{{ user.checkAdmin.isAdmin }}</h1> <button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button> <a href="{% url 'logout' %}">Logout</a> {% endblock %} -
Django Wagtail: get children of page using custom method in django regular view
I am playing with Wagtail 2.6.1 and I got in confusing problem. I need to work with Page model in vanilla Django view. I want to get children of BlogPage, so I made custom method, which should return all children pages. Method works, but only in template view. When I access it in django view, it returns empty queryset. I really don't understand why. My models.py class BlogPage(Page): template = "blog/blog.html" max_count = 1 subpage_types = ['blog.BlogPostPage','blog.PostAdvancedPage'] promote_panels = Page.promote_panels + [ FieldPanel('menu_order'), ] def getChildren(self): children = self.get_children().live().all() return children def get_context(self, request): context = super(BlogPage, self).get_context(request) context['categories'] = BlogCategory.objects.order_by('name').all() context['blog_posts'] = self.get_children().live().order_by('-first_published_at').all() return context class Meta: verbose_name = "Blog" verbose_name_plural = "Blogs" my views.py from .models import BlogPage def post_filter(request): if request.method == 'POST': posts = BlogPage().getChildren() # this return empty queryset print (posts) but when I render this method in template blog.html it works: <div class="section py-9"> {{self.getChildren}} </div> it successfully render all children pages in template: <PageQuerySet [<Page: Lorem Ipsum 01>,<Page: Lorem Ipsum 02>]> Please note that I am normally using get_context method to render all posts in my template, I just tried render this method (getChildren) in template to check if that's working. -
DOMException when sending audio file using Django
I am building a Django based web app in which I want to play an audio file from the server in the browser upon the click of a button. The file changes with the use of the app so I call a Django view through the src attribute of the audio element like so: <audio id="audio" src="{% url 'play' 'for-sure' %}" type="audio/wav"></audio> Here for-sure is the default filename to play. Here's the mapped view function: def play(request, file_name): with open(f'audio/{file_name}.wav', 'rb') as f: response = HttpResponse(f.read(), status=206) response['content_type'] = 'audio/wav' return response I also add a button to play the sound: <input type="button" value="Play audio" onclick="play()" id="play_btn"> And the accompanying Javascript: function play(){ var audioElement = document.getElementById("audio"); var promise = audioElement.play(); if (promise !== undefined) { promise.then(_ => { console.log('playing') }).catch(error => { console.log('playing error') console.log(error) console.log(error.message) }); } }; This works in Firefox (v68), but I keep getting DOMException: Failed to load because no supported source was found in Chromium (v76). From what I've found it seems to be the AutoPlay prevention policy, but it should be also active in Firefox. If it is, I'm guessing it could be triggered by receiving the HTTP response by the view that … -
defining object method outside its class block, any reason not to?
The following surprised me, although perhaps it shouldn't have. However, I've never seen this done elsewhere def bar_method(self): print( f"in Foo method bar, baz={self.baz}") # and pages more code in the real world class Foo(object): def __init__(self): self.baz = "Quux" bar = bar_method >>> foo = Foo() >>> foo.bar() in Foo method bar, baz=Quux >>> This follows from the definition of def which is an assignment of a function object to its name in the current context. The great advantage, as far as I am concerned, is that I can move large method definitions outside the class body and even into a different file, and merely link them into the class with a single assignment. Instantiating the class binds them as usual. My question is simply, why have I never seen this done before? Is there anything lurking here that might bite me? Or if it's regarded as bad style, why? (If you are wondering about my context, it's about Django View and Form subclasses. I would dearly love to keep them short, so that the business logic behind them is easy to follow. I'd far rather that methods of only cosmetic significance were moved elsewhere). -
Multi-Tenant Archiecture Variations
Is there a variation of the multi tenant architecture where tenants are able to know each other? also is it possible with this architecture that an entity belongs to multiple tenants? Right now I'm working in a multi tenant architecture where each tenant is independent, but now requirements change and a tenant could know another tenant. -
How to shape response with 'group_by' query
I want to create custom response object for an endpoint with using type of the object as keys. Its a django back-end model shape: Model.blahblah( id = uuid type = 'type1' value = 'im batman!' ) view: class HedesView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): hedes = Event.objects.all().query events.group_by = ["type"] evento = QuerySet(query=hedes, model=Hedes) return Response( { "hedes": EventSerializer(evento, many=True).data } ) response: hedes: [{...}, {...}, {...}] how can I edit this response to be like this hedes: { type1: [{...}, {...}], type2: [{...}] } -
Passing Dropdown Value To URL in Django
I am rendering a dropdown which displays a list of integers. This is the only field in the form/view. Once that form is submitted, the integer selected should be passed to the URL of the next view which is rendered on submission of the previous form. I am getting a 404 when I attempt this. Here is what I am currently trying: forms.py #this is the dropdown field class ManifestDropDown(forms.Form): reference = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(), empty_label=None) views.py #this is the view where the dropdown is submitted def manifest_references(request): if request.method == 'POST': form = ManifestDropDown(request.POST) if form.is_valid(): reference_id = form.cleaned_data.get('reference') form.save() return render('manifest', reference_id=reference_id) query_results = Orders.objects.all() reference_list = ManifestDropDown() context = { 'query_results': query_results, 'reference_list': reference_list, } return render(request, 'manifest_references.html', context) #this is the view where the value should be displayed in the url def manifest(request, reference_id): form = CreateManifestForm(request.POST) if request.method == "POST": .... data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) urls.py #url which displays the manifest view above url(r'^manifest/(?P<reference_id>\d+)/$', manifest, name='manifest'), -
Django: Convert string of numbers to ip address in dynamic listview
I have a django website containing a page with a listview. The list, created from a object-list in a for loop {% for betr in object_list %} contains a field with ip addresses like <td>{{ betr.netmask }}</td>. The data in the object list is provided as a string of numbers like "123456789111". What is the best way to display this as 123.456.789.111. Tried lambda or normal functions imported as utils, but always ran into errors. -
Is it possible to use GitLab CI/CD for running Django without Docker?
I'm trying to use GitLab CI/CD feature with my Django project. Is it possible to run this Django project with GitLab runner without Docker so after every git push server is started again? At this moment server is running but after git push it is not restarted but it creates new job instance again. I have tried to make some basic .gitlab-ci.yml file but after I push updates to master the job is running and never ending. I can reach the server website but when I want to update something else to master new job is created and the previous does not automatically end. script: - python3.6 manage.py runserver --noreload 0.0.0.0:8001 >/dev/null I think this line where I'm trying to runserver is most likely wrong. -
How to render two different sitetrees and highlight the differences
As part of a web-permission managing system user can request access to pages from group owners. On the authorisation page I would like to display the current sitetree (sitree_before) of the requesting user and next to it how his sitetree would look with the changed permissions (sitetree_after). In the best case scenario i would like to highlight in sitetree_after the new elements. I know I can render the sitetree with {% sitetree_tree from 'sitetree_main' %} but couldn't figure out how to pass additional arguments to modify the groups which are getting used to get the sitetree items. expected results: sitetree_before |- parent 1 |---child 1 |---child 2 |-----grandchild 1 |-----grandchild 2 |---child 3 sitetree_after |- parent 1 |---child 1 |---child 2 |-----grandchild 1 |-----grandchild 2 |---child 3 |---child 4 |---child 5 |---child 6 |-----grandchild 1 -
How delete obj with condition in view
My model class User(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Phone(models.Model): user = models.ForeignKey(Osoba, editable=False, related_name='phone', on_delete=models.CASCADE) phone = models.CharField(max_length=50) I would like to be possible to delete an object only if there is no value in his fields def delete_user(request, id): user = User.objects.get(id=id) if not user.email or user.phone: if request.method == 'POST': user.delete() print(user.email) return redirect('list_users') return render(request,'index-delete.html', {'user': user}) I tried this but it doesnt work -
Django microsoft authentication and rest framwork
I've developed an application that (by django-microsoft-auth)let our 0365 tenant use to authenticate. Actually user have a O365 SSO button in login form that if user is not yet logged open o365 login page and if the authentication is good create if not yet present, the user in django. Now i want to separate frontend and backend using django and django-rest-framework for the backend and react for the frontend. What'is the best way to use o365 authentication in this setup? -
Pass variable to included template in django
I am trying to pass variable to child template: {% block footer %} {% include '_footer.html' with var="foo" %} {% endblock footer %} but I am getting django error: Exception Type: TemplateSyntaxError at / Exception Value: expected token 'end of statement block', got 'with' What am I doing wrong? -
Azure Devops deploy django application to Linux Azure App Service
Like many AzureDevops tasks this should be easy, but is turning into masochistic nightmare of re-reading the same copied and pasted tutorial examples. Following the VSCode tutorial https://code.visualstudio.com/docs/python/tutorial-deploy-app-service-on-linux everything works beautifully and I can see in the output the virtual antenv being created and configured. However, it's taken a long time to get away from the right-click -> publish habit and to start using AzureDevops as our pipeline, I'm very uneasy nowadays about publishing from my local repo and dev machine. Trying to get the same working deployment in AzureDevops has thus far not proven particularly easy. The closest help I can find is in this article https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python-webapp?view=azure-devops#create-and-run-an-initial-pipeline where if followed through results in the contents of the .zip folder being deployed to \wwwroot folder correctly but the install process not completing by creating a VEnv and installing from the requirements.txt. Is it simply the case that this only works from a GitHub repo and not from an Azure Repo? If so, why, and does Microsoft have any intention of making the deployment process work with their own technology? -
Django query count only on a specific column
Why does Django's count() result in a SQL query like SELECT COUNT(*) and is there a way to just count on a single row, like for instance SELECT COUNT(id) -
How can I post data with json nested and image file use APIRequestFactory in Django
I have problem when post data json with image file using APIRequestFactory. This is my demo code: post_data = { 'token': token, 'account': 'account', 'avatar': image_file, 'user': { 'email': 'user email', 'account': 'user_account', } } request = self.factory.post('/account/create', post_data, 'multipart') And this is error I got: AssertionError: Test data contained a dictionary value for key 'user', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. Please help me resolve this problem. Thank you. -
How to build json dynamically in python using tuple
I want to build json in following format { "codeTableData": [ { "codeValue": "11", "codeDisplayName": "AAAAAA" }, { "codeValue": "22", "codeDisplayName": "BBBBBB" } ] } from tuple which is result = [('11', 'AAAAAA'), ('22', 'BBBBBB'), ('33', 'CCCCCCCC')] I have tried creating dictionary and then adding tuple data inside that dictionary but still no luck jsonResult = {"codeTableData: " [ { tmp1:tmp2 }, ]} json_data = json.dumps(jsonResult) for above code program execution comes out of function with no error shown -
All the tabs in the chrome are loading same django page simultaneously
I'm developing a django application. In chrome when i test the app it works fine but if i work with multiple pages of same django application all the pages load at the same time. i.e, If I open admin page in one tab all the tabs that are running django application loads admin page simultaneously. This happens even while using different users and tabs at the same time. When i tried the same in Edge browser it was fine. I was able to load two different pages at the same time but not in chrome. I don't know what is happening here. Please help me to understand this problem, whether this is due to some bugs in my chrome or django application.