Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save user and profile with signals
Im still learning Django and I am stuck at user registration / profile creation. My goal So, the purpose of this is to save the new user and at the same time save the profile of the new user with de data from the form. I use 2 forms u_form and p_form. What I have done so far: Created model Profile with OneToOneField to User Created 2 forms for User (u_form) and Profile (p_form) Created signals.py to create new Profile when new User is created In the view I have create function with u_form.save() Problem This works, but the new Profile is completely empty.. When I put p_form.save() in my view it gives me this error: NOT NULL constraint failed The code models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) voorletter = models.CharField(max_length=10) voorvoegsel = models.CharField(max_length=10) achternaam = models.CharField(max_length=200) depers = models.CharField(max_length=25) depersoud = models.CharField(max_length=25) telefoonnummer = models.CharField(max_length=25) class Meta: verbose_name = "Collega" verbose_name_plural = "Collega's" def __str__(self): return self.depers signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if … -
Django does not gracefully close MySQL connection upon shutdown when run through uWSGI
I have a Django 2.2.6 running under uWSGI 2.0.18, with 6 pre-forking worker processes. Each of these has their own MySQL connection socket (600 second CONN_MAX_AGE). Everything works fine but when a worker process is recycled or shutdown, the uwsgi log ironically says: Gracefully killing worker 6 (pid: 101)... But MySQL says: 2020-10-22T10:15:35.923061Z 8 [Note] Aborted connection 8 to db: 'xxxx' user: 'xxxx' host: '172.22.0.5' (Got an error reading communication packets) It doesn't hurt anything but the MySQL error log gets spammed full of these as I let uWSGI recycle the workers every 10 minutes and I have multiple servers. It would be good if Django could catch the uWSGI worker process "graceful shutdown" and close the mysql socket before dying. Maybe it does and I'm configuring this setup wrong. Maybe it can't. I'll dig in myself but thought I'd ask as well.. -
Error 502 with conflicting server name and (2: No such file or directory)
Mywebsite.co.uk displays a 502 Error. Running sudo tail -F /var/log/nginx/error.log outputs: 2020/10/22 09:42:13 [warn] 200096#200096: conflicting server name "mywebsite.co.uk" on 0.0.0.0:80, ignored 2020/10/22 09:42:13 [warn] 200107#200107: conflicting server name "mywebsite.co.uk" on 0.0.0.0:80, ignored 2020/10/22 09:42:29 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:42:50 [crit] 200110#200110: *4 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 37.70.203.239, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "xxx.xx.xxx.xxx" 2020/10/22 09:42:51 [crit] 200110#200110: *4 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 37.70.203.239, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "xxx.xx.xxx.xxx" 2020/10/22 09:43:00 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:43:24 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:57:01 [crit] 200110#200110: *10 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 103.42.252.150, server: _, request: "GET / HTTP/1.0", … -
How to add part of the path before the language code for django translate i18n
How to add part of the path before the language code for django i18n_patterns ? Example: my project is located at: http://domain.site/sub/admin/ When changing the language, a redirect to http://domain.site/`en`/sub/admin/ occurs automatically , but me need to so http://domain.site/sub/`en`/admin/. Thanks! urls.py code: urlpatterns = i18n_patterns ( ... path ('admin /', admin.site.urls), ... prefix_default_language = False, ) settings.py code: LANGUAGES = [ ('en', _ ('English')), ('ru', _ ('Russian')), ] i18n_switcher.py: from django import template from django.template.defaultfilters import stringfilter from django.conf import settings register = template.Library() def switch_lang_code(path, language): lang_codes = [c for (c, name) in settings.LANGUAGES] if path == '': raise Exception('URL path for language switch is empty') elif path[0] != '/': raise Exception('URL path for language switch does not start with "/"') elif language not in lang_codes: raise Exception('%s is not a supported language code' % language) parts = path.split('/') if parts[1] in lang_codes: parts[1] = language else: parts[0] = "/" + language return '/'.join(parts) @register.filter def switch_i18n(request, language): """takes in a request object and gets the path from it""" return switch_lang_code(request.get_full_path(), language) html link for change language <a href="{{ request|switch_i18n:'en' }}"> <img class="i18n_flag" src="{% static 'images/lang-en.svg' %}"/> </a> / <a href="{{ request|switch_i18n:'ru' }}"> <img class="i18n_flag" src="{% static 'images/lang-ru.svg' %}"/> … -
How to resolve JSONDecodeError at / in Django
This is my code I have been using views.py from django.shortcuts import render import requests from django.http import HttpResponse def form(request): return render(request,'hello/index.html') def home(request): a=request.POST.get("num") if not a: a=0 response = requests.post('http://127.0.0.1:5000/index'+ str(a)).json() return render(request, 'hello/index.html', {'out': response['out']}) index.html <!DOCTYPE html> <html> <body> <form action ="home" method="POST"> {% csrf_token%} <label for ="num">Your number: </label> <input type="text" name="num"> <input type ="submit" > </form> <div> {{ out }} </div> </body> </html> I am getting JsonDecoder error for these code I dont know how to solve it -
Django get fields of the ForeignKey Model efficiently?
I am using django-rest-framework as backend and react as a frontend For example if I have the following tables in Django class Master1(models.Model): field1 = models.CharField(max_length = 100) field2 = models.CharField(max_length = 100) field3 = models.CharField(max_length = 100) class Master2(models.Model): field1 = models.CharField(max_length = 100) field2 = models.CharField(max_length = 100) field3 = models.CharField(max_length = 100) class Transaction(models.Model): master1 = models.ForeignKey(Master1) master2 = models.ForeignKey(Master2) title = models.CharField(max_length = 100) I want to create a view for the Trasaction that displays several fields from each of its related models in frontend. Can someone suggest an efficient way of doing that. Should I just define the fields it needs in the view or should I use nested serializers? -
WSGI/Django 1.8 No handlers could be found for logger "django.request"
I wanted to try out graphite+graphite-web and followed this guide here: https://www.metricfire.com/blog/install-graphite-common-issues/#Log-rotation after that i got some errors and fixed a few of them! but now i got stuck at that one: On the website from graphite-web i get this error: graphite-web In the error.logs i have this error: error.log This are my wsgi.py settings: wsgi.py This are my apache2 settings: apache2-graphite.conf If u need anything else, let me know! -
AMQP service: how to check if running, stop and start it
I have an old Django app using celery==3.1.18 and amqp==1.4.9. I am trying to replace amqp with rabbitmq but I need to understand how the old system works. I cannot find any documentation helping me with this task. How do I check status, stop, start amqp services? Any link to documentation explaining how to move from amqp to rabbitmq will be greatly appreciated. Thank you. -
Invisible output in postgreSQL using jsonb
Only the table "checks_check" experiences this. It's not only invisible, there is actually no output to work with. The table was create by django 1.11. Terminal -
How to define a virtual environment in vs-code
I am a noob to vs-code (starting using it yesterday and I like it) I have a minor irritation. I am working on a django project and I'm using a virtualenv with virtualenvwrapper. The problem that I have is that (for example) in the line from django.shortcuts import render the linter says Unable to import 'django.shortcuts'pylint(import-error) My virtualenvs are in the directory ~/Envs and ls -l Envs returns drwxr-xr-x 4 jeff jeff 4096 Jun 18 14:46 django -rwxr-xr-x 1 jeff jeff 135 Jun 18 15:23 get_env_details -rw-r--r-- 1 jeff jeff 96 Jun 18 15:23 initialize -rw-r--r-- 1 jeff jeff 73 Jun 18 15:23 postactivate -rw-r--r-- 1 jeff jeff 75 Jun 18 15:23 postdeactivate -rwxr-xr-x 1 jeff jeff 66 Jun 18 15:23 postmkproject -rw-r--r-- 1 jeff jeff 73 Jun 18 15:23 postmkvirtualenv -rwxr-xr-x 1 jeff jeff 110 Jun 18 15:23 postrmvirtualenv -rwxr-xr-x 1 jeff jeff 99 Jun 18 15:23 preactivate -rw-r--r-- 1 jeff jeff 76 Jun 18 15:23 predeactivate -rwxr-xr-x 1 jeff jeff 91 Jun 18 15:23 premkproject -rwxr-xr-x 1 jeff jeff 130 Jun 18 15:23 premkvirtualenv -rwxr-xr-x 1 jeff jeff 111 Jun 18 15:23 prermvirtualenv drwxr-xr-x 4 jeff jeff 4096 Jun 18 15:26 wagtail I am working in the venv … -
Dockerized Django project deployment with supervisor - what is the correct way?
The cookiecutter-django docs are great, got the django project dockerized and it runs. Even the Supervisor example works flawlessly. Though when it comes to a new deployment, I wonder what the correct way of doing this is. Clearly, I need to run: $ docker-compose -f production.yml build But my guess is that I would have to stop supervisor first: $ sudo supervisorctl stop {{ my_project_slug }} and then run $ docker-compose -f production.yml build followed by this to bring the project back up: $ sudo supervisorctl start {{ my_project_slug }} Is that correct? Or is it ok to run the build command without stopping supervisor? -
uploading image and videos to aws s3 using Django Python takes lot of time
I am using below code in views.py: def upload(request): if request.method == 'POST': image = ImageForm(request.POST, request.FILES) video = VideoForm(request.POST, request.FILES) # Split the extension from the path and normalise it to lowercase. ext = os.path.splitext(str(request.FILES['file']))[-1].lower() print(ext) # Now we can simply use == to check for equality, no need for wildcards. if ext == ".mp4": print("mp4!") if video.is_valid: # form.save() fs = video.save(commit=False) fs.user = request.user fs.save() messages.success(request, 'Video inserted successfully.') return redirect('upload') But upload videos and photos takes a lot of time. i.e 3-4 mins. Please help me in finding a solution to this. -
PermissionError at /generate-pdf [Errno 13] Permission denied weasyprint
hello am using weasyprint to generate a pdf whats wrong with my code here getting access denied. def generate_pdf(request): """Generate pdf.""" # Model data student = Student.objects.all().order_by('last') # Rendered html_string = render_to_string('pdf-output.html', {'student': student}) html = HTML(string=html_string) result = html.write_pdf() # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_os_students.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response If i change the line output = open(output.name, 'rb') to output = open(output.seek(0), 'rb') the page loads to infinity while in console printing [22/Oct/2020 11:36:54] "GET /dashboard HTTP/1.1" 200 84413 Not Found: /assets/media/avatars/avatar15.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar15.jpg HTTP/1.1" 404 2917 Not Found: /assets/media/avatars/avatar2.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar2.jpg HTTP/1.1" 404 2914 Not Found: /assets/media/avatars/avatar1.jpg Not Found: /assets/media/avatars/avatar13.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar1.jpg HTTP/1.1" 404 2914 Not Found: /assets/media/avatars/avatar11.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar13.jpg HTTP/1.1" 404 2917 [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar11.jpg HTTP/1.1" 404 2917 -
django Submit function does not save data in database
I just started using django and this is my first app. i created "contact form" depending on several tutorials i'v seen, but it doesn't save data to database plus doesn't direct me to the "Thank you" html page. tried many scenarios but none worked can anyone help? i'm open to change any thing in the code just to make it work and save the data that i need to save. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # 'crispy_forms', 'widget_tweaks', models.py from django.db import models from django.conf import settings from datetime import date class Snippet(models.Model): MALE = 'MA' FEMALE = 'FE' GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), ] LOCAL= 'SA' NONE_LOCAL = 'NS' NAT_CHOICES = [ (LOCAL, 'Local'), (NONE_LOCAL, 'Non_Local'), ] RIYADH = 'RH' JEDDAH = 'JH' CITY_CHOICES = [ (RIYADH, 'Riyadh'), (JEDDAH, 'Jeddah'), ] DIPLOMA = 'DP' BACHELOR = 'BA' HIGHEREDU = 'HE' OTHER = 'OT' EDU_CHOICES = [ (DIPLOMA, 'Diploma'), (BACHELOR, 'Bachelor'), (HIGHEREDU, 'Higer Edu'), (OTHER, 'Other'), ] ONE = 'On' FIVE = 'Fi' OTHER = 'Ot' INC_CHOICES = [ (ONE, '100-500'), (FIVE, '500-1000'), (OTHER, 'Other'), ] name = models.CharField(max_length=100) email = models.EmailField() mobile = models.IntegerField(default=None) gender = models.CharField( max_length=2, choices=GENDER_CHOICES, default=MALE) nat … -
Cannot delete entries from database on Django
On admin page , I created a delete entries button . I clicked and it asked me yes or no .I click yes but no effect . (The whole system designed with Django ) How to solve ? On A.html <button class="btn btn-danger btn-sm" style = "padding: 2px 4px;" id="delete"onclick = "Del('{{i.id}}')">Delete</button> <script> function Del(id){ console.log("delet*********") swal({ title: "Are you sure?", text: "To Delete this Entry!", icon: "warning", buttons: ["No", "Yes"], closeOnClickOutside: false, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $.ajax({ method : "POST", url : "/delete_lost_item/", data : { 'id':id, }, success : function(response){ if (response == "success"){ swal("Entry has been Deleted..!", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.reload(); }); } } }) } }); } </script> on Table Lost_Item class Lost_Item_table(admin.ModelAdmin): list_display = ['id','lebal','title','brand','species'...] URL.PY url(r'^delete_lost_item/$',delete_lost_item, name='delete_lost_item'), -
Django : insert form data to the sessions to hold the data values without import models or forms
So here are my approach where I wanted to add the information from the user to add those values to my screening and vetting form but the form has multiple steps that are processing while he giving the information. The problem is I didn't see that form data on my server. Can someone guide me through this? here is my code: views.py page def personalData(request): if request.method == 'POST': g = request.POST['gender'] s = request.POST['salutation'] fN = request.POST['forename'] midName = request.POST['midname'] midName1 = request.POST['middleName1'] midName2 = request.POST['middleName2'] midName3 = request.POST['middleName3'] surN = request.POST['surname'] bir = request.POST['birthday'] visa = request.POST['work-visa'] nation = request.POST['nation'] biometric = request.POST['Biometric-ID'] visa_ex = request.POST['visa-expireDate'] nation_o = request.POST['nation-o'] passport = request.POST['passport'] passport_N = request.POST['passport-number'] passport_I = request.POST['passport-Issue'] passport_E = request.POST['passport-Expire'] country = request.POST['country'] birth_op = request.POST['birth-certification-o'] birth_ID = request.POST['birth-certificate-ID'] dri_op = request.POST['dri-type'] drive_op = request.POST['drive-lic-type'] veh_Id = request.POST['driving-licence-Id'] veh_Issue = request.POST['veh-issue-date'] veh_ex = request.POST['veh-expiry-date'] veh_detail = request.POST['vehicle-detail'] nation_op = request.POST['insurance-o'] nation_insure = request.POST['National-Insurance-NO.'] m_status = request.POST['marital-status'] dependent = request.POST['d-quantity'] disability = request.POST['disability'] # Sessions ses = [ {'gender': g, 'initial': s, 'forename': fN, 'middleName1': midName1, 'middleName2': midName2, 'middleName3': midName3, 'surname': surN, 'birthday': bir, 'Visa': visa, 'Nation': nation, 'biometric': biometric, 'visaExpire': visa_ex, 'where': nation_o, 'passportNum': passport_N, 'passportIssue': passport_I, … -
how to make 2 step approval system django?
I was trying to make a 2 step approval system in Django project where if a student applies for a leave it should be approved/rejected by the teacher (step 1) if rejected then admin won't be able to see the application if approved by the teacher then only the approvals approved by teachers will be shown in admin for final approval (step2) Now Admin can see the teachers and students leave then approve or reject it Please help -
models.py", line 287, in __init__ raise ValueError('ModelForm has no model class specified.') ValueError: ModelForm has no model class specified
class PostForm(forms.ModelForm): def init(self, *arg, **kwargs): super(PostForm, self).init(*arg, **kwargs) self.helper = FormHelper self.helper.add_input(Submit( 'post','Post', css_class='btn-primary')) self.helper.form_method = 'POST' class Meta: fields = ('__all__') ///////////////////////////////////////// if I remove def init_ function I am getting another error. Please check my https://github.com/m0nst3rm3/Instaclone link and help me get over this problem -
Hide columns of table on smaller screens breaking format of table
I have a table that is quite large and I would like to hide columns based on screen size. However when I add class="d-none d-xl-block" to my column header it breaks the formatting of the table when using xl wide screens. code: <table class="table table-hover table-sm"> <thead> <tr class=""> <th scope="col" class="">ID</th> <th scope="col" class="">Set Code</th> <th scope="col" class="">Set Name</th> <th scope="col" class="d-none d-xl-block">Set Type</th> <th scope="col" class="text-right">Release Date</th> <th scope="col" class="text-right d-none d-xl-block">Card Count</th> <th scope="col" class="text-right d-none d-xl-block">Digital Only</th> <th scope="col" class="text-right d-none d-xl-block">Foil Only</th> <th scope="col" class="text-right d-none d-xl-block">Nonfoil Only</th> <th scope="col" class="" style="text-align:center">Status</th> </tr> </thead> <tbody> {% for set in Sets %} <tr class=""> <th>{{ set.id }}</th> <td>{{ set.code }}</td> <td>{{ set.name }}</td> <td>{{ set.set_type }}</td> <td>{{ set.release_date }}</td> <td>{{ set.card_count }}</td> <td>{% if set.digital_only %} <span style="color: green">&#x2714;</span> {% endif %}</td> <td>{% if set.foil_only %} <span style="color: green">&#x2714;</span> {% endif %} </td> <td>{% if set.nonfoil_only %} <span style="color: green">&#x2714;</span> {% endif %} </td> <td>{% if set.status %} <label class="switch"><input type="checkbox"><span class="slider round"></span></label> {% else %} <label class="switch"><input type="checkbox"><span class="slider round"></span></label> {% endif %}</td> </tr> {% endfor %} </tbody> </table> Screenshot: -
Django signup: set username to provided email address and save?
Short question (no actual need to read the rest): I have read multiple threads/tutorials (e.g. this one) on how to let users login via email. And I was wondering: why can't I just keep things simple and ask for an email address upon signup and then set the username to that email address and save the user? Long part: I would create a form that is very similar to the UserCreationForm of Django 1.8. I'm not sure why I cannot find the same code for 3.1 (which makes me wonder even more whether my idea might be bad practice for some reason) but basically I would do this: create a ModelForm for the default user model, set fields = ["email"], render it manually as {{form.email}} in the template and then, in the view, I'll call form.save(commit=False) to get the object, set the username of that object to the given email address and save it. Orrrr don't I? :-) -
How to call Django restful api endpoint [closed]
I have an a Django endpoint http://127.0.0.1:8000/app/ and I want to call this endpoint and do something with it. How do I call the endpoint..? Your answers are highly appreciated. Here is My app model.py file class MyVideo(models.Model): name= models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to='videos/%Y/%m/%d/', null=True, verbose_name="") # mod = models.FilePathField def __str__(self): return self.name + ": " + str(self.videofile) Here is my View.py file class MyVideoView(viewsets.ModelViewSet): queryset = MyVideo.objects.all() serializer_class = MyVideoSerializer Here is my serializer.py file class MyVideoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyVideo fields = fields = ['id', 'url', 'name', 'created', 'videofile'] Here is my app urls.py file from django.urls import path, include from .views import MyVideoView from rest_framework import routers router = routers.DefaultRouter() router.register(r'app', MyVideoView) urlpatterns = [ path('', include(router.urls)), ] -
why couldn't I find the python module uwsgi after pip install uwsgi?
After I have installed the uwsgi, I add the following code: import uwsgi But the IDE is warning that uwsgi module not exist. the command I used to install the uwsgi is: pip install uwsgi the installed uwsgi package is: pip freeze | grep -i uwsgi uWSGI==2.0.19.1 but in the site-packages dir there is not any uwsgi subdir. -
Nginx directory forbidden 403 django
I am trying to deploy django in centos 8 . I am getting 403 directory forbidden error. I have applied chmod 755 var/www/ still i am getting this error I have also applied sudo chown myusername:psaserv /var/www/vhosts/aaa.com but still i am getting this error . This is the error i am getting inside the server logs 2020/10/22 08:15:14 [error] 78481#0: *398 directory index of "/var/www/vhosts/aaa.com/httpdocs/djangoProject/" is forbidden, client: 162.158.167.71, server: aaa.com, request: "GET / HTTP/1.1", host: "aaa.com" this is my nginx configuration file #user nginx; worker_processes 1; #error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; #pid /var/run/nginx.pid; include /etc/nginx/modules.conf.d/*.conf; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #tcp_nodelay on; #gzip on; #gzip_disable "MSIE [1-6]\.(?!.*SV1)"; server_tokens off; include /etc/nginx/conf.d/*.conf; } # override global parameters e.g. worker_rlimit_nofile include /etc/nginx/*global_params; -
I want use snippets in terminal
I wrote "makemigrations": { "prefix": "makemigrations", "body": [ "python manage.py makemigrations", " ${1:pass}" ], "description": "makemigrations" }, and,I've tried makemigrations in terminal,but this didin't work. please tell me how to solve it. -
Django - How to download the byta data in csv file format
I am new to Django, I am developing an application where the BA will upload the CSV data into the database during the requirement phase and the tester need to download the CSV file and compare the source and target results in system testing. I am able to upload the file to the table. However, Not able to download the same from the PostgresSQL database which is stored in the drawing_data field.(field type bytea) My ask is: I would like to download the file data which is stored in drawing_data. Thanks in advance Attaching my code. Could you please help me with this.. I am not able to download the file. from HTML 1 -DataBase: postgreSQL 2- Table Name: prj_details 3- model name: prj_details 4- filed/column details: file_extension = models.CharField(max_length=500) drawing_data = models.BinaryField() class Meta: db_table = 'prj_details' View.py: def download(request, drawing_data): # this url is for download try: obj = prj_details.objects.get(drawing_data) except prj_details.DoesNotExist as exc: return JsonResponse({'status_message': 'No Resource Found'}) get_binary = obj.csv if get_binary is None: return JsonResponse({'status_message': 'Resource does not contian csv'}) if isinstance(get_binary, memoryview): binary_io = io.BytesIO(get_binary.tobytes()) else: binary_io = io.BytesIO(get_binary) response = FileResponse(binary_io) response['Content-Type'] = 'application/x-binary' response['Content-Disposition'] = 'attachment; filename="{}.csv"'.format( drawing_data) return response url.py path('App_csv_diff/<drawing_data>/', …