Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.9: @csrf_exempt has absolutely no effect
in my views: from django.views.decorators.csrf import csrf_exempt @csrf_exempt def process_webhook(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) print(body) in urls: url(r'^webhook/$', my_app.views.process_webhook), and yet when I: curl -X POST -d "fizz=buzz" http://localhost:8000 I get the CSRF error seen below. What am I doing wrong? Why isn't @csrf_exempt working?: . . . <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p> . . . . -
"Symbol not found: _GEOSArea" on MacOS
I just started getting this error after reinstalling my local environment on the new MacOS Sierra: $ ./manage.py migrate Traceback (most recent call last): File "./manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/rafael/workspace/goodbed/beds/sitecomments/__init__.py", line 5, in <module> from beds.sitecomments.models import Comment File "/Users/rafael/workspace/goodbed/beds/sitecomments/models.py", line 1, in <module> from django_comments.models import Comment as DjangoComment File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django_comments/models.py", line 7, in <module> from .abstracts import ( File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django_comments/abstracts.py", line 18, in <module> class BaseCommentAbstractModel(models.Model): File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__ new_class.add_to_class('_meta', Options(meta, **kwargs)) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class value.contribute_to_class(cls, name) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend return import_module('%s.base' % backend_name) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 8, in <module> from .features import DatabaseFeatures File "/Users/rafael/.virtualenvs/goodbed/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/features.py", line 1, in <module> from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures File … -
nginx works as reverse proxy with apache for django server, but 404 found for subdirectory
I try to use nginx in 80 port as reverse proxy for apache in 8080 port, it's ok to visit root index (like "http://my_ip", but return nginx 404 not found for sub directory (like "http://my_ip/blogs/blog/example-blog"). My nginx setting as below: server { listen 80; server_name localhost; root /home/test/mysite/; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules proxy_pass http://localhost:8080; proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { root /home/test/mysite/; if (-f $request_filename) { expires 1d; break; } } location ~ .*\.(js|css)$ { root /home/test/mysite/; if (-f $request_filename) { expires 1d; break; } } My apache setting as below: <VirtualHost *:8080> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this … -
Not able to Deploy Django + Python 3 + PostgreSQL to EC2
I have a ready django project perfectly running on localserver. Now I need to deploy same on AWS EC2. As I am self learned developer and new to it, I went through tons of tutorials but could not find any easy explained tutorials on how to deploy django project using python 3 and postgres to EC2. Please guide me if anybody is interested to else provide me with tutorials explaining the same. -
Failed to extends User form in django
The error I get is: extend user to a custom form, the "user_id" field is my custom form is the "property", which is linked to the table "auth_user" is not saved, and I need both tables relate to make use my custom form attributes and shape of the User of django. my models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) Matricula = models.CharField(max_length=25) forms.py class SignupForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'Matricula') #Saving user data def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.Matricula = self.cleaned_data['Matricula'] user.save() ##Save profile profile = Profile() Profile.user = user profile.Matricula = self.cleaned_data['Matricula'] profile.save() i tried: user = models.OneToOneField(User, on_delete=models.CASCADE) but I get an error: Error You believe that ForeignKey can be used or correct use OneToOneField? -
Screen streaming between clients who are connected to a django server
I am working on a feature for a project that I'm not sure where to start. I have a django server running on a raspberry pi 3. I want one user (lecturer) to be able to connect to a server, click a screen cast button, and then anyone else (students) connected to the server can watch the screen live. Does anyone know of any free libraries/services that could help accomplish this? Ideally the users wouldn't have to install anything. -
Django 1.9 adding an html ID to errorlist
I'm using Django 1.9 and need to add an id to the html errorlist li. In Django, when an error is raised the HTML would look something like this (my rendered html): <div id="form"> <ul class="errorlist"> <li>Please enter xyz.</li> </ul> <p> <label for="id_xyz">X Y Z</label> <input class="form-control" id="id_xyz" name="xyz" placeholder="X Y Z" type="text"? </p> </div> I want to get this: <div id="form"> <ul class="errorlist"> <li id="testing">Please enter xyz.</li> </ul> <p> <label for="id_xyz">X Y Z</label> <input class="form-control" id="id_xyz" name="xyz" placeholder="X Y Z" type="text"? </p> </div> Here is my forms.py: class UserProfileForm(forms.ModelForm): company_name = forms.CharField(label="Company Name") def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['company_name'].required = False self.fields['company_name'].widget.attrs = { 'class': 'form-control', 'placeholder': 'Company XYZ' } def clean_company_name(self): company_name = self.cleaned_data['company_name'] if not company_name: raise forms.ValidationError(u'Please enter your company name.') return company_name My endgoal is to use this jQuery: <script> $(document).ready(function() { $('#id_company_name')[0].placeholder = $("#testing")[0].textContent }); </script> It's a hack I know, but it's what I'm going for. Any ideas on how to create an HTML id for the li that parent is a ul class="errorlist"? -
module not importing in my views.py file
I am running a django site and am having issues with the Http module running in my views file. It's running in a python virtual environment and I have checked to ensure that all required packages are installed via the pip3 freeze command. The module will import and run in another script file within the same environment just not my views.py file. When attempting to import the module in my views.py file I get the following error: [:error] [pid 2122] [remote 108.214.118.85:188] AttributeError: 'module' object has no attribute 'Http' The code on the script that is functioning properly is as follows: import json from oauth2client.service_account import ServiceAccountCredentials from httplib2 import Http from apiclient.discovery import build scopes = ['https://www.googleapis.com/auth/calendar'] credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes) http_auth = credentials.authorize(Http()) caladmin = build('calendar', 'v3', http=http_auth) events_query = caladmin.events().list(calendarId='calendarId').execute() def get_events(): if not events_query['items']: print('No upcoming events') events = events_query['items'] print(events) return events get_events() The code in my views file that will not import the Http module and throws the error is as follows: import os import json from oauth2client.service_account import ServiceAccountCredentials from httplib2 import Http from apiclient.discovery import build from django.shortcuts import render def news(request): events = get_events() context = {'events':events} return render(request, 'district/about/news.html') def … -
TemplateDoesNotExist but it exist
Python 2.7 & Django 1.10 my template exist but i do somesing wrong! TemplateDoesNotExist at /basicview/2/ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>TEST</title> </head> <body> This is template_two view! </body> </html> Request Method: GET Request URL: http://127.0.0.1:8000/basicview/2/ Django Version: 1.10.1 Exception Type: TemplateDoesNotExist Exception Value: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>TEST</title> </head> <body> This is template_two view! </body> </html> Exception Location: /home/i/djangoenv/local/lib/python2.7/site-packages/Django-1.10.1-py2.7.egg/django/template/loader.py in get_template, line 25 Python Executable: /home/i/djangoenv/bin/python Python Version: 2.7.11 Python Path: ['/home/i/djangoenv/bin/firstapp', '/home/i/djangoenv/lib/python2.7', '/home/i/djangoenv/lib/python2.7/plat-i386-linux-gnu', '/home/i/djangoenv/lib/python2.7/lib-tk', '/home/i/djangoenv/lib/python2.7/lib-old', '/home/i/djangoenv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-i386-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/i/djangoenv/local/lib/python2.7/site-packages', '/home/i/djangoenv/local/lib/python2.7/site-packages/Django-1.10.1-py2.7.egg', '/home/i/djangoenv/lib/python2.7/site-packages', '/home/i/djangoenv/lib/python2.7/site-packages/Django-1.10.1-py2.7.egg'] Server time: Пт, 23 Сен 2016 15:43:30 +0000 settings.py (os.path.join(BASE_DIR), 'templates', or /home/mainapp/templates) not working.. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, article/views.py my def looks like: def template_two(request): view = "template_two" t = get_template('myview.html') html = t.render(Context({'name': view})) return render(request, html, {}) My file: mainapp/mainapp/settings.py mainapp/mainapp/article/views.py mainapp/templetes/myview.html -
String index out of range while sending email
I'm running into this error: link, while trying to send mail with Django EmailMultiAlternatives. I tried searching for this error but no luck, also I tried removing or changing every variable for email, but with no luck. This is the code: def spremembapodatkovproc(request): if request.method == 'POST': req_id = request.POST.get('req_num', 'Neznan ID zahtevka') old_email = request.user.email old_name = request.user.get_full_name new_email = request.POST.get('email_new', 'Nov e-mail ni znan') new_fname = request.POST.get('fname_new', 'Novo ime ni znano') dokument = request.FILES.get('doc_file') komentar = request.POST.get('comment', 'Ni komentarja') # try: plaintext = get_template('email/usr-data-change.txt') htmly = get_template('email/usr-data-change.html') d = Context( { 'old_email': old_email, 'old_fname': old_name, 'new_email': new_email, 'new_fname': new_fname, 'req_id': req_id, 'komentar': komentar, 'user_ip': request.META.get('REMOTE_ADDR', 'IP Naslova ni mogoče pridobiti.') } ) subject, from_email, to = 'eBlagajna Sprememba podatkov', 'eblagajna@ksoft.si', ["info@korenc.eu"] text_content = plaintext.render(d) html_content = htmly.render(d) print(text_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' for f in ["templates\\email\\img1.png"]: fp = open(os.path.join(BASE_DIR, f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send() Thank you for your help. -
Django single-test migration
I have recently implemented a reusable app within the django project I am working on. For the sake of the question, let's call it reusable_app. This app also has some unittests that run, however, these tests depend on some basic models declared somewhere next to the tests in a model.py. Now, the the models aren't loaded in the database unless I specify the folder in INSTALLED_APPS in the testing configuration file. I was wondering if there is another way to achieve this, not having to expose the app in the settings file? I seem to be able to specify the app via @override_settings, but the migrations are not ran. Am I missing something? -
using django celery beat locally I get error 'PeriodicTask' object has no attribute '_default_manager'
using django celery beat locally I get error 'PeriodicTask' object has no attribute '_default_manager'. I am using Django 1.10. When i schedule a task it works. But then a few moments later a red error traceback like the following occurs [2016-09-23 11:08:34,962: INFO/Beat] Writing entries... [2016-09-23 11:08:34,965: INFO/Beat] Writing entries... [2016-09-23 11:08:34,965: INFO/Beat] Writing entries... [2016-09-23 11:08:34,966: ERROR/Beat] Process Beat Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/billiard/process.py", line 292, in _bootstrap self.run() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/beat.py", line 553, in run self.service.start(embedded_process=True) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/beat.py", line 486, in start self.scheduler._do_sync() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/beat.py", line 276, in _do_sync self.sync() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/djcelery/schedulers.py", line 209, in sync self.schedule[name].save() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/djcelery/schedulers.py", line 98, in save obj = self.model._default_manager.get(pk=self.model.pk) AttributeError: 'PeriodicTask' object has no attribute '_default_manager' after this happens the next schedule wont run unless I "control+c" out of the terminal and start it again. I saw on git hub that this may be because I am using django 1.10. I have already git pushed this to my heroku server. How can I fix this issue? The git hub post said he fixed it by doing this Model = type(self.model) obj = Model._default_manager.get(pk=self.model.pk) I was willing to try this but I don't know where to put this and I don't … -
Django 1.9 Can't leave formfield blank issue
I modified my forms to show a new label for the fields in my model. Now I can't have a user leave the form field blank. I've tried to add blank=True and null=True, but without luck. How can I allow fields to be blank? My Model: class UserProfile(models.Model): # Page 1 user = models.OneToOneField(User) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=100, blank=True, unique=True) # Page 2 Address line1 = models.CharField(max_length=255, blank=True, null=True) line2 = models.CharField(max_length=255, blank=True, null=True) line3 = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=2, blank=True, null=True) zip_code = models.CharField(max_length=15, blank=True, null=True) def __str__(self): return self.user.username forms.py: class UserProfileForm3(forms.ModelForm): line1 = forms.CharField(label="Address") line2 = forms.CharField(label="") line3 = forms.CharField(label="") city = forms.CharField(label="City / Town") state = forms.CharField(label="State / Province / Region") zip_code = forms.IntegerField(label="Zip / Postal Code") def __init__(self, *args, **kwargs): super(UserProfileForm3, self).__init__(*args, **kwargs) self.fields['line1'].widget.attrs = { 'class': 'form-control', 'placeholder': 'Address Line 1' } self.fields['line2'].widget.attrs = { 'class': 'form-control', 'placeholder': 'Address Line 2' } self.fields['line3'].widget.attrs= { 'class': 'form-control', 'placeholder': 'Address Line 3' } self.fields['city'].widget.attrs = { 'class': 'form-control', 'placeholder': 'City' } self.fields['state'].widget.attrs = { 'id': 'state_id', 'class': 'form-control', 'placeholder': 'State' } self.fields['zip_code'].widget.attrs = { 'id': 'zip_code_id', 'class': 'form-control', 'placeholder': 'Zip' } self.fields['country'].widget.attrs … -
Django project deployment: cannotload static files
I'm deploying a Django project using: virtualenv nginx gunicorn following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps My configuration django settings STATIC_ROOT = '/new_esmart/esmart2/static/' /etc/nginx/sites-available/esmart2 GNU nano 2.0.9 File: /etc/nginx/sites-available/esmart2 server { server_name 192.168.30.17; access_log off; location /static/ { alias /new_esmart/esmart2/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } Running (esmart_env) [root@eprssrv09 esmart2]# /new_esmart/esmart_env/bin/gunicorn --bind 192.168.30.17:8001 esmart2.wsgi:application I can access to my Django project but Not Found: /static/admin/css/login.css Any advice? -
Is it possible to have a class as your model field in Django?
I am currently trying to create a health network website in Django. The idea is that there will be a class called User inside my registration application. One of the states stored inside User is which hospital the user is registered into. I created another Hospital within the registration app. I want to user that model Hospital as one of the model field for the hospital_used state. How do I do that? Below is a portion of my UML that illustrates the relationship UML Diagram Below is a portion of my UML that illustrates the relationship png Here is the code I have for it so far. The code where it is encapsulated with an asterisk is what I need help with. class Hospital(models.Model): hospital_Name = models.CharField(max_length=150) def __str__(self): return "Hospital Name: " + str(self.hospital_Name) class User(models.Model): PATIENT = 'Pat' DOCTOR = 'Doc' NURSE = 'Nurse' ADMINISTRATOR = 'Admin' user_type_choice = { (PATIENT, 'Patient'), (DOCTOR, 'Doctor'), (NURSE, 'Nurse'), (ADMINISTRATOR, 'Administrator'), } name = models.CharField(max_length=50) dob = models.DateField(auto_now=False) username = models.CharField(max_length=50) *preferred_hospital = Hospital(models.CharField(max_length=50))* patient_type = models.CharField( max_length=5, choices=user_type_choice, ) Thank you StackOverflow Buddies -
DRF - Render Model Serializer to HTML Create Form
I am trying to render a form to create new objects. I have defined my API in a separate App and now I want to use it in another App of the same project. I followed the Tutorial and now I have a a Default Router, a ModelSerializer and a ModelViewSet and an automatically created browseable HTML API which also automatically renders a HTML form on the list page, to create new objects. I want to include this form now in my project. Of course I could write a form by myself and just use jQuery to make a POST request to the API but then I will have to create a form for every model manually. And if the model changes I will have to update the form. I was hoping to accomplish this using DRF and the documentation found here: http://www.django-rest-framework.org/topics/html-and-forms/ Sadly I have not found any example on the internet. I did find one Question on StackOverflow with the same problem but no solution. class TaskViewSet(viewsets.ModelViewSet): (in API/views.py) serializer_class = TaskSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return Question.objects.all().filter(owner=self.request.user.institute) def list(self, request): serializer = TaskSerializer(self.get_queryset(), many=True) return Response(serializer.data) def perform_create(self, serializer): serializer.save(owner=self.request.user.institute, created_by=self.request.user, modified_by=self.request.user) def perform_update(self, serializer): serializer.save(owner=self.request.user.institute, … -
Django - get() returned more than one it returned 700
I am having issues with a search form. I am trying to make a search field that queries the database and returns results on my results page. I have the page returning 1 result with a certain query and the other query with multiple rows I get this error get() returned more than one MyModel -- it returned 791!. This may seem silly as I am new to Django Forms. Please let me know if you need any other info. I have tried using .filter but that returns nothing. I have looked at multiple SO questions and some have helped but still having a little issue. My code is below: views.py from django.shortcuts import render from .models import Model def index(request): return render(request, 'index.html') def search(request): query = request.GET.get('q') if query: query = str(query) results = myModel.objects.get( site=query ) context = {"results": results} return render(request, 'results.html', context) results.html {% if results %} <ul> <li><p>{{ results.url }}</p></li> </ul> {% else %} <p>Nothing Available.</p> {% endif %} index.html <form action="/results/" method="GET"> {% csrf_token %} <input id="search_box" type="text" name="q" placeholder="Search..."> <button id="search_submit" type="submit" class="btn btn-defaultbtnlg"><i class="fa fa-search fa-fw"></i> <span class="networkname">Search</span></button> </form> -
GCP Cloud DNS unreachable
I just added a new domain in Cloud DNS but I can't access it in browser or even ping it. Maybe I have some mistake in my configuration or maybe there's a time range or propagate time for this to take effect. By the way I am using Compute Engine with Django running on it and I am trying to make a DNS for its external IP. -
JsonResponse to array
I use a django library function. my_data = get_stats(request) get_stats returns JsonResponse. return JsonResponse({'data': response}) Every response object consists of 'id', 'name' and 'value'. I need to parse my_data to array - I need to get every item's id, name and value. How can I do this? -
What method is equivalent to_internal_value in DRF 2?
I can't find that in documentation. I remember that I used such method in DRF 2 but don't know what is name of this one. -
How to download file from django API
I am trying to download a file from Django API.Here is the flow of code inside Django tests.py def generate_utilisation_report(): url = base_url + "generate_utilisation_report" payloads = [ { "clientId": 23, "startDate": "2016-01-01T04:00:00", "endDate": "2016-02-02T00:00:00", "interval": "month" } ] for payload in payloads: response = requests.post(url, headers={'content-type': 'application/json'}, data=json.dumps(payload)) print(response.text) views.py def generate_utilisation_report(request): file = get_utilisation_report(request) response = HttpResponse(file, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="Vehicle_Utilisation_Report.xlsx"' return response models.py def get_utilisation_report(request): workbook = xlsxwriter.Workbook('Vehicle_Utilisation_Report-' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '.xlsx') # add data inside workbook workbook.close() return workbook When I run the API,I can see the file being created inside the folder where the Django project resides.But I cannot download the file. What code changes should I make to download the file? Are there better ways to do this? -
Django: Setting the from address on an email
I'd like for my users to be able to enter their email-address and message and then send the email with the 'from address' being their own email-address. Currently the EMAIL_HOST is set on our own domain and the emails arrives when it is sent with a "from address" equal to our HOST_USER, but not if it is anything else. Is this possible? Our settings: EMAIL_HOST = 'smtp02.hostnet.nl' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "xxx" EMAIL_HOST_PASSWORD = "xxx" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
"Post Image data using POSTMAN"
I am trying to POST data to my API. I have a model with an image field where: image = models.ImageField() I have an image on my local box, which I am trying to send. Am I sending it correctly? { "id": "3", "uid":"273a0d69", "uuid": "90", "image": "@/home/user/Downloads/tt.jpeg" } -
How To Set Up Django Site on Servver
Let's say I have a Django website built. I can access it through localhost like a normal website. Let's also say I have a server with FTP, and a FTP app like Filezilla. How do I set up the site on the server? Do I just copy the files? -
How do I return a JsonResponse if the post data is bad in tastypie?
For example, client post a card number in data and I use it to fetch the card record from database. If it does not exist, I return a JsonResponse such as: return JsonResponse({ success:False, msg:'The card does not exsit! Please check the card number.' }) If the card does exist, I will use it to filter another record from database and use them togeter to create the obj such as an consumption record. I read the docs of tastypie but have no idea how to control the HttpResponse that tastypie finally returned.