Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying epics and tasks in Django
I'm using Django to create a Scrum board. In Scrum, Tasks may or may not be part of an Epic. Here's a simplified version of my models.py file: from django.db import models class Epic(models.Model): name = models.CharField(max_length=50) class Task(models.Model): TO_DO = "TODO" IN_PROGRESS = "IP" DONE = "DONE" TASK_STATUS_CHOICES = [ (TO_DO, 'To Do'), (IN_PROGRESS, 'In Progress'), (DONE, 'Done'), ] name = models.CharField(max_length=50) status = models.CharField( max_length = 4, choices = TASK_STATUS_CHOICES, ) epic = models.ForeignKey(Epic, on_delete=models.DO_NOTHING, null=True, blank=True) My views.py page currently filters objects by status: def board(request, **kwargs): todos = Task.objects.filter(status='TODO') ip = Task.objects.filter(status='IP') done = Task.objects.filter(status='DONE') context = { 'todos': todos, 'ip': ip, 'done': done, } return render(request, 'scrum_board/main.html', context) My template then displays three columns of tasks by iterating through each QuerySet by using a for loop. However, I'd like tasks from the same Epic to be displayed together and enveloped within a container (can be a simple HTML table, or a Bootstrap card). How can I do this? One way that immediately comes to mind is the following method (pseudo-code) for each column (task status): for epic in epics: # draw a html table cell for task in tasks: # display task for task in … -
Django - name 'utils' is not defined
So I am following this little tutorial for a search form but after getting everything setup and when I press search I get a error saying name 'utils' is not defined I tried Googling but had no luck so any help will be welcomed. Thanks! home.html: ... <form id="searchform" action="{% url 'pages_urls:search' %}" method="get"> <input type="text" name="q" type="text"/> <button type="button" onclick="searchform.submit()">Search</button> </form> ... urls.py: from django.urls import path from .views import search_view app_name = 'pages_urls' urlpatterns = [ ... path('search/', search_view, name='search'), ] views.py: ... def search_view(request): query_string = '' found_entries = None if ('q' in request.GET) and request.GET['q'].strip(): query_string = request.GET['q'] entry_query = utils.get_query(query_string, ['subject', 'content',]) posts = Post.objects.filter(entry_query).order_by('created_at') context = { 'query_string': query_string, 'posts': posts } return render(request, 'search.html', context) else: context = { 'query_string': 'Null', 'found_entries': 'Enter a search term' } return render(request, 'search.html', context) search.html: <p>Posts containing '{{ query_string }}'</p> {% for post in posts %} <div> <span> {{ post.created_at }} </span> <a href="#"><h2 class="page-title">{{ post.subject }}</h2></a> <div class="post"> {{ post.content|safe }} </div> </div> {% endfor %} -
I have been trying to get an instance of the apartment model all to avail
I have been trying to get an instance of the apartment model all to avail. When I try to use the primary key via the url, I get all the data instead of an instance which is what I need. When I use the link: "localhost:8000/apartments/1", instead of getting details about the instance of pk 1, I get all the data. models.py from django.db import models from django.utils import timezone class Apartment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) description = models.TextField() house_address = models.CharField('house_address',max_length=10000, null=True) #apartment_categories = models.ForeignKey('ApartmentCategory',on_delete=models.CASCADE) house_name = models.CharField('house_name',max_length=60) house_pic = models.ImageField(upload_to='images/') title = models.CharField(max_length=300) price = models.CharField('price',max_length=60) total_rooms = models.CharField('total_rooms', max_length=100), choices = ( ('Yes', 'Yes'), ('No', 'No') ) isFurnished = models.CharField('furnished',max_length=50,choices=choices) isParkingSpace = models.CharField('parkingspace',max_length=70,choices=choices) isAvailable = models.CharField('available', max_length=100,choices=choices) isFenced = models.CharField('fenced', max_length=100, choices=choices) isHaveWater = models.CharField('water', max_length=100,choices=choices) isNewHouse = models.CharField('new',max_length=80,choices=choices) isNegotiable = models.CharField('new', max_length=80,choices=choices) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.house_name views.py from django.shortcuts import render from .serializers import ApartmentSerializer,UserSerializer from .models import Apartment,User from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status, viewsets from django.core.paginator import Paginator from rest_framework.pagination import LimitOffsetPagination from rest_framework.permissions import IsAuthenticated from rest_framework.authtoken.models import Token from rest_framework.authentication import BasicAuthentication,SessionAuthentication,TokenAuthentication from django.http import Http404 from django.shortcuts import get_object_or_404 class ApartmentList(APIView): authentication_classes = … -
Django form invalid, no errors
I'm pretty new to Django so hopefully it's a rookie mistake. I have this form with choice fields built from a query set and built with a loop. Actually two of those, one for some indicators another one for comments. I'm then looping through each field to display what I need. I have a separate form to report a student as absent. this one works fine. But when I test is_valid on my indicator form it returns false and unfortunately I cannot seem to get the errors displayed in the template. Here is the form class IndicatorForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) competencies = Competency.objects.all() for competency in competencies: field_name = competency.competency indicators = competency.indicators() indicator_choices = [] for indicator in indicators: indicator_choices.append((indicator.level, indicator)) self.fields[field_name] = forms.ChoiceField(choices=indicator_choices, label=False) self.fields[field_name].widget.attrs.update({'class': 'select2field criterialevel'}) Here is the view def assess(request, course_id, student_id): competencies = Competency.objects.all() current_user = Users.objects.get(pk=request.user.id) course = Course.objects.get(pk=course_id) student = Users.objects.get(pk=student_id) if request.method == 'POST': comment_form = forms.CommentForm(request.POST) absent_form = forms.AbsentForm(request.POST) indicator_form = forms.IndicatorForm(request.POST) if absent_form.is_valid(): if absent_form.cleaned_data.get('absent'): absent_data = StudentAbsent(student=student, entryUser=current_user, course=course) absent_data.save() messages.success(request, "%s's data was saved successfully" % student.englishName) return redirect("/student-list/%s" % course_id) elif indicator_form.is_valid(): for competency in competencies: assessment = PMCompetencyAssessment(user=current_user, course=course, student=student, competency=competency.id, level=comment_form.cleaned_data.get(competency), … -
Keep PowerShell session alive within a Django app
I have a Django app that has to run several PowerShell scripts. The issue I'm having is that I have to create a new O365 session each time one is run. As PS O365 is prone to connection issues and hanging, sometimes the scripts start but never complete. Is there a way to open the PS session when the app is started and then be able to use the cmd-lets without creating a new session each time? Keeping the session open until the app is closed. I've tried opening a session as soon as a user logs in with this script: start-session.ps1 import-module ".\contactsdb\code\scripts\VIS-AD-Functions.ps1" $CredData = Get-Content -Raw ".\contactsdb\code\scripts\data\cred.json" | ConvertFrom-Json $MSCredentials = Get-StoredCredential -UserName $CredData.cred $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $MSCredentials -Authentication Basic - AllowRedirection Import-PSSession $Session -DisableNameChecking That starts a session but if I then try to run another script later on such as this: $Data = Get-Content -Raw ".\contactsdb\code\scripts\data\data.json" | ConvertFrom-Json foreach ($Dat in $Data) { Remove-DistributionGroup -Identity $Dat.identity -Confirm:$false } I get the following error: Remove-DistributionGroup : The term 'Remove-DistributionGroup' is not recognized as the name of a cmdlet -
Default image set in image field not found
In the Profile model below, a default image is set in the image field for a registered user. A default image is provided in the Django media directory media/profile_pics After the register view form is saved(in line 10) in the views, an error message is printed out saying the file or directory to the image is not found. This is because the directory in which Django is looking for the image is wrong. Its looking in the path C:\\dev\\blogger\\media\\default.png instead of C:\\dev\\blogger\\media\\profile_pics\\default.png I've been on this for hours just trying to fix it, but to no avail. source code below. Error: FileNotFoundError at /account/register [Errno 2] No such file or directory: 'C:\\dev\\blogger\\media\\default.png Directory C:. ├───.vscode ├───blog │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───blogger │ ├───static │ │ └───blog │ └───__pycache__ ├───media │ └───profile_pics ├───templates │ ├───blog │ │ └───post │ └───users ├───users │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ Model: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' # Override save nethod. Resize images for scalability def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or … -
AWS Signed URLs from SQL
I've got a lot of static content in an S3 bucket that doesn't have public read access. I want to provide access to this content by generating signed urls. I'm using python and boto3 library for most use cases. I have a few raw SQL queries though that pull the URLs straight from the database and dump them right to the browser. I'd rather not have to loop through all the results on the server, convert the urls to signed urls using python, and then send it to the browser. I'd prefer that there be a SQL equivalent of this magic. Instead of select imageFileUrl from photos; I'd like to be able to do something like select signed_url(imageFileUrl) from photos; The python boto class / function for this seems to be botocore.signers.RequestSigner.sign() Upon looking deeper the real meat of it (for my use case at least) appears to be botocore.auth.HmacV1QueryAuth and its get_signature, canonical_string, sign_string and _inject_signature functions. Has anyone solved this problem before? Am I on the right track? I'm using python 3, django 2, and postgresql 10. -
Django simple history register issue
I am trying to register simple history django "api" and it works fine (admin.site.register(Entries, SimpleHistoryAdmin) and show me the history in history tab in the specific object, but when i register it like admin.site.register(Entries, EntriesAdmin) it show me the filers and search fields but the history is "gone" like it is saying that there is nothing to show, even that it was there. I tried to combine that admin.site.register(Entries, EntriesAdmin, SimpleHistoryAdmin) but it raise the 500 server error. So can someone please help me how to show simple history records and also use filters in django admin? list_display = ('EngagementCode', 'EngagementManager', 'EngagementIncharge', 'published') list_filter = ('EngagementCode', 'EngagementManager', 'EngagementIncharge', 'published') history_list_display = ["EngagementCode"] search_fields = ('EngagementCode', 'EngagementManager', 'EngagementIncharge', 'published') -
How would I get the value in this python dict for loop?
Im trying to get a confidence score from an image analyzing api, but its returning a weird list dictionary, and i dont know how to loop through and get the score. r = requests.post( "https://api.deepai.org/api/nsfw-detector", files={ 'image': open(image/path, 'rb'), }, headers={'api-key': 'key'} ) data = r.json() ra = zip(data) row = data.values() for value in row: print(value) is retruning a json output of {u'detections': [], u'nsfw_score': 0.0003515253774821758} 403b793e-4ce7-44ba-8760-f9d97a1ed442 how do i loop through and get the nsfw score key value so i can set it as a variable so i can run another conditional (ie if score > .5 delete file) thanks! -
I am trying to send mass email and it is giving me this error in django "not enough values to unpack (expected 4, got 1)"
this are email addresses from subscibed newsletter. when i pass an email, it worked perfectly now i wanna send each blog post to my subscriber via mail. i used the send_mail function and i filter all the emails from the database and pass it to the send email function but it is given me this error "not enough values to unpack (expected 4, got 1)". i will be really glad to get a solution to this. this are my lines of code: def postblog(request): if request.method == 'POST': post_form = PostForm(request.POST, request.FILES) if post_form.is_valid(): post = post_form.save() print(post) emails = Newletter.objects.filter(email = 'email') # post = Post.objects.filter(id=post_form.id) post_url = request.build_absolute_uri(post.get_absolute_url()) subject = post.title message = f'{post.title}\n\n.{post.image.url} {post.descriptions[:40]}\n{post_url}' send_mass_mail(subject, message, 'omotoshomicheal93@gmail.com', [emails]) print(send_mass_mail) return redirect('post_blog') else: post_form = PostForm() and this is the error: ValueError at /post-blog/ not enough values to unpack (expected 4, got 1) Request Method: POST Request URL: http://127.0.0.1:8000/post-blog/ Django Version: 2.2.6 Exception Type: ValueError Exception Value: not enough values to unpack (expected 4, got 1) Exception Location: C:\Users\user\Documents\atom\mydjango\myenv\lib\site-packages\django\core\mail\__init__.py in <listcomp>, line 83 Python Executable: C:\Users\user\Documents\atom\mydjango\myenv\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\\Users\\user\\Documents\\atom\\mydjango\\myenv\\swiftblog', 'C:\\Users\\user\\Documents\\atom\\mydjango\\myenv\\Scripts\\python37.zip', 'C:\\Users\\user\\Documents\\atom\\mydjango\\myenv\\DLLs', 'C:\\Users\\user\\Documents\\atom\\mydjango\\myenv\\lib', 'C:\\Users\\user\\Documents\\atom\\mydjango\\myenv\\Scripts', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\user\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\user\\Documents\\atom\\mydjango\\myenv', 'C:\\Users\\user\\Documents\\atom\\mydjango\\myenv\\lib\\site-packages'] Server time: Thu, 19 Dec 2019 08:00:06 +0000 … -
Redirecting www to non-www with http to https redirect and wildard subdomains
I just installed SSL certs but when visiting the www domain of my site it now shows the Apache2 Ubuntu default page. How do I redirect the www to non-www with http --> https and * subdomains? <VirtualHost *:80> ServerName clearpath.site ServerAlias *.clearpath.site ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =clearpath.site [OR] RewriteCond %{SERVER_NAME} =*.clearpath.site RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet And me VH for port 443: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName clearpath.site ServerAlias *.clearpath.site ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/david/clearpath_project/static <Directory /home/david/clearpath_project/static> Require all granted </Directory> Alias /media /home/david/clearpath_project/media <Directory /home/david/clearpath_project/media> Require all granted </Directory> <Directory /home/david/clearpath_project/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/david/clearpath_project/config/wsgi.py WSGIDaemonProcess django_app python-path=/home/david/clearpath_project python-home=/home/david/clearpath_project/> WSGIProcessGroup django_app Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/clearpath.site/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/clearpath.site/privkey.pem </VirtualHost> </IfModule> Any help is appreciated. -
Django annotate this?
I have a function that is present on a field on my model that I would like to sort by. The function (sort in the example below) takes the instance of the model as the argument and spits out a value. I need to pass the model instance so that I can get values from fields. I want to sort by the output of the function. I'm trying to do something like: model.objects.annotate(sort_value=field.sort(this)).order_by(sort_value) How can I reference an individual model instance in the queryset (using this as the placeholder in the example)? Should I be using something other than annotate? -
JSON error after setting sessions expiry in django
I'm try to make sessions expire in one hour, so I have this line of code: logger.debug(f'Session will expire at {session.get_expiry_date()} (in {session.get_expiry_age()} seconds)') session.set_expiry(datetime.now() + timedelta(hours=1)) logger.debug(f'Session will expire at {session.get_expiry_date()} (in {session.get_expiry_age()} seconds)') It appears to work fine - I get this debug log: [18/Dec/2019 17:34:43] DEBUG [app.accounts.models:222] Session will expire at 2020-01-01 17:34:43.108876 (in 1209600 seconds) [18/Dec/2019 17:34:47] DEBUG [app.accounts.models:224] Session will expire at 2019-12-18 18:34:47.659005 (in 3600 seconds) But then, when it completes processing the request, I get the following error: File "...\Python37\site-packages\django\contrib\sessions\backends\base.py", line 96, in encode serialized = self.serializer().dumps(session_dict) File "...\Python37\site-packages\django\core\signing.py", line 87, in dumps return json.dumps(obj, separators=(',', ':')).encode('latin-1') File "...\Python37\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "...\Python37\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "...\Python37\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "...\Python37\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type datetime is not JSON serializable -
Make Django REST endpoints inaccessible if no permission exists
currently I am creating a webbackend with Django, where the administration is done with KeyCloak. With KeyCloak I can assign users with certain role (e.g. customers, subscription customers). The customer and subscription customer have different permissions. (E.g. like in the film industry, where only the subscription customers can watch all movies and the normal customer can not) There's an endpoint to every movie. How can I make this endpoint inaccessible with missing permissions? -
Rule of thumb for designing nested/related models in Django
I'm building an application in which companies can publish different types of posts. Posts contain in part common data and in part post-specific data. Posts, no matter which type they are, are displayed together and ordered according to their publication date. Thinking about how to model posts, I read that model inheritance - having a common base model/class (e.g. CompanyPost) containing common attributes and inheriting it in child models (e.g. a PostA child) - would give me flexibility down the road. I understood e.g. that looping over instances from greatly different models would be difficult and with inheritance I could easily loop over all the posts by accessing them via the parent class. So that is what I did: I have a company model. Then I have a base model for company posts. It contains common posts attributes. An attribute is the company that publishes the posts. It refers to the Company model with a ForeignKey. Finally I have child models (based on the CompanyPost base model) for posts of type A, type B etc.: class Company(models.Model): name = models.CharField(...) ... class CompanyPost(models.Model): company = models.ForeignKey(Company,...) ... class PostA(CompanyPost): name = ... class PostB(CompanyPost): name = ... Now the problem. … -
How to write data to model
I've put together code to create/save profiles: view.py class ProfilePageView(FormView): template_name = 'meal_delivery/profile.html' form_class = ProfileForm success_url = '/meal_delivery/profile' def form_valid(self, form): profiles = Profile.object.filter(user_id=self.request.user.id) if profiles: form.instance = profiles[0] form.save() messages.success(self.request, 'Profile Updated') else: obj = form.save(commit=False) obj.user = self.request.user obj.save() messages.success(self.request, 'Profile Saved') return super(ProfilePageView, self).form_valid(form) def get_initial(self): profiles = Profile.object.filter(id=self.request.user.id) if not profiles: return {} return { 'first_name': profiles[0].first_name, 'last_name': profiles[0].last_name, 'address1': profiles[0].address1, 'address2': profiles[0].address2, 'city': profiles[0].city, 'state': profiles[0].state, 'zip_code': profiles[0].zip_code, 'allergens': profiles[0].allergens } form.py class ProfileForm(forms.ModelForm): first_name = forms.CharField(max_length=60) last_name = forms.CharField(max_length=100) address1 = forms.CharField(max_length=200) address2 = forms.CharField(max_length=200) city = forms.CharField(max_length=100) state = forms.CharField(max_length=100) zip_code = forms.CharField(max_length=25) CHOICES = tuple((o.pk, o.name) for o in Allergen.objects.all()) allergens = forms.MultipleChoiceField(choices=CHOICES, required=False) class Meta: model = Profile fields=['first_name', 'last_name', 'address1', 'address2', 'city', 'state', 'zip_code', 'allergens'] def clean(self): pass models.py class Profile(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=100) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zip_code = models.CharField(max_length=25) user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) allergens = models.ManyToManyField(Allergen, related_name='profiles') object = ProfileManager() Creates profile if one does not exist, no problem. However, when I go to update the data, nothing updates, no errors are reported and if I check the form object, it shows the updated fields … -
Deal 'Update Images' in Popup Django
I am stuck in a scenario . I have a update from through which I want to update images in database. like I have a Database table in which images field have a ManytoMany realtion to a image table in db class Merchandise(models.Model): adOwner = models.ForeignKey(VendorProfile, on_delete=models.CASCADE) imagesMerchandise = models.ManyToManyField(merchandiseImages) Many to Many table is class merchandiseImages(models.Model): image = models.ImageField(null=False, upload_to='Mrchandise') Now when I get data from database I populate on a popup my images like this (just to show on popup data from my database) res.data[0].imagesMerchandise.forEach(function (arrayItem ,i ) { $("#photos1").append('<div id='+i+' class="col-md-3 col-sm-3 col-xs-3"><img width="100%" height="80px" name="photoimages" src='+arrayItem.image+' class="rounded mb-2"></div>'); $('#photos1').attr('src', arrayItem.image) }); I am appending this code to my form to show images in database. Code of my input field is like <div class="col-md-9"> <div class="form-group"> <input type="file" class="form-control" accept="image/*" name="photo" id="photo" onchange="readFile(this);" multiple required/> </div> </div> Now when I get request.FILES['photo'] I only get new uploaded images not from databases as I want to include my uploaded images to input field so I can update my images . Or is there any good way to do this ? ANy help would be highly apprecited -
when i run the program it shows an error in server like, no json object could be decoded
when i run the program it shows an error in server like, no json object could be decoded,can help to solve this issue. def savesubcategory(request): import json if request.method == 'GET': received_json_data = json.loads(request.body) store_list = [] for item in received_json_data: id = item['user'] name = User.objects.get(id=id) print name id = item['news_category'] categ = NewsCategory.objects.get(id=id) print categ for ite in item['sub_category']: subcat = NewsSubCategory.objects.get(id=ite) savecat = SavingCategoryandPreferences(user = name ,news_category = categ ,subcategories = subcat) savecat.save() return HttpResponse(received_json_data) return HttpResponse("faild") -
Is it possible to save a model without uploading a file?
I have a model that contains a FileField. I am manually saving the file through an API call, though, so I don't want the model to upload anything for the FileField, but I do want it to save the file name and location. Can this be done? -
Docker does not create project directory as expected
I am following the docker/django tutorial: https://docs.docker.com/compose/django/ I set up a project directory C:\docker_test and configured docker-compose.yml, Dockerfile and requirements.txt as described in the guide. When I run docker-compose run web django-admin startproject composeexample . it executes as expected but I do not see a composeexample directory created. If I attempt to re-run the command I get this error: CommandError: /code/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files I don't have a /code/ directory on my local machine... where is it located? Thanks! -
Is possible create an application Django/HTML for Sony Bravia TV?
Good morning, I would ask there's possible create an application like Netflix for TV (exactly Sony Bravia)? Like emulator for TV. If it isn't possible in Django maybe is it possible in Spring? -
Is it possible to display pyodbc data to html via Django website?
We have a bunch of employees who have ODBC connections on their desktops and use Excel to query the database. The strain of the queries is causing SQL to bog down. I would like to incorporate these SQL queries into a Django website I already use for reports. I want to execute a SQL query and return the results to HTML. I have done something similar in the past where I did a SQLquery -> saved each individual result(row) into an instance of a model, then serialized that model and displayed it. Is this the best approach? I feel like querying a SQL database then saving it into the local SQLite database is bad practice. -
Accessing data using Pillow corrupts it on response in Django Rest Framework (The file you uploaded was either not an image or a corrupted image.)
I want to extract the format and mode parameter from the uploaded image within the Serializer and dynamically update my fields. Here is the code ... class ImageDataSerializer(serializers.ModelSerializer): class Meta: model = models.ImageData exclude = ['height','width'] And in my view serializer = serializer(data=request.data,partial=True) serializer.is_valid(raise_exception=True) obj = serializer.save(user=request.user,extension="PNG",image_type="RGB") return Response(serializer.data) This works perfectly. I am sending my InMemeoryUploadedFile instance as my data and the serializer does its job saving it to the database. However, I would like to determine the extension and image_type automatically using the Pillow library. This is what I have tried so far ... class ImageDataSerializer(serializers.ModelSerializer): def __init__(self,*args,**kwargs): super(ImageDataSerializer,self).__init__(*args,**kwargs) myimage = self.initial_data['data'] with Image.open(myimage) as myimage: self.fields['extension'].initial = myimage.format self.fields['image_type'].initial = myimage.mode # Update the extension and image_type initial values class Meta: model = models.ImageData exclude = ['height','width'] What happens is my image file get corrupted and in the response I am getting the message "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have also tried determining the extension and mode within the view and pass it to request.data dictionary but accessing the image file once using Pillow.Image.open() is later corrupting it. -
Python/Django - Acumulative variable with two or more models
Im new in python/django and first of all sorry for this dumb question... but I have a view with something like this: index = 0 try: TableA.objects.get(usuario=request.user) index = index + 1 except TableA.DoesNotExist: index = index + 0 try: TableB.objects.get(usuario=request.user) index = index + 1 except TableB.DoesNotExist: index = index + 0 [...] I wanted that index was acumlative. I understand why this is not working. But how can i do that? -
How to use a get function as a field in a Django Model?
I have a model A like this: class A(models.Model): ... ... def get_total(self): return (self.item_set.total - self.discount) # This returns a integer I can access this using object.get_total() function. But i want to use this function as a field name. something like this, A.objects.aggregate(Sum(get_total())) # not working A.objects.values_list('get_total()') # not working How can i call that function as a field like this?