Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django upload file size limit and restriction
I have a form in my app where users can upload files so how can i set a limit to the uploaded file size and type ? **models.py** class Document(models.Model): emp = models.ForeignKey(Emp, null=True, on_delete=models.SET_NULL) Description = models.CharField(max_length=100, null=True) Fichier = models.FileField(upload_to='file/') data_created = models.DateTimeField(auto_now_add=True, null=True) **forms.py** class documentForm(ModelForm): class Meta: model = Document fields = '__all__' exclude = [] **view.py** def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) -
Web socket disconnecting after stablishing a connection
I got a web socket connection that I perform with django channels, my app works perfectly fine in local, but when trying to run it on the vps, the web socket gets disconnected right after stablishing a connection with a 1005 code const socket = new WebSocket('wss://mydomain.com/ws/chat/testing/'); I was sending a message to the backend in socket.onopen() function, but that was not the problem since after commenting that line of code, the connection gets also closed The nginx configuration file looks like this: location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8115; } Django routing.py: application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('chat/testing/', Chat().as_asgi()) ]) ) ) }) Setting.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I don't know if relevant but when using const socket = new WebSocket('wss://mydomain.com:8115/ws/chat/testing/'); I got a connection failed with code 1006 -
try block is working but except block is not handling error in python
While Handling Python dictionary key error except block is not working but try block is working. Below is my code def catch_empty_key(a): try: return 'aaaa' except : return 'bbbb' def zohoapicall(accesstoken): accesstoken = "" if accesstoken == "": parameters = { "refresh_token":"1000.06f10f49d6f00478887e3820634b928f.c045ff2a9dcb9c99057ec42645bf1e44", "client_id":"1000.UKZQIWVQ2A2THKSZ2126Y7E7CAA8CW", "client_secret":"91d25fbaeea0e81190a681708cd554a1030a9c4547", "redirect_uri":"https://www.google.com", "grant_type":"refresh_token", } response = requests.post("https://accounts.zoho.com/oauth/v2/token?", params=parameters) if response.status_code == 200: data = response.json() accesstoken = data['access_token'] headers = { 'Content-Type':'application/json', 'Authorization':'Zoho-oauthtoken ' + str(accesstoken) } response = requests.get("https://books.zoho.com/api/v3/invoices", headers=headers) if response.status_code == 200: data1 = response.json() data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] return HttpResponse(data_2, accesstoken) Here in the second last line data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] except block of catch_empty_key function is not working and it is throwing an error. On the Other hand if I replace second last line with something that is a key of invoice then try block is working and returning aaa as output. for example data_2=[catch_empty_key(invoice['is_a_key']) for invoice in data1['invoices']] I want to understand why this error is coming and how can we solve it? -
Authentication returns None in django rest frame work API
views.py @api_view(['POST']) def login(request): data = {} email = request.data.get('email') password = request.data.get('password') user = authenticate(email = email, password = password) U = User.objects.get(email=email) if user is not None: login(request, user) data['response'] = 'successfully logged in' elif Userprofile.objects.filter(email=email).exists() == False: data['response'] = 'user does not exist' elif U.is_active == False: data['response'] = 'Please verify your email' else: data['response'] = 'invalid password' return JsonResponse(data) otp=random.randint(11111,99999) @api_view(['POST']) def signup(request): serializer = UserprofileSerializer(data=request.data) data = {} if serializer.is_valid(): name = serializer.validated_data['name'] email = serializer.validated_data['email'] phone_number = serializer.validated_data['phone_number'] password = make_password(serializer.validated_data.get('password')) account = Userprofile.objects.create_user(name = name, email = email, phone_number = phone_number, password = password) data['response'] = 'successfully registered a new user' send_mail( 'Welcome to Trycompound', 'Your OTP is '+str(otp), EMAIL_HOST_USER, [email], ) user = User.objects.get(email=email) user.otp = otp user.save() else: data = serializer.errors return JsonResponse(data) I really can'f figure what's wrong because I have actually done these with the normal templates and when i tried it with the django rest framework, I am unable to login because authenticate is returning 'None'. and yes User is active, it says 1 in the database. -
issues with Docker on wsl (ubuntu 22.04)
An attempt to build a docker image fails on RUN pip install -r requirements.txt step with the following error: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ for some reason, asgiref==3.5.2 doesn't want to install. What could be the reason for this? System used: OS: Windows 11 WSL 2 with Ubuntu 22.04 on board Docker version 20.10.19, build d85ef84 Dockerfile contents: # Pull base image FROM python:3.10.6-slim-bullseye # Set enviroment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . requirements.txt contents: asgiref==3.5.2 Django==4.1.2 sqlparse==0.4.3 -
how to get foreignkey names instead of sql reference number django view
Im trying to build a simple rest api in django. i have a transaction, account and stock table. Each transaction points to 1 account and 1 stock(on seperate tables using foreign keys). im trying to have my api gets the stock ticker for each transaction and not the sql reference number. does anyone know how to get simple views to return values instead of table keys? the serializers im using: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = "__all__" class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = "__all__" class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = "__all__" the models for transaction and stock: class Stock(models.Model): ticker = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.ticker class Transaction(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) amount = models.IntegerField() price = models.FloatField() type = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.account im leaving out the account/user model but its a mess and half tied into the django base user model the view im using is a basic APIVIEW: class TransactionView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (JWTAuthentication,) def get(self, request, *args, **kwargs): account = Account.objects.get(email=request.user.email) transactions = Transaction.objects.filter(account=account) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) … -
Relative links to admin.py
There is a class in admin.py: class NewsAdmin(TranslationAdmin): form = NewsForm list_display = ('title', 'date' 'show_url') def show_url(self, obj): return format_html("<a href='http://www.host.ru/news/{url}' target='_blank'>view</a>", url=obj.id) show_url.short_description = "View" Need a link http://www.host.ru replace with a relative one, something like this: protocol + domain name + news/{url} How can this be done? -
ModelChoiceFIeld Usage and what to include in queryset?
I cannot seem to figure out why my ModelChoiceField is not working, even after going through the django documentation about ModelForm which confused me despite having successfully relied on them throughout my learning. The error in my code is probably silly, and I apologize for that in advance. The error I get on my terminal when trying to makemigrations is: 'line 429, in getattr raise AttributeError(name) from None AttributeError: objects' forms.py from random import choices from django import forms from .models import Student from students.choices import * class StudentForm(forms.ModelForm): class Meta: model = Student fields = '__all__' #imports all of Student model's fields labels = { 'student_number': 'Student Number', #changes how the attribute names are presented to the user 'first_name': 'First Name', 'last_name': 'Last Name', 'email': 'Email', 'english': 'English', 'math': 'Math', 'language': 'Language', 'science': 'Science', 'ib_predicted': 'Predicted IB Score' } widgets = { 'student_number': forms.NumberInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'english': forms.ModelChoiceField(queryset=English.choices), 'science': forms.ModelChoiceField(queryset=Science.objects.all()), 'language': forms.ModelChoiceField(queryset=Language.objects.all()), 'math': forms.ModelChoiceField(queryset=Math.objects.all()), 'ib_predicted': forms.NumberInput(attrs={'class': 'form-control'}) } choices.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ class English(models.TextChoices): LANGLIT = 'LL', _('Language and literature') LIT = 'L', _('Literature') class Math(models.TextChoices): AA = 'AA', _('Analysis … -
Django Rest Framework Serializer PrimaryKeyRelatedField pass in uuid list
So, I am trying to make a social media application and users can tag other users in their post. class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) caption = models.CharField(max_length=100, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) allow_comments = models.BooleanField(default=True) archived = models.BooleanField(default=False) media_file_url = models.FileField(upload_to='videos/', validators=[validate_file_extension]) tags = TaggableManager(blank=True, through=TaggedHashtag) mentioned_users = models.ManyToManyField(User, blank=True, through='MentionedUser') class MentionedUser(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) tagged_user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = (('post', 'tagged_user')) ordering = ['date_created'] For serializing the uuids for the mentioned_users, I followed these instructions. Everything works fine, I can submit one uuid correctly like this: But when I try to submit more than one uuids, I get this error: Here is my serializer: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() mentioned_users = serializers.PrimaryKeyRelatedField(many=True, allow_null=True, queryset=User.objects.all(), pk_field=serializers.UUIDField(format='hex')) id = serializers.CharField(read_only=True) class Meta: model = Post fields = [ 'caption', 'allow_comments', 'media_file_url', 'id', 'tags', 'mentioned_users', ] What am I doing wrong here? What is the correct way to submit list of uuids? Also, is the present method I am using efficient, any form of help would be appreciated. Thank You. Also, I tried adding double quotes … -
Django Formset not correctly populating form data
I am trying to set up a page where a Return can be made to an order, with as many ReturnItems as needed. The empty forms for additional ReturnItems are generated by JavaScript passing in the empty form HTML string created by the formset factory. When the forms are properly filled in, it works as expected. However, when I try to submit with multiple ReturnItems forms being empty, the validation of the forms do not work properly. What I don't understand is that even though the request.POST data is correct the 'reason' and 'opened' field are not populated for the forms which causes the forms to be empty and skipped, instead of raising a ValidationError for missing the product name/code. Any help or suggestions would be useful, thanks. Example of request.POST data <QueryDict: {'csrfmiddlewaretoken': ['token'], 'first_name': ['first'], 'last_name': ['last'], 'email': ['e@email.com'], 'telephone': ['12345'], 'order_id': ['123'], 'order_date': ['2022-10-05'], 'form-TOTAL_FORMS': ['2'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['1'], 'form-MAX_NUM_FORMS': ['15'], 'form-0-product_name': ['prod1'], 'form-0-product_code': ['code1'], 'form-0-quantity': ['2'], 'form-0-reason': ['1'], 'form-0-opened': ['False'], 'form-1-product_name': ['prod2'], 'form-1-product_code': ['code2'], 'form-1-quantity': ['3'], 'form-1-reason': ['1'], 'form-1-opened': ['False'], 'comment': ['comment']> Views.py def return_view(request): sitekey = settings.H_CAPTCHA_SITEKEY ReturnItemFormSet = formset_factory( ReturnItemForm, extra=0, min_num=1, max_num=15, validate_min=True, absolute_max=15, ) return_form = ReturnForm() return_item_formset = ReturnItemFormSet() empty_form … -
Django: How to use CreateView in one model and at the same time update a field in a second model. (Using a form in templates only)
I couldn't find a direct answer elsewhere. I created a Group Model and a GroupMember Model. My goal is that a user creates a Group via a form in templates, then automatically in the GroupMember model the fields should be filled. In particular the field is_admin should be 1, although its default value is set to 0. How to tell CreateGroupView to fill the GroupMember model? views.py class CreateGroupView(LoginRequiredMixin, CreateView): fields = ("name","description") model = Group class SingleGroupView(DetailView): model = Group class ListGroupView(ListView): model = Group models.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User,through="ProjectMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE,) group = models.ForeignKey(Group, related_name="memberships",on_delete=models.CASCADE,) is_admin = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") my template to create a Group <form class="m-5" method="POST" action="{% url 'groups:create' %}" id="groupForm"> {% csrf_token %} <div class="form-group"> <label for="id_name">Name</label> <input type="text" name="name" maxlength="255" class="form-control" placeholder="Name" title="" required id="id_name"> </div> <div class="form-group"> <label for="id_description">Description</label> <textarea name="description" cols="40" rows="10" class="form-control" placeholder="Description" title="" id="id_description"></textarea> </div> <input type="submit" value="Create" class="btn btn-primary btn-large"> </form> the urls.py urlpatterns = … -
Possible Unhandled Promise Rejection (id: 0): [AxiosError: Network Error] - React Native and Django
I'm trying to get the data from Django backend for my React Native project but im getting this error Possible Unhandled Promise Rejection (id: 0): [AxiosError: Network Error] im new to react native and django but ive done this before in react js but i dont know why i cant get it to work here Here's My React Native Code import React, { useState, useEffect } from "react"; import axios from "axios"; import { StyleSheet, ScrollView, View, Text } from "react-native"; // Components import ProductCard from "../components/ProductCard"; export default function HomeScreen({ navigation }) { const [products, setProducts] = useState([]); useEffect(() => { async function fetchProducts() { const { data } = await axios.get("http://127.0.0.1:8000/api/products/"); setProducts(data); } fetchProducts(); }, []); return ( <View style={styles.container}> <ScrollView style={styles.scrollView}> {products.map((product) => ( <View style={styles.productsContainer}> <ProductCard product={product} navigation={navigation} /> </View> ))} </ScrollView> </View> ); } I also added these to settings.py INSTALLED_APPS = [ "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] CORS_ALLOW_ALL_ORIGINS = True -
Integrate Stripe payment flow into django
I’m trying to integrate stripe custom payments flow into my Django ecom website as PayPal isn’t as good but the docs (https://stripe.com/docs/payments/quickstart?lang=python) for python are in the flask framework. Does anyone have boilerplate code for handling a simple transaction for this in Django (views, template etc.) -
ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb'
What is the new import for: ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb' I did some internet searching and didn't find an immediate result for the error. I am trying to upgrade from django 3.2 to django 4.1.2 -
Django Group by multiple times
In my Django models, I have class Tracker(models.Model): grade = models.ForeignKey(Grade, on_delete=models.CASCADE) teacher = models.ForeignKey(User, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) BREAK_TYPE_CHOICES = [ ('1', 'Toilet Pass'), ('2', 'Hall Pass'), ('3', 'Doctor Pass'), ] break_type = models.CharField(max_length=10, choices=BREAK_TYPE_CHOICES) start_date_time = models.DateTimeField(auto_now_add=True) end_date_time = models.DateTimeField(auto_now=True) status = models.BooleanField(default=False) I need to find all the breaks given in a day, group by teachers with a break up on the basis of break type. Currently, I can get breaks given in a day and group them by teachers. breaks_today = Tracker.objects.filter(status=True, start_date_time__gte=date_from, end_date_time__lte=date_to) breaks_today = breaks_today.values('teacher').order_by('teacher').annotate(count=Count('teacher')) How do I proceed with the next step, i.e. group by break types, then group by teacher? -
how to get over all kms using property method in django for render into templates?
Greeting developers,Actually i want to render overall km travel by particular vehicle from using @property method in django model . here is my models class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) date = models.DateField(default=timezone.now, blank=True, null=True) and related to that models i have onther models class Logsheet(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets") trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, default=0.0) distance_to = models.FloatField(blank=True, null=True, default=0.0) time_from = models.TimeField(blank=True, null=True) time_to = models.TimeField(blank=True, null=True) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) doeking_km = models.FloatField(blank=True, null=True, default=0.0) def save(self, *args, **kwargs): self.doeking_km = int(float(self.distance_to)) - int(float(self.distance_from)) super(Logsheet, self).save(*args, **kwargs) where is doeking km is daily kms .. Problems I want to render over all km travel by particual vehicle using @property method so i can easily render it templates help me guys. -
Django Unit Testing - How to test all instances in a model?
I want to test all instances in a DB using Django. I have a python script that populates the DB and I want to test every single instance if it pass the test. I provide here a dummy tests.py: from django.test import TestCase from app_core.models import Item # Item model fields are: pk, first, second class PairTestCase(TestCase): def setUp(self): # This script populates the DB creating several Item instances from app_core.init import init_items def test_pair_elems_different(self): """First and second fields MUST be different inside the instance""" item = Item.objects.get(pk=1) self.assertNotEqual(item.first, item.second) As you can see, I just tested a single instance. Let's suppose the DB contains 1000 Item instances, what is the best way to test them all? The only solution that pops up in my mind is using a simple FOR loop inside test_pair_elems_different, iterating all object and comparing each instance. Is this approach correct in the context of unit testing best practices/principles? -
Complex query to calculate user balance
I have the following model (that is simplified): class CoinTransaction(models.Model): class TransactionTypes(Enum): purchase_of_coins = ('pu', 'Purchase of Coins') # Will have a positive amount conversion_into_money = ('co', 'Conversion Into Money') # Will have a negative amount earning = ('ea', 'Earning') # Will have a positive amount expense = ('ex', 'Expense') # Will have a negative amount @classmethod def get_value(cls, member): return cls[member].value[0] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions') amount = models.IntegerField() transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes]) I want a query to get two values related to a given user: earned_coins and other_coins, without saving their value into the User model. The query should calculate these values exactly like this: earned_coins = 0 other_coins = 0 for transaction in CoinTransaction.objects.filter(user=user).order_by('creation_date'): amount = transaction.amount if transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('conversion_into_money'), CoinTransaction.TransactionTypes.get_value('earning')]: earned_coins = max(earned_coins + amount, 0) elif transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('purchase_of_coins'), CoinTransaction.TransactionTypes.get_value('expense')]: other_coins += amount if other_coins < 0: earned_coins = max(earned_coins + other_coins, 0) other_coins = 0 -
ValueError when using Django Model to import data from file into legacy database
I would like to use Django’s models to import data from newly arriving files into a legacy database. This should happen in the background whenever the user opens the main page of my app. Unfortunately, I am stuck with an “ValueError: Cannot assign "'Student_2": "Exam.student_id" must be a "Student" instance.” I know there are plenty of questions regarding how to solve this error but I still cannot figure out how to solve this in my case. I am not allowed to change anything about the legacy database and I have no influence on the format of the new files. This is how my database looks like: Here are some example data: This is how a file with new data looks like: This is how my models look like: class School(models.Model): school_id = models.CharField(primary_key=True, max_length=100) class Meta: managed = False db_table = 'school' class Student(models.Model): student_id = models.CharField(primary_key=True, max_length=100) school_id = models.ForeignKey('School', models.DO_NOTHING, db_column='school_id') class Meta: managed = False db_table = 'student' class Exam(models.Model): result_id = models.CharField(primary_key=True, max_length=100) grade = models.CharField(max_length=100, blank=True, null=True) student_id = models.ForeignKey('Student', models.DO_NOTHING, db_column='student_id') class Meta: managed = False db_table = 'exam' This is how I try to import the data: new = new_file.txt result_id = linecache.getline(new, … -
How to get value error of datetime in python for an if statement
I'm currently making an appointment app as a hobby and working on a portion of my app where when a user clicks on a day it returns all appointments they have for that day. I'm using datetime in the django filter and noticed a small bug. ValueError: day is out of range for month Pretty much my code in brief looks like this: dateArr = selected_date.split('-') startDate = datetime.datetime(int(dateArr[0]), int(dateArr[1]), int(dateArr[2]), 0, 0, 0, tzinfo=timezone.utc) endDate = datetime.datetime(int(dateArr[0]), int(dateArr[1]), int(dateArr[2]) + 1, 0, 0, 0, tzinfo=timezone.utc) I know I could write a helper function that checks to see if it's the last day of a month and then also add 1 to the month, or reset month to 1 if its dec 31. But is there a way to get the value code for datetime errors to use in an if statement? I looked through the docs but don't see anything. maybe value codes are a python thing and I should be looking somewhere else? thanks in advance! EDIT*** Think i found the answer to my own question here - https://docs.python.org/3/tutorial/errors.html - for anyone from the future. -
ReadingFile' object has no attribute 'get_text_from_image'
I have a python Django application. And I want to filter some sub text from extracted text. So this is how my views.py looks like: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: print("Now its type is ", type(name_of_file)) print(uploadfile.image.path) # reading PDF file if uploadfile.image.path.endswith('.pdf'): content = ExtractingTextFromFile.filterAnanas(self) # ENDING Reading pdf file else: with open(os.path.join(settings.MEDIA_ROOT, uploadfile.image.path)) as f: content = f.read() return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) and this is class: ExtractingTextFromFile.py class ExtractingTextFromFile: def extract_text_from_image(filename): text_factuur_verdi = [] pdf_file = wi(filename=filename, resolution=300) all_images = pdf_file.convert('jpeg') for image in all_images.sequence: image = wi(image=image) image = image.make_blob('jpeg') image = Image.open(io.BytesIO(image)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) return text_factuur_verdi def __init__(self ): # class variables: self.apples_royal_gala = 'Appels Royal Gala 13kg 60/65 Generica PL Klasse I' self.ananas_crownless = 'Ananas Crownless 14kg 10 Sweet CR Klasse I' self.peen_waspeen = 'Peen Waspeen 14x1lkg 200-400 Generica BE Klasse I' self.tex_factuur_verdi = [] def make_pattern(substr): return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n" def filterAnanas(self): … -
How to declare and get an output parameter in store procedure in Django?
I am trying to work with store procedures. So far I am able to work with input parameters and is successfully able to retrieve records or insert etc. Now, I have a store procedure that requires an output parameter @Id. The goal is to insert a record in the database using the store procedure which I am able to that. The issue, however, I am facing is that I am not being able to get the @Id. I am using MsSQL database. I have tried various ways to get the @Id output, but it gives an error. This is the code: cursor.execute("DECLARE @Id int; exec proc_jobcardInsert @Id = @Id OUTPUT, @Stocknumber='"+Stocknumber+"', @Modalnumber='"+Modalnumber+"'") cursor.fetchone() I have also tried it like this: cursor.execute("exec proc_jobcardInsert @Stocknumber='"+Stocknumber+"', @Modalnumber='"+Modalnumber+"'") cursor.fetchone() And I also tried cursor.fetchone()[0] All of them are not working. I also one or two other things but all gives me an error stating: django.db.utils.ProgrammingError: No results. Previous SQL was not a query Data is being inserted into the database but I want the @Id at the end. Please guide me as how to achieve it and what am I doing wrong here. -
Razorpay signature verification fail even after passing all the data correctly - Django
I am trying to verify the signature with razorpay. I am receiving the data required for the verification correctly from the frontend and also passing the data correctly to the utility.verify_payment_signature(). The code is as below # setup razorpay client this is the client to whome user is paying money that's you client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_SECRET_ID)) # razorypay information razorpay_payment_id = request.data.get('razorpay_payment_id','') razorpay_order_id = request.data.get("razorpay_order_id",'') razorpay_signature = request.data.get('razorpay_signature','') # this is for verification of razorpay params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': razorpay_payment_id, 'razorpay_signature': razorpay_signature, } check = client.utility.verify_payment_signature(params_dict) if check == None: #code else: #fail_payment The tutorial from which I learnt this says if the verification is successful the check should return None but instead the check is returning True, hence, failing the payment. I am unable to understand what is actually the problem. Please suggest me a solution -
AttributeError at /website/tbt.html 'User' object has no attribute 'get'
I am trying to generate a pdf from data taken by the user. in this case it contains a few fields as shown in models. It gives me an error after I hit the submit button my models.py tbt_date = models.DateField( verbose_name="Date of Creation", default=timezone.now ) selected_site = models.ForeignKey( sites_data, verbose_name="Choose a site", on_delete=models.CASCADE ) selected_block = models.ForeignKey( blocks_list, verbose_name="Choose a block", on_delete=models.SET_NULL, null=True ) tbt_report_img1 = models.ImageField( upload_to="formImages/TBT/", verbose_name="Upload Image 1" ) tbt_report_img2 = models.ImageField( upload_to="formImages/TBT/", verbose_name="Upload Image 2" ) rt_pdf = models.FileField(upload_to='pdfs/', verbose_name='PDF File', null=True) my views.py tbt_form_view = tbt_report_form() context = { "loggedInUser": request.user, "tbt_form":tbt_form_view, } return context #@login_required(login_url="user_login") def generate_tbt_report(request, t_form, selected_form, filename): selected_site = t_form.selected_site selected_block = t_form.selected_block selected_site_data = sites_data.objects.filter(name=selected_site)[0] tbt_date = t_form.tbt_date print(tbt_date) params = { "selected_site": selected_site_data, "tbt_date": tbt_date, "selected_block": selected_block, "t": t_form, "data": selected_form, "loggedInUser": request.user, } template_path = "website/tbt_report_pdf.html" temp_pdf = render_to_pdf(request, template_path, params, filename) return temp_pdf @login_required(login_url="user_login") def tbt_form(request): if request.method == "POST": t_form=tbt_report_form(request.user, request.POST, request.FILES) t_form.full_clean() print("in post") if t_form.is_valid(): print("Valid") t_form = t_form.save() filename='TBT' + ' ' + str(t_form.tbt_date) + ' ' + str(t_form.selected_block) + '.pdf' pdf = generate_tbt_report(request, t_form, filename) cv_get = tbt_report.objects.get(id = t_form.id) cv_get.rt_pdf.save(filename, File(BytesIO(pdf.content))) print("Saved") return pdf else: print("1") print(t_form) messages.error( request=request, message="Please … -
django: build a class based view that set a session object and call another view
is possible to build a class based view that set a session object and call another view? I did this with a form, but I need to set a session object just calling a url. Thanks