Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting started with the Stripe API
I want to add customer to customer payment in my project so I decided to go with Stripe API. But the documentation after "getting started" has a lot of stuff and seems confusing to me. Is there a proper way or sequence to follow it? I'd like to do it in Django -
how to solve this error ValueError: unicode object contains non latin-1 characters in django? [closed]
I want to show a message in Persian language when the user logs out of the account, but I receive this error: ValueError: unicode object contains non latin-1 characters The message I want to display is: شما خارج شدید How should I solve this problem? thanks -
Can Django handle two related post requests in succession? And The input from the first post will be saved and used for the second post
I have tried to build a web application that return the calories of a type of food. I use an API for pulling information and representing to the users. After seeing the result, if the users decide that she/he wants this food information to be stored in the dataset for future reference, they will save it. I want all this process to be wrapped inside one template and one view base fucntion and I have tried something like this: My model: class Ingredient(models.Model): MEASUREMENT=[('ml','ml'), ('gram','gram')] name=models.CharField(blank=False, max_length=200) quantity=models.DecimalField(blank=False, max_digits=8,decimal_places=0,default=100) measure=models.CharField(blank=False,max_length=4,choices=MEASUREMENT,default='gram') calories=models.DecimalField(blank=False,null=False,decimal_places=2,max_digits=8,default=0) def __str__(self): return self.name My views: from django.shortcuts import render from django.http.response import HttpResponseRedirect, HttpResponse from .models import Ingredient from .forms import IngredientForm import requests, json import requests import json api_url = 'https://api.calorieninjas.com/v1/nutrition?query=' def ingredient_form(request): add=False kcal=0 if request.method == 'POST': name=str(request.POST.get('name')) if Ingredient.objects.filter(name=name).exists(): track=Ingredient.objects.filter(name=name) add=True for val in track: if val.measure==str(request.POST.get('measure')): add=False amount=float(request.POST.get('quantity')) kcal=(amount/float(val.quantity))*float(val.calories) break if add==True: query = str(request.POST.get('quantity')) + ' '+str(request.POST.get('measure'))+' ' + str(request.POST.get('name')) response = requests.get(api_url + query, headers={'X-Api-Key': 'ZwDpQLeGgrYKVgNd7UE7/Q==ZwxlN5PK4cfBMhua'}) data = response.json() if len(data['items'])==0: return HttpResponse('Does not exits') else: kcal = float(data['items'][0]['calories']) else: add=True query = str(request.POST.get('quantity')) + ' '+str(request.POST.get('measure'))+' ' + str(request.POST.get('name')) response = requests.get(api_url + query, headers={'X-Api-Key': 'ZwDpQLeGgrYKVgNd7UE7/Q==ZwxlN5PK4cfBMhua'}) data = response.json() if … -
Changing User image in updating time in django
I am making User Profile for learning. in updating time user default image doesn't change. but username and email change to new username and email.only user image don't change. if I change profile image form admin page, it will change. but from Update page don't change. I can't find problem where is it. sorry for grammar mistakes :) /models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default='user.png', upload_to='static/images') def __str__(self): return self.user.username def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) /forms.py from django import forms from .models import UserProfile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserForm(UserCreationForm): class UpdateUser(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'email') class UpdateProfile(forms.ModelForm): class Meta: model = UserProfile fields = ('image', ) /views.py from .models import UserProfile from django.contrib import messages from django.shortcuts import render, redirect from .forms import UserForm, UpdateUser, UpdateProfile from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate, logout # Create your views here. def Home(request): if request.user.is_authenticated: user = request.user user, … -
Django import-export with FK constraint
I have been attempting to import data into my Django project using Django import-export. I have two models Ap and Job, Job has a FK relationship with Ap. Using the Admin, I can select the file and the type, CSV. So far my program seems to run, but gets hung up on the FK. I'm close, something is off and causing the import script to fail. Models.py class Ap(models.Model): line_num = models.IntegerField() vh = models.IntegerField() vz = models.IntegerField() status = models.CharField( choices=statuses, default="select", max_length=40) classified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Job(models.Model): aplink = models.ForeignKey(Ap, related_name=( "job2ap"), on_delete=models.CASCADE) job_num = models.IntegerField() description = models.CharField(max_length=200) category = models.CharField( choices=categories, default="select", max_length=40) status = models.CharField( choices=statuses, default="select", max_length=40) dcma = models.BooleanField(default=False), due_date = models.DateField(blank=True), created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py class ImportView(View): def get(self, request): form = ImportForm() return render(request, 'importdata.html', {'form': form}) def post(self, request): form = ImportForm(request.POST, request.FILES) job_resource = JobResource() data_set = Dataset() if form.is_valid(): file = request.FILES['import_file'] imported_data = data_set.load(file.read()) result = job_resource.import_data( data_set, dry_run=True) # Test the data import if not result.has_errors(): job_resource.import_data( data_set, dry_run=False) # Actually import now else: form = ImportForm() return render(request, 'importdata.html', {'form': form}) resource.py class CharRequiredWidget(widgets.CharWidget): def clean(self, … -
Single page pdf usinng headless chrome
I want to create a pdf from HTML as a single page pdf The tech's that I have been using is Chrome headless Django Python Now the currently when we try to use chrome headless it prints the HTML file as a multiple pages Problem We want to have a single page pdf rather then having a multiple page pdf Note By single page pdf i don't mean that it should just print the first page Any help or guidance will be a great help and thanks in advance -
Digitalocean space access denied
I created a digital ocean storage space. The url of the space is as https://storagespace.nyc3.digitaloceanspaces.com However, when I click on the url to open on the browser I get the following error: <Error> <Code>AccessDenied</Code> <BucketName>storagespace</BucketName> <RequestId>tx000000000000001618a5e-0081246af3-1805687a-nyc3c</RequestId> <HostId>1805987a-nyc3c-nyc3-zg03</HostId> </Error> I have no idea what this error means or why I'm having it. I connected the s3 bucket with my django website and the static files are not being served to the browser as well, instead I get 403 forbidden error. Please how do I remove this access denied error? -
How to say "yes" to collectstatic prompt
I am trying to deploy a django app by Elastic Beanstalk. In my container-commands.config file, container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic <- What to do? option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: practice-ecommerce-app.settings When i ran eb deploy, I got errors, and following is cfn-init-cmd.log 2021-08-24 03:39:31,949 P14507 [INFO] -----------------------Command Output----------------------- 2021-08-24 03:39:31,950 P14507 [INFO] 2021-08-24 03:39:31,950 P14507 [INFO] You have requested to collect static files at the destination 2021-08-24 03:39:31,950 P14507 [INFO] location as specified in your settings. 2021-08-24 03:39:31,950 P14507 [INFO] 2021-08-24 03:39:31,950 P14507 [INFO] This will overwrite existing files! 2021-08-24 03:39:31,950 P14507 [INFO] Are you sure you want to do this? 2021-08-24 03:39:31,950 P14507 [INFO] 2021-08-24 03:39:31,950 P14507 [INFO] Type 'yes' to continue, or 'no' to cancel: Traceback (most recent call last): 2021-08-24 03:39:31,950 P14507 [INFO] File "manage.py", line 22, in <module> 2021-08-24 03:39:31,950 P14507 [INFO] main() 2021-08-24 03:39:31,950 P14507 [INFO] File "manage.py", line 18, in main 2021-08-24 03:39:31,950 P14507 [INFO] execute_from_command_line(sys.argv) 2021-08-24 03:39:31,950 P14507 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line 2021-08-24 03:39:31,950 P14507 [INFO] utility.execute() 2021-08-24 03:39:31,950 P14507 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute 2021-08-24 03:39:31,950 P14507 [INFO] self.fetch_command(subcommand).run_from_argv(self.argv) 2021-08-24 03:39:31,951 P14507 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/base.py", … -
dj-rest-auth: ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION not working
I'm using dj-rest-auth, allauth, and simple jwt to implement authentication. In django-allauth, setting ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION=True will automatically login user after the email is verified. But posting key to "/dj-rest-auth/registration/verify-email/" only returns {"detail":"ok"}. The source code below explains why: # allauth class ConfirmEmailView(TemplateResponseMixin, LogoutFunctionalityMixin, View): # ... def post(self, *args, **kwargs): # ... if app_settings.LOGIN_ON_EMAIL_CONFIRMATION: resp = self.login_on_confirm(confirmation) if resp is not None: return resp # this is a HttpResponseRedirect object # ... # dj-rest-auth class VerifyEmailView(APIView, ConfirmEmailView): # ... def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.kwargs['key'] = serializer.validated_data['key'] confirmation = self.get_object() confirmation.confirm(self.request) return Response({'detail': _('ok')}, status=status.HTTP_200_OK) Since I'm using JWT, how could I override this view to login user after verification and return access code? -
Add and delete buttons while using formset
I am using django formsets along with a form. On submitting everything is working fine. I want to add "Add New" and "Delete" button for the formset fields. My code looks like: Views.py: def create_food_menu(request): restaurant = Restaurant.objects.get(id=request.user.restaurant.id) form = FoodMenuForm(restaurant) FoodMenuPortionFormset = modelformset_factory(FoodMenuPortion, form=FoodMenuPortionForm, extra=1) food_menu_portion_formset = FoodMenuPortionFormset(queryset=FoodMenuPortion.objects.none(), prefix="food_menu_portion_formset" ) if request.method == 'POST': form = FoodMenuForm(restaurant, request.POST, request.FILES) food_menu_portion_formset = FoodMenuPortionFormset(request.POST, prefix="food_menu_portion_formset") if form.is_valid() and food_menu_portion_formset.is_valid(): food_menu = form.save() food_menu.restaurant = restaurant unique_filename = image_converter(request.POST.get("imagebase64"), 'food_menu/image/') food_menu.image = unique_filename food_menu.save() for item in food_menu_portion_formset: food_menu_portion_obj = item.save(commit=False) food_menu_portion_obj.food_menu = food_menu food_menu_portion_obj.save() addons = item.cleaned_data['addons'] for addon in addons: food_menu_portion_obj.addons.add(addon) food_menu_portion_obj.save() messages.success(request, 'Food Item Added Successfully.') return redirect('list_food_menu') else: pass context = { "title": "add food item", 'food_menu_form': form, "food_menu_portion_formset": food_menu_portion_formset } return render(request, "food_menu/food_menu.html", context) models.py: class FoodMenu(models.Model): name = models.CharField(max_length=20) menu_sub_category = models.ForeignKey(MenuSubCategory, on_delete=models.CASCADE) logo = models.ImageField(upload_to='food_menu/logo') image = models.ImageField(upload_to='food_menu/image', default='main/default.jpg') vegetarian = models.BooleanField(default=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) availability = models.BooleanField(default=False) description = models.TextField(max_length=500, blank=True, null=True) class Meta: db_table = TABLE_PREFIX + "food_menu" def __str__(self): return self.name class FoodMenuPortion(models.Model): unit = models.CharField(max_length=20) food_menu = models.ForeignKey(FoodMenu, on_delete=models.CASCADE, related_name='food_menu_portion') price = models.DecimalField(max_digits=10, decimal_places=2) tax = models.DecimalField(max_digits=10, decimal_places=2) available_from = models.TimeField(null=True, blank=True) available_to = … -
How to change the option attribute of a select using Django forms
I have the following Django form (truncated): from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['category', 'type'] widgets = { 'expense_category': forms.Select( attrs={ 'class': 'form-control', } ), 'expense_type': forms.Select( attrs={ 'class': 'form-control', } ), } This is the html rendered: <select name="expense_category" class="form-control" multiple="" id="id_expense_category"> <option value="A" selected>A</option> <option value="B">B</option> <option value="C">C</option> </select> <select name="expense_type" class="form-control" multiple="" id="id_expense_type"> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> Desired result: <select name="expense_type" class="form-control" multiple="" id="id_expense_type"> <option class="category_a" value="1" selected>1</option> <option class="category_b" value="2">2</option> <option class="category_c" value="3">3</option> </select> In short, I would like to add the 'class' attribute to the select options, but I don't know how. I have found solutions on stackoferflow from 2011 but it looks like it is already deprecated. model.py(truncated): from django.db import models from django.contrib.auth.models import User from project.models import Project from expense.constants import * class Expense(models.Model): user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) expense_category = models.CharField( choices=EXPENSE_CATEGORY, default=EXPENSE_STAFFING_PAYMENTS, max_length=200, ) expense_type = models.CharField( choices=EXPENSE_TYPE, default=EXPENSE_PRINTER_LEASE, max_length=200, ) -
save data in editable table to database
I have a web app, backend using Django and frontend using HTML5. Restful API(Django rest framework) is used for GET, PUT, POST and DELETE data types. In the HTML page, I have an editable table, which is supposed to save whatever edited content to database. How could I achieve that? HTML5 page: <table id="thisTable" contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;" id="bk-table" data-toggle="table" data-toolbar="#toolbar" data-cookie="true" data-cookie-id-table="materialId" data-show-columns="true" data-show-refresh="true" data-show-fullscreen="true" data-show-export="true" data-height="650" {# data-sticky-header="true"#} {# data-sticky-header-offset-left="7em"#} {# data-sticky-header-offset-right="7em"#} data-click-to-select="true" data-id-field="id" data-show-footer="true" data-url="/api/materials/" data-query-params="queryParams" data-remember-order="true" data-pagination="true" data-side-pagination="server" data-total-field="count" data-data-field="results"> <thead class="thead-dark" > <tr contenteditable='true'> <!--th data-sortable="true" >ID</th--> <th data-field="courseCode" data-formatter="renderCourse">Course Code</th> <th data-field="type">Course Type</th> <th data-field="school">School</th> <th data-field="discipline.name">Discipline</th> <th data-field="discipline.hop1">HOP Name</th> <th data-field="discipline.hop1_email">HOP Email</th> <th data-field="discipline.executive">Executive Name</th> <th data-field="discipline.executive_email">Executive Email</th> </tr> </thead> </table> rest.py: class MaterialSerializer(serializers.ModelSerializer): book = BookSerializer(many=False) course = CourseSerializer(many=False) # should not use SemesterCourseSerializer this because it also include books # setting allow_null True so that this field always present in the output, otherwise it will not present when null # that cause datatable alert error when render missing field. school = serializers.ReadOnlyField(source='course.courseInfo.school.name', allow_null=True) #courseCode = serializers.ReadOnlyField(source='course.courseInfo.code') courseId = serializers.ReadOnlyField(source='course.courseInfo.id') year = serializers.ReadOnlyField(source='course.semester.year') month = serializers.ReadOnlyField(source='course.semester.month') term = serializers.ReadOnlyField(source='course.semester.term') quota = serializers.ReadOnlyField(source='course.quota') type = serializers.ReadOnlyField(source='course.courseInfo.type') available = serializers.ReadOnlyField(source='course.courseInfo.available') … -
Merge two Django query sets and deduplicate objects sharing a common value
I have a Django project using a segmentation library and need to merge two query sets and deduplicate the resulting query set, which is causing me to scratch my head over how to do so. not_segments = Page.objects.all().no_segments() (paraphrased) gives me pages with segment pages excluded. only_segments = Segment.objects.get_queryset().for_user(user=user) (paraphrased) gives me segmented page objects from the same model, but of course there are overlaps. not_segments = Page 1, Page 2, Page 3, Page 4 only_segments = Page 2 (for user), Page 4 (for user) So let’s say there’s a guid field in the model which is not enforced as unique, but rather identical in value between a root page and its segment child page. How do I compare the objects of the two query sets when merging them and omit objects from not_segments if an object with the same guid exists in only_segments? To get at the desired result of queryset = Page 1, Page 2 (for user), Page 3, Page 4 (for user) -
Django and React Google cloud deployment
I have a website that uses Django for the backend and React for the frontend and i want to make my website ready for customers. what are the step i should take to make my application production ready? what settings in react or Django should i change? what do i do with static files? what do i do with the database? should use something like Nginx? how do i make sure my app is secure? should i even use google cloud or is there a better alternative for my application like AWS or something similar? -
Shopify API to get All Records for Customers,Orders & Products (Django)
I have searched for getting all customer one by one.But after some study understand the whole way to solve. for getting 250 data from shopify api we can use limit but pagination and synchronization for getting all data we need some step to get all data. shop_url = "https://%s:%s@%s.myshopify.com/admin/api/%s/" % (API_KEY, PASSWORD, SHOP_NAME, API_VERSION) endpoint = 'customers.json?limit=250&fields=id,email&since_id=0' r = requests.get(shop_url + endpoint) Step 1:Where we need to put the initial id to start extraction and store to your db customers.json??limit=250&fields=id,email&since_id=0 Step 2:Next changes the since_id value with with last id of your extraction like my image. last id=5103249850543 (suppose) Mentioned in Fields Data customers.json??limit=250&fields=COLUMN_YOUNEED_FOR_CHK&since_id=5103249850543 -
Django Python Google Social Auth: django.db.utils.ProgrammingError: relation "account_emailaddress" does not exist
I am super new here so don't roast me. I keep getting this error: django.db.utils.ProgrammingError: relation "account_emailaddress" does not exist For context, I am running a django application and am trying to run "manage.py migrate account" in order to use Google Social Authentication. After trying to sign up with google, it gives me this error as well: relation "account_emailaddress" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "account_emailaddress" -
How to change the option attribute of a select using Django forms
I have the following Django form (truncated): from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['category', 'type'] widgets = { 'category': forms.Select( attrs={ 'class': 'form-control', } ), 'type': forms.Select( attrs={ 'class': 'form-control', } ), } And this is the html rendered: <select name="category" class="form-control" multiple="" id="id_category"> <option value="A" selected>A</option> <option value="B">B</option> <option value="C">C</option> </select> <select name="type" class="form-control" multiple="" id="id_type"> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> And this is the desired result: <select name="type" class="form-control" multiple="" id="id_type"> <option class="category_a" value="1" selected>1</option> <option class="category_b" value="2">2</option> <option class="category_c" value="3">3</option> </select> In short, I would like to add the 'class' attribute to the select options, but I don't know how. I have found solutions on stackoferflow from 2011 but it looks like it is already deprecated. -
AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator'
I'm using Python v3.8.5 and Django v3.2.6. When I type in "models.py" this code : image = models.ImageField(null=True, blank=True) But it was shows : AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator'. The full error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 1271, in check *cls._check_fields(**kwargs), File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 1382, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\files.py", line 384, in check *self._check_image_library_installed(), File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\files.py", line 389, in _check_image_library_installed from PIL import Image # NOQA File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 43, in <module> import defusedxml.ElementTree as ElementTree File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\defusedxml\ElementTree.py", line 62, in <module> _XMLParser, _iterparse, _IterParseIterator, ParseError = _get_py3_cls() File "C:\Users\dhibh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\defusedxml\ElementTree.py", line 56, in _get_py3_cls _IterParseIterator = pure_pymod._IterParseIterator AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator' Why I am getting this error ? Thanks in advance. -
Django-OpenCV : Invalid number of channels in input image:
I want to upload an image to my django backend and have the images treated and prepared for OCR before it is saved. However for some images i get this error : Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1 i tried to run the processing pipeline on jupyter and used the same image and the error didn't show up so maybe when saving the image to the ImageField this error is being produced however i can't fix it. here is the processing code (preprocessing.py) from cv2 import cv2 import numpy as np from matplotlib import pyplot as plt def process_image(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (9, 9), 0) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 5)) dilate = cv2.dilate(thresh, kernel, iterations=5) # Find all contours contours, hierarchy = cv2.findContours(dilate, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key = cv2.contourArea, reverse = True) # Find largest contour and surround in min area box largestContour = contours[0] minAreaRect = cv2.minAreaRect(largestContour) # Determine the angle. Convert it to the value that was originally used to obtain skewed image angle = minAreaRect[-1] if angle < -45: angle = 90 +angle elif (angle>-45)and(angle<=0): angle=angle elif … -
How to Read a Specific sheet from an Excel File Using Django
I'm reading an xlsx file to store the data in the database. Everything is working correctly. But my question is that I want to read only one specific spreadsheet from the Excel file. For example, a file can have multiple sheets like: Sheet1, Sheet2 ... I want to read data only from Sheet2 and store in database. At the moment I'm doing it as follows: imported_data = dataset.load(data.read(), format='xlsx') However, this way it does not filter a specific sheet. How can I do this? After I put each line of sheet in database.. -
How do I create a nested json format in django rest serializer?
Currently I have this format in the api "inner_divertor": { "volume": 5.2, "volume_units": "m^2", "volume_notes": "xyz" }, "outer_divertor": { "volume": null, "volume_units": "m^3", "volume_notes": null } I'm trying to add a nested "volume" variable "inner_divertor": { volume:{ "volume": 4.3, "volume_units": "m^2", "volume_notes": "xyz" } }, "outer_divertor": { volume:{ "volume": null, "volume_units": "m^3", "volume_notes": null} } class InnerDivertorSerializer(FlexFieldsModelSerializer): class Meta: model = InnerDivertor fields = ( 'volume', 'volume_units', 'volume_notes') class OuterDivertorSerializer(FlexFieldsModelSerializer): class Meta: model = OuterDivertor fields = ( 'volume', 'volume_units', 'volume_notes') -
Django with Oracle DB - ORA-19011: Character string buffer too small
I have the following model for an Oracle database, which is not a part of my Django project: class ResultsData(models.Model): RESULT_DATA_ID = models.IntegerField(primary_key=True, db_column="RESULT_DATA_ID") RESULT_XML = models.TextField(blank=True, null=True, db_column="RESULT_XML") class Meta: managed = False db_table = '"schema_name"."results_data"' The RESULT_XML field in the database itself is declared as XMLField. I chose to represent it as TextField in Django model, due to no character limit. When I do try to download some data with that model, I get the following error: DatabaseError: ORA-19011: Character string buffer too small I figure, it is because of the volume of data stored in RESULT_XML field, since when I try to just pull a record with .values("RESULT_DATA_ID"), it pulls fine. Any ideas on how I can work around this problem? Googling for answers did not yield anything so far. -
Why ListStyle plugin doesn't show up in my CKEditor in Django website?
As seen here, I have two more extraPlugins, which do show up on the Website. The problem is liststyle only. Am I supposed to add anything to the toolbar list? 'NumberedList' and 'BulletedList' are already there, and I thought liststyle was supposed to override them. As you can see, the liststyle is again not seen here, although field and codesnippet are. I have also downloaded the plugin dependencies for liststyle. Is there anything else I need to do? -
Data in templates
I need your support. I have 2 models Author and Post, I want to display the data for a particular author in a template. I want display the posts of an specific Author, and the information (first_name and last_name) of that Author. In my view file I created a method, with 2 querysets. One of this QuerySet looks in the table Post the posts of an specific Author, and the other query set looks in the Author table the information of the Author owner of the posts. My question, Can I do this with only one QuerySet? If yes, How can I display it in the template? MODELS class Autor(models.Model): first_name = models.CharField(max_length=30, null=False, verbose_name='First Name') last_name = models.CharField(max_length=30, null=False, verbose_name='Last Name') class Post(models.Model): autor = models.ForeignKey(Autor, on_delete=models.CASCADE) post = models.CharField(max_length=200, null=False, verbose_name='Post') VIEW.PY def index(request): autor = Autor.objects.filter(first_name='Peter').first() autor_posts = Post.objects.filter(autor__first_name='Peter') return render(request, 'posts.html', {'autor_posts': autor_posts, 'autor': autor}) POSTS.HTML Author: {{ autor.first_name }}, {{ autor.last_name }} Posts: {% for post in autor_posts %} <p>{{ post.id }}, {{ post.post }}</p> <p></p> {% endfor %} -
Why can't I run "python manage.py startup APP_NAME" with django?
I'm trying to build a Django app, but it doesn't let me startup the app so I can bring it to the development server. I run python manage.py startup APP_NAME, where I expect the app to run. Instead, I get an error saying there is no such file or directory called manage.py. However, I have it open. Is there a reason for this?