Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does Django Model Class and Model Field work in jQuery Autocomplete?
Let's say I have a Django model like this: class City(models.Model): city_name = models.CharField(max_length=100, default='Toronto') class Meta: verbose_name = 'City' def __str__(self): return self.city_name class State(models.Model): state_name = models.CharField(max_length=100, default='Ontario') class Meta: verbose_name = 'State' def __str__(self): return self.state_name class Country(models.Model): country_name = models.CharField(max_length=100, default='Canada') class Meta: verbose_name = 'Country' def __str__(self): return self.country_name ====================== OR ====================== class Location(models.Model): city= models.CharField(max_length=100, default='Toronto') state= models.CharField(max_length=100, default='Ontario') country = models.CharField(max_length=100, default='Canada') class Meta: verbose_name = 'Location' def __str__(self): return '%s: %s' % (self.city, self.state, self.country) Now, I have a form field in my HTML template where I need to use the jQuery autocomplete to get country list in that form field. My question is, would the country list be called from the Country Model Class or as a Model Field from the Location Model? How do I go about this? -
Sharing a SOAP client object between Django views
My Django application uses an API which is a SOAP service. I'm currently using a python SOAP/WSDL client called SUDS. In order to use the API, I have to initialize the client and provide it with a link to the endpoint, login, API key, and password. Simplified code that does it: from suds.client import Client client = Client('link.to.WSDL.endpoint') session_id = client.service.a_log_in_service('api_key', 'login', 'password') # the session_id is required by all other 'client.service.xxx' services Everything works just fine, although it takes some time to initialize the client. Now, every time I want to send a request to the API in a view, I have to initialize the client. I can't see any way to "share" the already initialized client among many views. It would be great to have the client up and running somewhere, so that any user can send an API request using it. Once I've done the log in in a view, I can store the session_id (in a session, db, file) and use it in other views, but the client still needs to be initialized over again, which means downloading the 200-KB XML file. Having to download 200 KB every time a user hits a button seems not … -
Displaying search results with Django
I am trying to develop a web app for a school project. The basic functionality is you search for a wine, a script scrapes several websites and returns results on wine name, vintage, price, and a link to where you can purchase. I currently have mostly working code in that when the server will take my searches and return results. However, every time I search for a new wine, the results from the previous search still remain in the table that is rendered. I can't figure out why. Below is my views.py and pertinent corresponding template code: (the scraped data is sent as a dictionary of objects with the pertinent attributes) Views def search(request): return render(request, 'findwine/search.html', {}) def results(request): if request.method == 'POST': print(request) query = request.POST.get('search') search_results=WineScraper.searchfunction(query) return render(request, 'findwine/results.html', {'search_results': search_results}) else: return render(request, 'findwine/search.html', {}) HTML results template <div class="container text-center"> <a href="{% url 'search' %}" id="search">Back to Search</a> </div> <div class="table-responsive"> <table class="table table-bordered table-hover table-striped tablesorter"> <thead> <tr> <th class="header"> Wine Name <i class="icon-sort"></i></th> <th class="header"> Vintage <i class="icon-sort"></i></th> <th class="header"> Price <i class="icon-sort"></i></th> <th class="header"> Wine Link <i class="icon-sort"></i></th> </tr> </thead> <tbody> {% if search_results %} {% for key,value in search_results.items %} <tr> … -
Ajax not working in production, but works on localhost, Django + Restframework
Implementation of ajax using djangorestframework works fine on localhost but doesn't work in production. All dependencies are the same. The error code is 500, so something is not correct in view function. @api_view(['POST', ]) def live_search(request): if request.method == 'POST': key = request.data['key'] result = Event.objects.filter(title__istartswith=key) events = serializers.serialize('json', result) print (key) print (result) else: error = "Fuck" return error data = { 'events': events, } return Response(data) Just the same works localy, I updated in production with git pull, and I checked it to be fully indentical. All dependencies are installed, python3 version is the same, migrations are applied to make sure. But anyways error is returned. -
Store and read csv file django
When the user uploads a file, I want it to store the file, read the first 10 rows and send the first 10 rows back to the page. I'm not sure how to go about doing this in the views or on the client side. def UploadTest(request): if request.POST and request.FILES: csvfile = request.FILES['csv_file'] dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024)) csvfile.open() reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect) return render(request, 'index.html', {"form": reader} ) That is what I have in my views.py right now. But I don't want it to render a new page. -
Django Query functions in models
This is more of a best practices question, than a technical question, but I'm at a cross roads in my learning as well as my current design and could use some best practices guidance. I'm building a django app that keeps track of some basic user data, as well as events that happen to that user. As an example I have a model: user that contains the user information, and a model: Event that will track things such as start date, status changes, leaving date. I'm building a form that will input this data, and save it, and in the process makes old events that share a type superseded so the history is intact, but the queries only pull one event at a time for the main status of each event type... My question is...From a logical layout standpoint in the code...it feels like adding the code to pull/return the events, and maybe even save new events, should be functions defined within the user model, so an instance of User in a view could simply pull userx.GetStart() or userx.UpdateStatus(relevant variables here) But...At the same time, I have this contradictory feeling that tells me somewhere someone has some darned good reasons … -
ssl with django gunicorn and nginx
I am currently working on deploying my project over https however I am running into some issues. I have it working with http but when I try to incorporate the ssl it breaks. I think I am misconfiguring the gunicorn upstream client in my nginx block but I am uncertain. Could the issue be in the unix binding in my gunicorn service file? I am very new to gunicorn so I'm a little lost. Here is my configuration below. Gunicorn: [Unit] Description=gunicorn daemon After=network.target [Service] Environment=PYTHONHASHSEED=random User=USER Group=www-data WorkingDirectory=/path/to/project ExecStart=/path/to/project/project_env/bin/gunicorn --workers 3 --bind unix:/path/to/project/project.sock project.wsgi:application [Install] WantedBy=multi-user.target Nginx (working-http): server { listen 80 default_server; listen [::]:80 default_server; server_name server_domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/project; } location / { include proxy_params; proxy_pass http://unix:/path/to/project/project.sock; } } Nginx (https): upstream server_prod { server unix:/path/to/project/project.sock fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server; server_name server_domain; } server { server_name server_domain; listen 443; ssl on; ssl_certificate /etc/ssl/server_domain.crt; ssl_certificate_key /etc/ssl/server_domain.key; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://server_prod; break; } } } -
Django image rotation
I'm using django-smartfields to resize uploaded images to save to my model. It works great, except if the original image is in portrait orientation the image gets rotated 90 degrees clockwise. It doesn't rotate landscape images. I can't find much in the documentation to figure out how to change this behavior. I want it to preserve the original orientation and resize it as-is. Here is my model: from smartfields import fields from smartfields.dependencies import FileDependency from smartfields.processors import ImageProcessor class Image(models.Model): client = models.ForeignKey(Client, null=True, blank=True) image = fields.ImageField(upload_to = settings.MEDIA_URL, dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 500, 'max_height': 500})) ]) And here is the handler: def create_image(request): form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): client = Client.objects.get(id=request.session['id']) image = Image.objects.create(client=client, image=form.cleaned_data['image'], pet_name=request.POST['pet_name'] -
count and sort by column value django query
django model class Report_Shop(models.Model): barcode = models.CharField(max_length=500) email = models.CharField(max_length=500) shop_name = models.CharField(max_length=500) above model multiple entries of one shop_name allow how to count same value of shop_name ??? shop_count i.e. number of unique shop name -> example 3 s_name i.e.s shop name -> 1.yyy 2.xxx 3.zzzz no_reports i.e. number of entries of shop name -> 1.yyy (3) -> 2.xxx (11) -> 3.zzz (5) give me some advise for better response, thanks in advance !!! -
Django + postgres: orderby + distinct + filter() - strange behaviour
I have 2 simple models: Claim and ClaimStatus. Claims can have many statuses (eg. 1: Not analyzed yet, 2: Being analyzed, 3: Analyzed), all of which are written down in the database, together with claim_id and creation_date. The model of interest here - ClaimStatus - is created the following way: class ClaimStatuss(models.Model): status = models.IntegerField(choices=investigated_choices, default=1) claim_id = models.ForeignKey('Claim', to_field='claim_id') creation_date = models.DateTimeField(auto_now=True) My aim is to select claims and their last (= active) statuses for filtering to show eg. all cases that are being analyzed at the moment, using the advice fron this thread: Django orm get latest for each group TO make it simpler, I have just 2 objects in my database: id: 6,claim_id: 578, status: 2, date: 2017-04-12 16:55:25.371014+00:00 id: 7,claim_id: 578, status: 3, date: 2017-04-12 17:04:06.944270+00:00 I do the following: Select all ClaimStatuss objects, and group them to have the latest one for each claim_id (only one in this example): statuses = ClaimStatuss.objects.all().order_by('claim_id','-creation_date').distinct('claim_id') I check, if only one, the latest element has been selected for the queryset: statuses.get().status 3 Now I filter this one-element Queryset, to leave only the objects, which contain status=2 statuses.filter(status=2).get().status 2 And I see, that my Query containing just one object with … -
Django Regroup Not Grouping Model Properly
I am building a gardening app using Django. I am a Django newbie. I have vegetables that are planted in plots. I am trying to use the {% regroup %} template tag to display my planting schedule. So I want to display all planted vegetables, grouped by plot. The output should look like this. Plot 1 First Planted Vegetable In Plot 1 Second Planted Vegetable In Plot 1 Plot 2 First Planted Vegetable In Plot 2 Second Planted Vegetable In Plot 2 Third Planted Vegetable In Plot 2 But instead it looks like this. Plot 1 First Planted Vegetable In Plot 1 Plot 1 Second Planted Vegetable In Plot 1 Plot 2 First Planted Vegetable In Plot 2 Plot 2 Second Planted Vegetable In Plot 2 Plot 2 Third Planted Vegetable In Plot 2 Can someone lend me a hand? I've reviewed the documentation for the {% regroup %} template tag and cannot seem to figure out where I'm going wrong. Here are my classes: class PlantedVegetable(models.Model): vegetable_type = models.ForeignKey(VegetableType, null=True, blank=True, related_name="planted_vegetables") plant_day = models.IntegerField(default=1) plot = models.ForeignKey(SquarePlot, null=True, blank=True, related_name="planted_vegetables") growth_phase = models.IntegerField(default=0) class SquarePlot(models.Model): plot_id = models.IntegerField(default=1) sunlight = models.IntegerField(default=100) n_level = models.IntegerField(default=100) p_level = models.IntegerField(default=100) k_level … -
Store Image in django
I want to store the imaage in django but unable to do it. This is what i tried.. upload.html <form name="saveImage" enctype="multipart/form-data" action="{% url 'Reports:saveimage'%}" method="post"> {% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-left:20%;" placeholder = "Picture" name = "picture" /> <input type="submit" value="Store"></input> </center> </div> </form> model.py def vo_image_upload(inatance,filename): return os.path.join('Volunteer',filename) class Volunteer(models.Model): myphoto = models.ImageField(db_column='MyPhoto', upload_to=vo_image_upload, blank=True, null=True) views.py def saveimage(request): image= request.FILES['picture'] vo = Volunteer.objects.using('NSS_VO').update(myphoto=image). return HttpResponse("<h1>Success</h1>") Update is used because I am storing image after registration. This code is only saving the File name to myphoto field in database but not storing the image in media folder of Project/project/media/. Project/Project/url.py from django.conf.urls import url ,include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^ReportsData/', include('Reports.urls')), ] if settings.DEBUG : urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) and above upload.html ,views.py , models.py belongs to app Reports. What changes I have to do to store the images successfully -
Should Python errors be documented in code or comments?
Let's say we have a service method that performs its business logic by using one or more helper methods, where each helper method can raise one or more errors. Because there can potentially be many helper methods that in total encapsulate lots of code, we want a way for folks using the service method to know all of the errors it can raise without needing to read through the implementation of every helper method. To make this more concrete, let's assume this is being done in a Django context, where each view calls a service method, and then that view is then responsible for catching any errors the service method raises and returning an appropriate response for each to the user. So question is, should the errors that each helper method can raise be documented by just re-raising the errors using a try/except, or should they be noted in a docstring? For example, which is better here, service_method_v1 or service_method_v2?: def service_method_v1(): try: helper_method_1() except SomeError: raise def service_method_v2(): """This method can raise a SomeError.""" helper_method_1() helper_method_1(): raise SomeError I know there is some computational overhead when using try/except, but this purpose let's assume that this is negligible in terms … -
Django Bootstrap Navbar issues for mobile
I'm new to frontend development and I am working on a simple institutional website. I'm using Django 1.10, Bootstrap and Whitenoise for my static files. It seems to be working fine for computer screens, but for mobile I'm having some issues, specially with the navbar. When I shrink the screen and I open the dropdown menu it gets stacked over the brand image. I tried a lot of different things, but nothing solved my problem. I also tried adding some background-color to the navbar dropdown menu and it works on my development (it's a gray color), but it doesn't show up when I see it on production. This is the website: http://flowersforpeaceproject.com here's my code: base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{% block head_title %} Flowers for Peace {% endblock %}</title> <!-- STYLES --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css?family=Merriweather+Sans:300" rel="stylesheet"> <link href="{% static 'css/base.css' %} " rel="stylesheet"> <!-- Favicon? --> <link rel="shortcut icon" type="image/x-icon" href=""> <!-- Animations --> <link rel="stylesheet" href=""> {% block CSS_File %} {% endblock %} <!-- CSS FILE --> {% block style %} {% endblock %} <!-- INPAGE CSS --> </head> … -
Start celeryd on startup - OS Error (Ubuntu/Django)
I am trying to get celeryd to start when my ubuntu server starts. I have added the appropriate celeryd file to /etc/init.d/ and I have configured my /etc/defaults/celeryd # Name of nodes to start, space seperated list CELERYD_NODES="w1" # Where to chdir at start. CELERYD_CHDIR="/home/my_user/web/my_project/" #Path to celery command CELERY_BIN="/usr/local/bin/celery" #App instance to use CELERY_APP="my_project" # Celery Multi command, this is what handles running multiple workers CELERYD_MULTI="celery multi" # Extra args for celeryd CELERYD_OPTS="--time-limit=300 --concurrency=8" # %n will be replaced with the nodename. CELERYD_LOG_FILE="/var/log/celery/%n.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERY_CREATE_DIRS=1 # Workers should run as an unprivileged user. CELERYD_USER="celery" CELERYD_GROUP="celery" # Where to chdir at start. CELERYBEAT_CHDIR="/home/my_user/web/my_project/" # Extra arguments to celerybeat CELERYBEAT_OPTS="--schedule=/var/run/celery/celerybeat-schedule" When my server starts, or I run service celeryd start I get the following error about the file/directory not existing. The folder does exist and I can run celery manually (not from init.d): Apr 12 19:17:51 ubuntu_server sudo[1520]: my_user : TTY=pts/0 ; PWD=/home/my_user ; USER=root ; COMMAND=/usr/sbin/service celeryd start Apr 12 19:17:51 ubuntu_server sudo[1520]: pam_unix(sudo:session): session opened for user root by my_user(uid=0) Apr 12 19:17:51 ubuntu_server systemd[1]: Starting LSB: celery task worker daemon... -- Subject: Unit celeryd.service has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit celeryd.service has … -
Picture cannot display Django
I've issue related with displaying image from Model.I have caption instead of picture. I don't know what is the cause of that . from django.db import models class Games(models.Model): name = models.CharField(max_length=250) platform = models.CharField(max_length=500) genre = models.CharField(max_length=100) language = models.CharField(max_length=100) image = models.ImageField(upload_to='Images_game',default='' ) # def __str__ (self): # return self.Name class Game_detail(models.Model): game = models.ForeignKey(Games,on_delete=models.CASCADE) subcryption = models.TextField() publisher = models.CharField(max_length=250) date_of_publish = models.DateField() class Order(models.Model): person_name = models.CharField(max_length=24) person_surname = models.CharField(max_length=24) street = models.CharField(max_length=45) city= models.CharField(max_length=45) views.py from django.shortcuts import render from .models import Games,Game_detail,Order from django.shortcuts import render,get_object_or_404,redirect from django.views.generic import ListView,DetailView,CreateView class IndexView(ListView): template_name ='games/list.html' context_object_name = 'all_games' model = Games def get_queryset(self): return Games.objects.all() class Item_Detail (DetailView): context_object_name = 'object' template_name ='games/detail.html' model = Games # tu jest wazna zmiana def get_context_data(self, **kwargs): context = super(DetailView,self).get_context_data(**kwargs) context['Game_detail']=Game_detail.objects.all() return context class Create_order (CreateView): template_name ='games/create.html' model= Order fields = ['person_name','person_surname','street','city'] settings.py from django.conf.urls import include,url from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^games/',include("games.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) list.html template <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> {% for obj in all_games%} <a href ='{%url "detail" pk=obj.pk%}'>{{obj.name}}</a> {{obj.image}} {{obj.platform}} {{obj.genre}} {{obj.language}} … -
Design django models
I am writing a django model for inventory management. There are more than two types of data but maintaining stocks is same is same table. Is the design proper? How can i achieve this in django? Class Board(models.Model): name = models.CharField(max_length=256) boardtype = models.ForeignKey(Boardtype, null=True) gsm = models.IntegerField(default=0) grain = models.CharField(max_length=50) width = models.IntegerField(default=0) height = models.IntegerField(default=0) class Inks(models.Model): name = models.CharField(max_length=256) inktype = models.ForeignKey(Inktype, null=True) color = models.IntegerField(default=0) .... Class inventory(models.Model): value = = models.IntegerField(default=0) stock_type = enum for stock_used/stock_received .... #i want to add a Foriegn_key for Inks/Board/anything -
How to convert a view method to Generic List View?
I have this method on the view page. It works fine and shows everything correctly but I want to convert it into a generic list view so that I could apply pagination to it. Here is the function :` #views.py def index(request): all_artists = Artist.objects.all() all_songs = Song.objects.all() all_albums = Album.objects.all() return render(request, 'index.html', {'all_albums':all_albums,'all_songs':all_songs, 'all_artists':all_artists}) So I followed some tutorials and ended up with this: #new views.py class IndexView(ListView): template_name = 'index.html' context_object_name = 'home_list' queryset = Artist.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['all_artists']=Artist.objects.all() context['all_songs']=Song.objects.all() context['all_albums']=Album.objects.all() Though it compiles without any error, when I render the page, the context object does not gets rendered. Your help is very much appreciated! Thankyou -
Django/Mezzanine/S3/Bootstrap - Looking for local dev / remote production setup suggestions
I'm not having any luck elsewhere so I appreciate any help/suggestions I get here. Here's a rundown of what I'd like to do: Local development environment of Mezzanine, which would also integrate Bootstrap for front-end, static/media served by S3. Push to GitHub with unique config files (settings.py, API keys, S3 settings, etc) in .gitignore. Pull to remote production server for publishing on web. I want to use GitHub as a way to track and display what I'm doing with my website. The problem I'm running into is how to efficiently manage the files in .gitignore to make sure the necessary configs are present on the production server. What would be a "best practice" for this scenario? The local development environment would be used for working on front-end more than back-end but should I have an identical setup locally to match production server setup? For example, serving production static/media with S3, changing db to PostgreSQL for production, etc...should I mirror these on production server manually? One guide I've been reading is https://tutorial.djangogirls.org/en/ but they don't really mention how to manage major back-end differences that aren't shared to the repo. Thanks! -
What is the conventional method to filter pages in the Django-cms rest api?
As far as I know, the django-cms rest api does not provide rest api filters. I need to filter by the published page title so that ?t=XX will return the published version of that page. I've written one, but I'd like to know if I'm using "title_set" appropriately in this case. class PageViewSet(QuerysetMixin, viewsets.ReadOnlyModelViewSet): serializer_class = PageSerializer def get_queryset(self): site = get_current_site(self.request) t = self.request.query_params.get('t', None) queryset = Page.objects.filter(publisher_is_draft=False).all() if t is not None: # return the page with cms_title.title = t return queryset.filter(title_set__title__exact=t) else: # default to the home page return queryset.filter(title_set__title__exact='Home') -
Populate form fields with Django forms after raise validation error
i need help, im new with django forms o how its work.Have a html form and i encrypted the values with javascript when the form is submited like this $("#form").submit(function(){ //remplace the original value and send to the server the encrypted data $("#field1").val(encrypted_data); $("#field2").val(encrypted_data); return true }); I have this class in my django project class SomeForm(forms.Form): field1 = forms.CharField(label="field 1") field2 = forms.CharField(label="field 1") clean_field1(self): data = decrypt_text(self.cleaned_data['field1']) p = re.compile(r'[\d]{8}') #validate decrypt data is a number and his lengt is more than 8 if p.match(data) is None: raise forms.ValidationError("Error") return data this work fine, the problem is when the data es invalid, i need pass to the field the original value, and currently returns the field with de encrypted value. thanks in advance!! -
Django: How to set up Pillow?
I had my app working with ImageField via Pillow. An unrelated issue set off an update domino chain and now I am stuck trying to get Pillow to work. My upgrade to Python 3.6 forced me to upgrade Pillow to version 4, which doesn't seem to work with Django. When I run a check I get: gallery.Photo.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". Of course I have already done that. I upgraded to Django 1.11, but I am still getting this same error. I tried adding Pillow to my INSTALLED_APPS, but it was not found. Besides, I hadn't needed to do that before. How can I troubleshoot this issue? -
Django updating multiple instance with for loop, causing inconsistent behaviour
I am using Django 1.10 with sqlite db. I am observing inconsistent behaviour while updating few instance of Model using for loop. Some times not instance gets updated and sometime one instance is getting update. Any suggestions please... - is there anything I need to put for immediate db write ? - Should I need to change DB from sqlite to some other DB ? Code in views.py for request.POST method looks like this: for p in participant: instance = Participant.objects.get(pk=p.pk) instance.attribute = event instance.save(update_fields=["attribute"]) print("instance attribute :", str(instance.attribute)) print("\now checking\n") for p in participant: print("instance attribute :" str(p.attribute)) -
Automate Lets Encrypt for django with nginx and uwsgi
I'm worried that this question may be one that could be answered very simply if I just knew what to look for, so I apologise if this is something that's been addressed I've set up a production web server for a Django app using nginx and uwsgi. It's got a let's encrypt SSL certificate installed, and now I'd like to automate the renewal. I used the method referenced in this article to add the certificate: https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04 by adding the .well-known directory to the server block. location ~ /.well-known { allow all; } I've tried to keep this but the /.well-known is now 403 forbidden from nginx when the rest of the server config is added (provided below) Can anyone tell me what I've done wrong or how to solve this? here's the server config file: server { listen 80 default_server; listen [::]:80 default_server; server_name www.website.co.uk; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; include snippets/ssl-website.co.uk.conf; include snippets/ssl-params.conf; location = /.well-known/ { root /home/user/website; allow all; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/duncan/Parentheticals; } location / { include uwsgi_params; uwsgi_pass unix:/home/user/website/website.sock; } } Thanks in … -
Saving & Email file in View
I have a Django view where a vendor uploads a document (usually a PDF). I save this document to my static folder, and then email it to the right people. The issue I'm dealing with is file corruption. I think I know the root cause, but I don't have a solution. Example view: def Example(request): if request.method == 'POST': form = upload_doc_form(request.POST, request.FILES) if form.is_valid: f = request.FILES['myFile'] filename = f._get_name() location = open(os.path.join('path\\to\\my\\static\\folder\\', filename, 'wb') for chunk in f.chunks(): location.write(chunk) email = EmailMessage( . . . ) myFile = os.path.join('path\\to\\my\\static\\', filename) email.attach_file(myFile) email.send() return HttpResponseRedirect.... The recipients then receive an email with a corrupted file. My hunch is that the "location" objection needs to be closed after writing to it, but when I do this, the server throws a 500 error.