Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value Error: Cannot query "post": Must be "UserProfile" instance
I am getting the Value Error: Cannot query "post": Must be "UserProfile" instance when I make a get request to call PostListView.as_view(). Here is my model.py : from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=30) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() password = models.CharField(max_length=100) def __str__(self): return self.user.username class Post(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) title = models.CharField(max_length=100) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py : class PostListView(ListAPIView): serializer_class = PostSerializer permission_classes = [AllowAny] def get_queryset(self): """Returns only the object related to current user""" user = self.request.user return Post.objects.filter(user=user) Also, I want a Foreign key relationship exists between User and Post on Model-level, not on the Database level. -
Save .xlsx file to Azure blob storage
I have a Django application and form which accepts from a user an Excel(.xlsx) and CSV (.csv) file. I need to save both files to Azure Blob Storage. I found it to be trivial to handle the .csv file with the following code: from azure.storage.blob import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(os.getenv('STORAGE_CONN_STRING')) blob_client = blob_service_client.get_blob_client(container="my-container-name", blob=form.cleaned_data.get('name_of_form_field_for_csv_file')) blob_client.upload_blob(form.cleaned_data.get('name_of_form_field_for_csv_file'')) However, I've been unable to figure out how to save the .xlsx file. I--perhaps somewhat naively--assumed I could pass the .xlsx file as-is (like the .csv example above) but I get the error: ClientAuthenticationError at /mypage/create/ Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. I found this SO Answer about the above error, but there's no concensus at all on what the error means and I've been unable to progress much further from that link. However, there was some discussion about sending the data to Azure blob storage as a byte stream. Is this a possible way forward? I have also learned that .xlsx files are compressed so do I need to first decompress the file and then send it as a byte stream? If so, has anyone got any experience with this who … -
Why do I get TCP/IP error when trying to create DB in my Lambda?
So I'm trying to deploy my Django project using lambda, with zappa. I'm using MySQL for DB engine. Now after doing some research, I realized that I needed to create a custom Django command to create DB, since I'm using MySQL. So I created crate_db command, zappa updated, then ran zappa manage dev create_db. Then I got this error: 2004 (HY000): Can't create TCP/IP socket (97) below is my create_db.py file, for your information. import sys import logging import mysql.connector import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings rds_host = os.environ.get("MY HOST") db_name = os.environ.get("") user_name = os.environ.get("MY USERNAME") password = os.environ.get("MY PASSWORD") port = os.environ.get("3306") logger = logging.getLogger() logger.setLevel(logging.INFO) class Command(BaseCommand): help = 'Creates the initial database' def handle(self, *args, **options): print('Starting db creation') try: db = mysql.connector.connect(host=rds_host, user=user_name, password=password, db="mysql", connect_timeout=10) c = db.cursor() print("connected to db server") c.execute("""CREATE DATABASE bookcake_db;""") c.execute("""GRANT ALL ON bookcake_db.* TO 'ryan'@'%'""") c.close() print("closed db connection") except mysql.connector.Error as err: logger.error("Something went wrong: {}".format(err)) sys.exit() Any ideas? Thanks. -
How to populate OneToOne field from template side in django?
I am working on a small django-python project which has two models "staff_type" and "staff". In the staff_type model, only designation and date fields are populated. And in the staff model, there is OneToOneField relation of staff_type. Means whenever a user want to add staff first he/she will have to add staff_type and then in the staff module, user will choose the staff type (designation) from a select menu in which all the staff_type are shown respectively. Now, whenever a user select any designation (staff_type) and fill the entire form, I want to store the selected staff_type id in the staff model/table. Note: I have tried this from django admin, and it works perfectly but I want to do the same work in my own designed templates. Modles.py class staff_type(models.Model): designation = models.CharField(max_length=50) salary = models.IntegerField() datetime = models.DateTimeField() entrydatetime = models.DateTimeField( auto_now=False, auto_now_add=False) class staff(models.Model): staff_type = models.OneToOneField(staff_type, on_delete=models.CASCADE) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) fathername = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) zip = models.IntegerField(blank=True) address = models.CharField(max_length=100) contact =models.CharField(max_length=20) cnic = models.CharField(max_length=14) photo = models.ImageField() cv = models.ImageField() otherfiles = models.ImageField() views.py def add_staff_type(request): if request.method == 'POST': designation = request.POST.get('designation') salary = … -
How to connect this two check box
how to connect input and output column.When one box is checked in input column,the other check box with same name in output column should disable , both are iterated through for loop(django) -
I am getting the error : django.db.utils.IntegrityError: NOT NULL constraint failed: store_customer.email
Can anyone please help me solve this error? When I check out as a logged-in user and press the make payment button it clears the cart and does everything that it is supposed to. The problem is when I do the same for a guest user it does not clear the cart or register anything in the database. The payment button does nothing. error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\django\ecommerce\ecomm\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\django\ecommerce\ecomm\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\django\ecommerce\ecommerce\store\views.py", line 73, in processOrder customer, order = guestOrder(request, data) File "D:\django\ecommerce\ecommerce\store\utils.py", line 66, in guestOrder customer, created = Customer.objects.get_or_create( File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 588, in get_or_create return self.create(**params), True File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 1270, … -
HOW TO CREATE FILTERED DROPDOWN IN DJANGO INLINE ADMIN FORM
I am seeking to add a dropdown to an inline form in DJANGO based on the user selection. I require a PYTHONIC solution no jquery or javascript please. I have read two approaches. The first being to create a second form and override the default formset and altering the init function. The second approach to make use of the formfield_for_foreignkey option on the inline. Neither work because I can't get the context data of the form. The use-case is that I need to grab a field on the form. I then wish to use that variable to a related model variable. In have uploaded a screen-shot here of the OrderItem admin form. I wish to grab the "PRODUCT" line on the orderitem. Using that instance of the PRODUCT I then want to access the "packaging" variable of that product instance. The issue I run into is that neither option described above provides easy access to the form values. Code is below: RELEVANT MODELS class OrderItem(models.Model): rx_written = models.DateField(default=datetime.date.today) order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) doctor = models.ForeignKey(Practitioner, on_delete=models.CASCADE, blank=True, null=True) pet = models.ForeignKey(Pet, on_delete=models.CASCADE, blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) tax = models.DecimalField(max_digits=10, decimal_places=2, … -
how to send image file from requests after getting it from post api
i am creating post writing project. when user upload image it send that image to django with POST request and after that i want to send that image to IMGUR from same post django api with my access_token because i want to key my credentials private. because i dont want to store image to my django server. but i cant send image to IMGUR directly because of accss token. #My javascript code, django post request var myHeaders = new Headers(); myHeaders.append("Authorization", "Bearer mytokennnnnnnnnnnnnnnnnnnnnn"); var formdata = new FormData(); formdata.append("upload", fileInput.files[0], "/C:/mypc/myname/Downloads/unsplash.png"); var requestOptions = { method: 'POST', headers: myHeaders, body: formdata, redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/image/upload/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); #my django api code class ImageUploadView(APIView): permission_classes = [ AllowAny ] parser_classes = [MultiPartParser, FormParser] def post(self, request): url = "https://api.imgur.com/3/upload" payload={} headers = {'Authorization': 'Bearer mytokennnnnnnnnnnnnnnnnnnnnnnn'} files=request.data['upload'] response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text) return Response({"data":response.text}) my error for (k, v) in files: ValueError: too many values to unpack (expected 2) help me, how can i implement this logic -
Why do I get 502 error when deploying with Zappa? [closed]
So I'm trying to deploy my Django project with Zappa. I've done zappa install and zappa init, and now tried zappa deploy. Everything works fine, except the following error : Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.. I've done some research and was advised to try zappa tail to see the log. However, all I see is [DEBUG] and can't find any [ERROR]s. What do you think is the problem? Thanks in advance. -
django filtering optimization
I have a large database and want to filter it based on some optional values from user. This is the listview class all_ads(generic.ListView): paginate_by = 12 template_name = 'new_list_view_grid-card.html' def get_queryset(self): usage = self.request.GET.get('usage') status = self.request.GET.get('status') last2week = datetime.datetime.now() - datetime.timedelta(days=14) last2week_q = Q(datetime__gte=last2week) status = status.split(',') if usage: usage = usage.split(',') else: usage = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] intersections = list(set(status).intersection(usage)) result = models.Catalogue.objects.defer( "ads_json_html", "description" ).filter(last2week_q).order_by('-datetime') cat_ids = result.only('city', 'district').filter( Q(*[Q(city__contains=x) for x in city_district], _connector=Q.OR) | Q(*[Q(district__contains=x) for x in city_district], _connector=Q.OR) ).values_list('pk', flat=True) result = result.filter(pk__in=cat_ids) typ_ids = result.only('type').filter(type__in=intersections).values_list('pk', flat=True) result = result.filter(pk__in=typ_ids) return result models.py: class Source(models.Model): name = models.CharField(max_length=100, unique=False) def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name class Catalogue(models.Model): source = models.ForeignKey(Source, db_index=True, null=False, on_delete=models.CASCADE) city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) datetime = models.CharField(db_index=True, max_length=100, null=True) description = models.TextField(null=True) ads_json_html = models.TextField(null=True) def __str__(self): return self.source_token There are some other fields in Catalogue. The problem is filtering work fast on small database, but it is slow on large database. If I return result after last2week_q filter, it takes just 800 ms to filter and render template; But with cat_ids and typ_ids filtering, it … -
Problems with the Django Admin. Doesn't show Users section
Can anyone tell me why is it that I don't see the "Users" section within Authentication and Authorization? If you need more code, please let me know. I honestly don't know what happened, always in all my Django projects, when I create the Superuser and enter the url '/ admin', there is the Users section. I don't know what could be wrong. I appreciate your help ♥ models.py from django.db import models from django.db.models import Count from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver terminal log [11/Jul/2021 02:18:44] "GET / HTTP/1.1" 200 6606 [11/Jul/2021 02:18:48] "GET /admin/ HTTP/1.1" 302 0 [11/Jul/2021 02:18:49] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 2267 [11/Jul/2021 02:18:57] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 [11/Jul/2021 02:18:57] "GET /admin/ HTTP/1.1" 200 5483 [11/Jul/2021 02:19:13] "GET /admin/auth/ HTTP/1.1" 200 2910 admin.py from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from cerveceria.models import * -
How do I create a bidding system using django?
I am currently interested in making a website that functions similar to freelancer.com. In the platform, I want to have two types of users: employers and employees. When an employer posts a job using a django model form, for example, someone looking for article writing services, it becomes visible to employees to bid. When the employer picks one employee, the job becomes invisible to other employees. It becomes a private communication between the employer and the employee. I am stuck in creating the bidding system. I don't know which django (python) function to use for bidding to display all the functions I have stated. I can so far create a job django model and employer forms to post the jobs to the available list of jobs on the website. I don't know what to do next for employees to start bidding on the job. I also want to know the python function I can use so that when the order is marked completed, the employee can no longer upload new files. Please advise. -
How to reconcile shared applabel in two third party apps in django?
I have a large django project I am working on, that is largely based around the wagtail CMS. I recently added the django-wiki app to my project, and ran into issues running makemigrations, getting the error: "Application labels aren't unique, duplicates: sites " It seems both wagtail and django-wiki have apps and applables called 'sites', which is causing a conflict. Given that these apps are not my apps, renaming them as though they were would seem like a bad approach, causing issues whenever I were to upgrade. What is the correct approach to deal with this problem without breaking the packages? -
Custom User Model with multiple Unique id - Django RestFramework
Hi StackOverFlow buddies, I have created a custom User model for my project and would like to register the Users with Restframework. I want Custom User model to have 2 unique fields together, for which I followed "Official doc" for unique_together property. It seems to be only taking only 1 field (ie email for my case), as a unique one. Relevant piece my code until this point looks like this: PS: Let me know if more info is required. models.py class MasterUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) firstname = models.CharField(max_length=100,blank=True) contact = models.CharField(max_length=100, blank=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname'] class Meta: unique_together = (('email', 'contact'),) serializer.py password2 = serializers.CharField(style={'input_type': 'password'}, write_only= True) class Meta: model = MasterUser fields = ('firstname', 'password', 'password2', 'email','contact') extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = MasterUser( email = self.validated_data['email'], firstname = self.validated_data['firstname'], contact = self.validated_data['contact'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password doesnt matches'}) account.set_password(password) account.save() return account views.py @api_view(['POST']) def registration_view(request): if request.method == "POST": serializer = RegisterUserSerializer(data= request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = "Successfully registered new user!" else: data = serializer.errors return Response(data) Where … -
Errno 111 Connection refused Django REST on CPanel
I'm using gmail smtp, and I get this error: [Errno 111] Connection refused I'm getting this on cpanel shared hosting, but it's working perfectly fine on local. Here's my Django configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = config("EMAIL_HOST") EMAIL_PORT = 587 EMAIL_HOST_USER = config("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD") EMAIL_FROM = config("EMAIL_FROM") DEFAULT_FROM_EMAIL = 'email@gmail.com' SERVER_EMAIL = 'email@gmail.com' EMAIL_BCC = "" EMAIL_USE_SSL = False I contacted my WHM and told them to disable smtp restrictions. Their firewall is also not blocking gmail's smtp and the required ports are also open. Please help me. -
Django JQuery autocomplete not working - nothing showing up, but API URL works
I have tried to implement autocomplete exactly as this tutorial shows: https://www.youtube.com/watch?v=-oLVZp1NQVE Here is the tutorial code, which is very similar to what I have here: https://github.com/akjasim/cb_dj_autocomplete However, it is not working for me. The API url works, but nothing populates in the field, i.e. there is no autocomplete that shows up. What could I be doing wrong? Here is the jquery: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#product").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> Here is the html: <title>Autocomplete</title> </head> <body> <form> <label for="product">Product</label> <input type="text" name="product" id="product"> </form> Here is the views: def autocomplete(request): if 'term' in request.GET: qs = Model.objects.filter(title__icontains=request.GET.get('term')) titles = list() for product in qs: titles.append(product.title) # titles = [product.title for product in qs] return JsonResponse(titles, safe=False) return render(request, 'file_for_viewing.html') Then here is the URL: path('autocomplete',views.autocomplete, name='autocomplete'), -
Issue connecting to secure websocket using Django/Nginx/Daphne
Having an issue using secure websocket (wss) with django, Nginx, Gunicorn, and daphne. My site is hosted through cloudflare which provides the SSL/TLS certificate. I'm using a linux socket in /run/daphne/daphne.sock, where I gave the user 'ubuntu' ownership of the daphne folder. The websockets work fine locally when it is not secured. When I tried hosting on my EC2 instance, I get the error- sockets.js:16 WebSocket connection to 'wss://www.mywebsite.com/ws/sheet/FPIXX8/' failed: Then it keeps trying to reconnect and fail again. It never sets up an initial connection since I don't get a ping. Here are a few relevant files and snippets of code- settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', # asgi_redis.RedisChannelLayer ? 'CONFIG': { 'hosts': [('localhost', 6379)], }, } } I think there may be an issue with the 'hosts' but I haven't been able to figure out through tutorials/googling, nor am I sure exactly what it does besides set a port. Since I'm using sockets, I imagine this would need to be different (or maybe it's ignored?) in deployment. Routing.py (in main project dir) from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( … -
Executing a multitable SQL query using a Django QuerySet
I'm working in a Django project and I would like to know how a data like that SELECT cities.name, states.name, countries.name FROM cities JOIN states ON states.id = cities.state_id LEFT OUTER JOIN countries ON countries.id = states.country_id WHERE cities.name = 'Guadalajara'; could be retrieved using the Django ORM (I mean using a model's query set and its filters). I'm not very experienced using ORMs and I'm much better in SQL. But I have to create similar queries in Django. What is the best way to do it? -
How to dynamically filter with get_queryset on one of many queries based on if-logic using gt (greater than), lt
I have 3 dropdown boxes that allow the user to pass a parameter (1), operator (2), criteria (3) e.g "price (1) greater (2) than 200 day simple moving average (3)". I am overriding the get_queryset function from my views.py file and testing with user entering the query above into the dropdown boxes. The outcome I am seeking is simply to be able to catch all of the possible combinations in if-statements and only return the relevant filtered query that matches the 3 conditions selected. In my code below the intial queryset = TableData.objects.all() remains as the query set even if I do reach the other filtering conditions in my if-statement. def get_queryset(self, *args, **kwargs): #global queryset #tried making this global but it didn't work queryset = TableData.objects.all() req = self.request.GET ajax_requests = req.getlist('filterList[]') for req in ajax_requests: parameter = "" operator = "" criteria = "" yourdict = json.loads(req) filter = yourdict[0] parameter = filter['parameter'] operator = filter['operator'] criteria = filter['criteria'] if parameter == 'priceAnchor': # The user selected to compare price as the first option if operator == 'ltOption': # The user wants to see price less than a third attribute if criteria == 'sma200Criteria': #TableData.objects.filter(price__lt=F('ma200')) queryset = TableData.objects.filter(volume__gt=100000000) … -
'powershell.exe' is not recognized as an internal or external command, operable program or batch file
I am using Windows 10, and Windows Powershell as command terminal. I just started to learn Django framework and being trying to setup my env as 1st time practice. This is my location: PS C:\Users\MyUsername\Desktop\cfeproj> This was successful: python -m pipenv install However, when I run : pipenv shell PS C:\Users\LENOVO\desktop\proj> pipenv shell Launching subshell in virtual environment... 'powershell.exe' is not recognized as an internal or external command, operable program or batch file. Please help me ho to configure this problem. I'm basically very new and still learning. Would be so appreciate if somebody can help me out here. =D -
Save a file from requests using django filesystem
I'm currently trying to save a file via requests, it's rather large, so I'm instead streaming it. I'm unsure how to specifically do this, as I keep getting different errors. This is what I have so far. def download_file(url, matte_upload_path, matte_servers, job_name, count): local_filename = url.split('/')[-1] url = "%s/static/downloads/%s_matte/%s/%s" % (matte_servers[0], job_name, count, local_filename) with requests.get(url, stream=True) as r: r.raise_for_status() fs = FileSystemStorage(location=matte_upload_path) print(matte_upload_path, 'matte path upload') with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) fs.save(local_filename, f) return local_filename but it returns io.UnsupportedOperation: read I'm basically trying to have requests save it to the specific location via django, any help would be appreciated. -
Why do I get "AttributeError: 'Template' object has no attribute 'add_description'" error when deploy with Zappa?
So I'm trying to deploy my Django project with zappa. I've installed, and init-ed successfully and now trying to deploy. However, after zappa deploy, I get the following error: AttributeError: 'Template' object has no attribute 'add_description'.What do you think is the problem? Full error message is: Traceback (most recent call last): File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 3422, in handle sys.exit(cli.handle()) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 588, in handle self.dispatch_command(self.command, stage) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 630, in dispatch_command self.deploy(self.vargs["zip"], self.vargs["docker_image_uri"]) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 960, in deploy endpoint_configuration=self.endpoint_configuration, File "c:\users\user\envs\synergy\lib\site-packages\zappa\core.py", line 2417, in create_stack_template self.cf_template.add_description("Automatically generated with Zappa") AttributeError: 'Template' object has no attribute 'add_description' -
how to create a file dynamically with OCR result from an image model
i created two apps in django one to upload a file and process it and one to preform OCR and create a pdf file from the processed image. so i have two models one for images and another for files, when i upload an image it goes through the processing pipeline then automatically the file field in the File model is populated with the result. When i m working with the admin panel or with DRF api root it is working fine, but when i use POSTMAN or react Native front end i get internal server error and the image is uploaded but no file is created. I m still learning django and backend concepts so i don't even know where to look for the issue: here are my models class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=100,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) super(Uploads, self).save(*args, **kwargs) if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.txt') )) class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) label=models.CharField(max_length=100, default='none') title=models.CharField(max_length=200,default='test') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) import PIL.Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def Create_Pdf(image): text=pytesseract.image_to_string(PIL.Image.open(image)) return(text) -
Docker build error Could not find a version that satisfies the requirement Django
I'm just learning Docker and working with django from last 1 year. Today I try to work with docker and getting this error. ERROR: Could not find a version that satisfies the requirement Django<3.2.2 I'm familiar with this error. But with docker i don't know how to solve this. Dockerfile Configuration: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user requirements.txt Django >=3.2.5,<3.2.2 djangorestframework>=3.12.4,<3.9.0 see the error message image here can anyone help me how to fixed this ? -
Django is not updating my database after submitting my form
I have created a model and a form, both are working correctly, and I have added data to the database using the admin module models.py class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) lastname = models.CharField(blank=True, max_length=15) company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company") position = models.CharField(blank=True, max_length=15) country = CountryField(blank_label='(select country)') email = models.EmailField(blank=True, max_length=100, default="this_is@n_example.com") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) phone = PhoneField(default="(XX)-XXX-XXX") def __str__(self): return f'{self.firstname}' forms.py class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('firstname', 'lastname',"position",'country','email','phone') views.py @login_required def add_client(request): if request.method == "POST": client_form = ClientForm(instance=request.user, data=request.POST) if client_form.is_valid(): client_form.save() messages.success(request, 'You have successfully added a client') else: messages.success(request, "Error Updating your form") else: client_form = ClientForm(instance=request.user) return render(request, "account/add_client.html", {'client_form':client_form}) add_client.html {% extends "base.html" %} {% block title %}Client Information {% endblock %} {% block content %} <h1> Client Form</h1> <p>Please use the form below to add a new client to the database:</p> <form method="post" enctype="multipart/form-data"> {{ client_form.as_p }} {% csrf_token %} <p><input type="submit" value="Save changes"></p> </form> {% endblock %} Everything seems to be working fine, I can submit data in the website and I get a message stating that the the submission when fine, however, when I check the admin website and inspect the database, …