Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keep active tab after reload
I'm trying to keep active tab after reload using bootstrap and JS, but something goes wrong. I don't know whether i put script in wrong place or code is broken. Thanks for help! Code below: HTML_base <!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> {% block title %} {% endblock title %} <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" type='text/css' href="{% static 'post/style.css' %}"> <script type="text/javascript" src="{% static 'post/javatab.js' %}"></script> </head> <body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-git.js"></script> </body> </html> HTML_detail <ul class="nav nav-tabs card-header-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="PL-tab" data-toggle="tab" href="#PL" role="tab" aria- controls="PL" aria-selected="true">PL</a> </li> <li class="nav-item"> <a class="nav-link" id="RU-tab" data-toggle="tab" href="#RU" role="tab" aria-controls="RU" aria-selected="false">RU</a> </li> </ul> Javatab $(function() { $('a[data-toggle="tab"]').on('click', function(e) { window.localStorage.setItem('activeTab', $(e.target).attr('href')); }); var activeTab = window.localStorage.getItem('activeTab'); if (activeTab) { $('#myTab a[href="' + activeTab + '"]').tab('show'); window.localStorage.removeItem("activeTab"); } }); SETTINGS.PY STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
I am new to django and when I am trying to python manage.py runserver... I was getting an error below... what I have to do now? please let me know
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
aws lambda django app deployed with zappa - pythin import precendecy
We have a Django application we deploy on AWS Lambda, using Zappa. We use pipenv to manage python packages of the project. Some packages we use (e.g cryptography) need to be compiled with the same configration as the lambda machine. To do that, I've generated wheels for those packages on a similar machine, and included them in a sub folder in the directory. So here is our deployment process now: install packages with pipenv (which also includes those special packages) extract precompiled wheels in a special directory run zappa deploy command So after this, we have two versions of those packages, one installed via pipenv, and one extracted manually from precompiled wheels. The reason for this is, I still want the project to be able to run locally (using the package installed via pipenv, and not using the precompiled ones). So I want local versions of the project to use packages installed via pipenv, but want Lambda to use extracted - precompiled version. I've added the directory where we keep precompiled packages to PYTHONPATH environment variable, but as far as I can see, zappa puts all python packages installed via pipenv in the root folder of the project. Those have … -
Django relationships in Models
I have a big confused of using relationship in models. I have this database that contains Data (see Image) Database organisation image I have many fields. Every field have some element attached to it (wells). Every well is unique and if allocated to one field. The well have many data for every element (Info, Petro, Geo and Tests) Every data is attached to a service that can add and modify. Every Service can manage one data. Every Service has manager and some users. I wrote a code but I don't know when I use relationships types. like ForeignKey, ManyToManyField...... My code : from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse # Create your models here. class Fields(models.Model): Fieldname = models.CharField(max_length=15) DiscoveredDate= models.DateField(max_length=4) #YYYY Mechanisms = models.CharField(max_length=15)# OBSERVATION = models.TextField() post_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.Fieldname def get_absolute_url(self): return reverse('Fields', args=[self.pk]) class Meta: ordering=('-post_date',) class Wells(models.Model): WellID = models.ManyToManyField(max_length=15,related_name='Fields') # or I use ForeignKey TYPE = models.CharField(max_length=35) Startdate = models.DateField(max_length=35) # date with format mm-dd-YY EndDate = models.DateField(max_length=15) # date with format mm-dd-YY Duration = models.IntegerField(max_length=4) # enteger supervisor = models.CharField(max_length=30) OBSERVATION = models.TextField() post_date = models.DateTimeField(default=timezone.now) author = … -
How to add red asterisk to form field if the field fails to validate?
If a form field fails to validate, Django will display a helpful message (e.g. "This field is required"). However, in addition to the helpful message, I also want to display a red asterisk next to the form field itself if there are any validation errors for the field. Something like: Excerpt from my template: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"/> </form> I know I can insert the asterisk using manual form rendering, but I am looking for a way to do this without editing the template. Is there a way to do this? Perhaps it can be done by overriding specific form.Form methods? -
input Csv models.FileField into pandas object
I have model Field instance. myCsv = myFile.objects.get(id=1) // myCsv.document is models.FileField and want to put this in pandas. df = pd.read_csv(thred.document.read()) OSError: Expected file path name or file-like object, got <class 'bytes'> type How can I put the cev file to pandas object?? -
How can I fetch object from ForeignKey with date after now in Django?
I have the following models: class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) class Flight(models.Model): date = models.DateTimeField(default=datetime.now, blank=True, verbose_name="Data") flight_id = models.CharField(max_length=10, verbose_name="Ref. Voo") company = models.ForeignKey(AirCompany, null=True, on_delete=models.SET_NULL, verbose_name="Companhia") airport = models.ForeignKey(Airport, null=True, on_delete=models.SET_NULL, verbose_name="Aeroporto") class Trip(models.Model): trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem", primary_key=True) destination = models.CharField(max_length=200, null=True, verbose_name='Destino') client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") Knowing that both Flight and Clients are a ForeignKey in Trip, how can I fetch all the clients who have flights after now? I used Going = Flight.objects.filter(date__gt=datetime.now()).order_by('date') to get all the flights leaving after now, but I also need to get which clients are going after now. -
Blur image with easy_thumbnails
How to blur an image with this logic in the Django model. @property def get_small_url_port(self): return DOMAIN + get_thumbnailer(self.image).get_thumbnail({ 'size': (75, 100), 'box': self.cropping_port, 'crop': 'smart', # 'upscale': True, }).url -
Django Logging Error in format : KeyError : ‘classname’
Extra context cannot set with given log format which is defined in settings.py and I am using APIs are responding and even logs are generating in the log file if we remove %(classname)s()] %(token)s %(router_macid)s %(user_email)s %(device_macid)s From the format then it is working fine without and error, i am using django==2.1, djangorestframework==3.10.3 Error --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.6/logging/__init__.py", line 994, in emit msg = self.format(record) File "/usr/lib/python3.6/logging/__init__.py", line 840, in format return fmt.format(record) File "/usr/lib/python3.6/logging/__init__.py", line 580, in format s = self.formatMessage(record) File "/usr/lib/python3.6/logging/__init__.py", line 549, in formatMessage return self._style.format(record) File "/usr/lib/python3.6/logging/__init__.py", line 391, in format return self._fmt % record.__dict__ KeyError: 'classname' Call stack: File "/usr/lib/python3.6/threading.py", line 884, in _bootstrap self._bootstrap_inner() File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/usr/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 154, in handle handler.run(self.server.get_app()) File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 183, in finish_response self.close() File "/usr/lib/python3.6/wsgiref/simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent File "/usr/lib/python3.6/http/server.py", line 536, in log_request self.requestline, str(code), str(size)) File "/usr/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 124, … -
How to render django-easy-audit logs in django template
I recently installed django-easy-audit in my app. At the moment, it is rightly showing all logs in the admin dashboard, however, I wish to have these logs rendered to my django template. Is there a way around this? -
json field in django-haystack with elasticsearch engine
How can I store json in elasticsearch by django-haystack fields now I use this trick: # search_indexes.py class BlogPostIndex(indexes.SearchIndex, indexes.Indexable): author = indexes.CharField() @staticmethod def prepare_author(obj): return json.dumps(serializers.UserMinimalSerializer(obj.author).data) # serializers.py class BlogPostSearchSerializer(HaystackSerializer): author = serializers.SerializerMethodField() @staticmethod def get_author(obj): return json.loads(obj.author) but by this trick search not working in json data -
How to upload files to GAE through form data post in Django?
I have my django webapp that contains a method in one of my models to upload the user chosen file (from form) to a specified file directory. But i am not able to use the model after i have deployed my app on Google App Engine (using gcloud). I am using the Google MySQL db for my django app. Also, I am not able to use os.makedir() method in my app as the server prompts there is Read-Only-Permission MODELS.PY def upload_to(instance, filename): now = timezone_now() base, ext = os.path.splitext(filename) ext = ext.lower() rootpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) return rootpath + f"/face_detector/static/face_detector/img/{now:%Y%m%d%H%M%S}{ext}" # Do add the date as it prevents the same file name from occuring twice # the ext is reserved for the file type and don't remove it class PicUpClass(models.Model): picture = models.ImageField(_("picture"), upload_to=upload_to, blank=True, null=True) I am a rookie in python so please suggest me some basic solutions. -
How to specify html tag attributes in Django auto-generated ModelForms?
I am new to Django and was wondering how to specify html tag attributes like class = "" or id = "" in ModelForms ? Also, if there is any workaround to AJAX in Django, allowing me to dynamically update web pages, I would be pleased to know about it. Here is my first ModelForm : class UserForm(ModelForm): class Meta: model = User fields = [ 'number', 'name', 'birth_date', 'sport_club', 'subscribe_date', 'license_number' ] -
Display blob data in django template
I'd like to display a blob on the page. I get the binary data, convert it to base64, prepare the image src attribute from the view. Then render it in the template like so: <img style="width:100%;" src="{{blob_encoded}}"> However, i get the following error: can only concatenate str (not "bytes") to str Note that i have tried this also in the template without concatenation in the view but doesn't work: <img style="width:100%;" src="data:image/jpeg;base64,{{blob_encoded}}"> My view: def display_blob(request,du_id): qs = File.objects.values('du_file').filter(du_id=du_id) enc = base64.b64encode(qs[0]['du_file']) return render(request, 'images/display.html', { 'blob_encoded': 'data:image/jpeg;base64,'+base64.b64encode(qs[0]['du_file']), }) -
Not displaying details in database even though made models ,views and ran migrations
I am not able to get the deatils of the beneficiary in the database when I fill up the form for beneficiary and husband the details of only the husband is shown in the database and the details of the beneficiary is somewhat lost.The fields of the beneficiary are all empty. <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/" enctype="multipart/form-data" id="regForm"> <div class="group"> <div class="tab"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <!--Beneficiary Details--> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="[0-9]{4}[0-9]{4}[0-9]{4}" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <input type="file" name="adhaarcopy" /> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Give consent to collect adhaar card data </label> <div class="invalid-feedback"> You … -
Best practices for storing articles' texts in django website
New to Django here, please bear with me if this question seems silly. I'm in the process of designing (and afterwards developing) a blog website. I've identified three types of page that I will have on my blog (article, home, misc) each of these having a separate template. Every new article would have its own text and images. Presumably I'd be using a single .html template to display many article texts. Do I store the article texts and images in a separate model? If so, do I store the html of the article text (with all its formatting) in plain text and then render it in the view? What's the best way to do this? Alternatively, I'd create a new template for every article, but this seems redundant. -
Get value from django form and use to find data in sql
I want the user to insert name in the form and after submitting the program goes to the DB and find certain values for this specific name and return to the user. This view.py does not work. How can i make it work and be able obj to identify id based on inserted name and go and find the specific values? view.py def home(request): if request.method == 'POST': form=PersonForm(request.POST) if form.is_valid(): form1=form.save(commit=True) name=form1.name obj=School.objects.get(id=1) context={ 'name':name, 'object':obj } return render(request, 'first/results.html', context) else: form = PersonForm() return render(request, 'first/search.html', {'object':obj}) models.py class School(models.Model): student=models.CharField(max_length=200) schgroup=models.CharField(max_length=200) class Meta: managed=False db_table='school' class Person(models.Model): name= models.CharField(max_length=150) forms.py class PersonForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput) class Meta: model = Person fields = ('name',) Could you please help me. I will be happy for any help and advise. -
Deploy Django project on Apache server Centos 7
I am pretty much a having trouble Django project on Apache server. The error says: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Here is the virtualHost <VirtualHost *:8000> DocumentRoot /var/www/reactive WSGIPassAuthorization On WSGIDaemonProcess reactive python-path=/var/www/reactive:/var/www/venv3/lib/python3.6/site-packages WSGIProcessGroup src WSGIScriptAlias / /var/www/reactive/src/wsgi.py ErrorLog /var/www/reactive/logs/error.log CustomLog /var/www/reactive/logs/custom.log combined <Directory /var/www/reactive/src> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The thing is the server pretty much working when I run the it manually. python3 manage.py runserver 0.0.0.0:8000 But when I try to make it keep running as virtualHost Then the problem above popping up. Do I missing something with the code about virtualHost:8000 here is the folder structure of venv3 and reactive folders Additionally I check the systemctl status httpd.service Feb 28 16:25:44 cpanel.example.com systemd1: Starting The Apache HTTP Server... Feb 28 16:25:44 cpanel.example.com httpd[23540]: [Fri Feb 28 16:25:44.919001 2020] [so:warn] [pid 23540] AH01574: module wsgi_module is already loaded, skipping Feb 28 16:25:44 cpanel.example.com httpd[23540]: [Fri Feb 28 16:25:44.919548 2020] [so:warn] [pid 23540] AH01574: module php7_module is already loaded, skipping Feb 28 16:25:45 cpanel.example.com systemd1: Started The Apache HTTP Server. and looked okay. -
Appropriate way to apply Django Server
I am trying to create a server. Data sent from the wireless communication device enters the database through this server. Use Message Queue to prevent data loss (VernaMQ). I wonder if Django is the right server for sending and receiving data from multiple wireless devices and if there is a problem, is there an alternative to using Django? -
How we can use redis pipeline in django-redis?
I want to use Redis pipeline (execute multiple commands) in django-redis. We can use multi and exec command in Redis but how we can in django-redis ? One solution is : I have list of hash keys i want to get all hashes using of hash key. On every iteration command send to redis server to fetch one by one hash. for hashkey in feedlist: result = con.execute_command('hgetall',hashkey) print(result) This is not a good idea instead of this we can use redis pipeline. But how i can achieve Redis pipeline in django-redis ? -
Is there a way to automatically update the models of a django app every time a webpage is requested?
I was wondering if there was a way of automatically updating models in a django app when a request is made to the webpage as I need a database to be displayed but I would like the page to be updated along with the database. I tried placing the following code in my views.py file but it only creates the models and does not update them when the database is updated.(I used pandas to get the info off of my database) from django.shortcuts import render from CollectMail.models import Details from django.http import HttpResponse import pandas as p file = p.read_csv(r"C:\Users\Robert Chomba Mumba\Desktop\Project At Access Bank 2\Emails\test_data_final.csv") n = len(file['EMAIL']) j = 0 k = 1 while j != n: NewItem = file['EMAIL'][j] NewObject = 'ID' + str(k) NewObject = Details(email = NewItem) j +=1 k +=1 def index(request): return HttpResponse(Details.objects.all()) -
p5.js and p5.sound.js does not work with different machine
i just made one front-end HTML project which take audio from user using p5.js and p5.sound.js. Everything working fine with my HTML code. but when i integrated that HTML code with my DJANGO back-end. it works fine with only same computer(localhost:8000/). But when i try to access and run django app from different machine(like 192.168.0.43:8000) it raise following error in browser console. ` ` there are following code in sketch.js let mic, fft, level1, state, soundFile, recorder; let can1; var timer = null; /** first setup the microphone **/ function setup() { state = 0; window.onbeforeunload = null; can1 = createCanvas(400, 400); can1.parent('canvas-area'); noFill(); mic = new p5.AudioIn(); mic.start(); //start mic fft = new p5.FFT(); fft.setInput(mic); } /** when mic on draw the circle on canvas **/ function draw() { background(245, 247, 250); let spectrum = fft.analyze(); // strokeWeight(2); stroke(61, 191, 232); beginShape(); if (state == 1) { for (i = 0; i < spectrum.length; i++) { vertex(i, map(spectrum[i], 0, 255, height, 0)); } } else if ($('#record').text() == 'Resume') { textSize(32); text("Resume Recordering", 40, 180) } else { textSize(32); text("Click To Start Meeting", 40, 180) } endShape(); } /** run following code when documnet is ready **/ $(document).ready(function(){ /** … -
Django-mailer - autosend not working locally (maybe: bad localhost crontab path?)
I'm new to django and I've installed django-mailer 2.0. It's working when I manually send the queued mails: (venv)$ python manage.py send_mail, but when I set up the crontab (which is the first time I use a cron job), it's not working. I guess there might be some mistakes in the paths. Official documentation of django-mailer suggests: * * * * * (/path/to/your/python /path/to/your/manage.py send_mail >> ~/cron_mail.log 2>&1) Mine: # first I tried: * * * * * (/usr/bin/python3 /Users/username/Documents/GitHub/projectname/manage.py send_mail >> ~/cron_mail.log 2>&1) # then I tried: * * * * * (/Users/username/Documents/GitHub/projectname/venv/bin/python /Users/username/Documents/GitHub/projectname/manage.py send_mail >> ~/cron_mail.log 2>&1) Neither is working.. Help please! -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__users_personal_detail.husband_adhaarcopy
I added new fields and file fields and when I ran migrations I got this error.Looks like I am getting error in a FileField .I don't know what's causing this issue.Please help! Applying users.0010_auto_20200228_1138...Traceback (most recent call last): File "C:\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__users_personal_detail.husband_adhaarcopy The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 110, in database_forwards schema_editor.add_field( File "C:\Python\Python38\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, … -
Image Encoding and Decoding. base64 String Image
'Basically I am trying to save image Captured from Camera to server. First picture is captured Converted to base 64 String and then sent to Django backend using Volley request. On django side I am using base64.decodebytes(String Name) to again convert it to image. the image is converted and saved but it is not returning a success response and the file is not being saved in the directory I want. I am using the imagefield to save image toa given path using ***** pic= models. ImageField(upload_to="Folder_name"). Kindly help me out in solving this server side error and guide me if I am not properly decoding it.' =====================Android===================== Function for Converting Image to String base64. public String getStringImage(Bitmap bm){ ByteArrayOutputStream ba= new ByteArrayOutputStream( ); bm.compress( Bitmap.CompressFormat.JPEG,100,ba ); byte[] imagebyte = ba.toByteArray(); String encode = Base64.encodeToString(imagebyte, Base64.DEFAULT ); // Toast.makeText( MainActivity.this,"String is"+encode,Toast.LENGTH_LONG ).show(); return encode; } Using Volley to send Parameters to Django: protected Map getParams() throws AuthFailureError { String image = getStringImage( photo ); Map params = new HashMap( ); Date date = new Date( ); long timeMilli = date.getTime(); params.put("IMG", image); params.put("tm", String.valueOf( timeMilli )); return params; ===============================Pycharm======================== URL: path('add_file', views.fileAdd, name='fil'), Function DEf: def fileAdd(request): pak = request.POST['IMG'] tim …