Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django application fails to deploy on AWS ElasticBeanstalk with 'firebase-admin' library
I am deploying my python/django application to aws elasticbeanstalk. It gets deployed fine if i don't specify 'firebase-admin' library in requirements.txt. But fails to deploy if i add 'firebase-admin' no matter what version in requirements.txt as shown below: Here's my requirements.txt: Django==3.0.1 djangorestframework==3.11.0 psycopg2==2.7.3.1 django-cors-headers==3.2.0 pytz==2017.2 tinys3==0.1.12 apiclient==1.0.3 drf_yasg==1.17.1 google-api-python-client==1.7.3 google-auth==1.5.0 google-auth-httplib2==0.0.3 httplib2==0.11.3 django-rest-auth==0.9.5 oauth2client==4.1.2 geographiclib==1.50 geopy==1.20.0 numpy==1.15.2 pyyaml==5.3.1 And AWS elasticbeanstalk python instance details: Python 3.6 running on 64bit Amazon Linux/2.9.7 Please Help. Thanks -
django allauth template tags not working in custom template
I have added the following code in verification_sent.html file. But template tags do not work on templates. # templates/account/verification_sent.html {% extends 'primary/_base.html' %} {% load i18n %} {% block content %} <h1>{% trans "Verify Your E-mail Address" %}</h1> {% load account %} {% user_display user as user_display %} {% blocktrans %}{{ user_display }}, Confirmation email has been sent to your email address{% endblocktrans %} {% endblock content %} Result shows as below Verify Your E-mail Address AnonymousUser, Confirmation email has been sent to your email address. How can I get the Registered user full name and email address from template file? -
import requests is showing error in python but it is showing in pip3 list
import request is not workingIf I am trying to install requests it is showing requirement already satisfied but If I am trying to import then it is throwing error. Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'requests'. I am running the command pip3 list then it is showing requests 2.23.0. but not able to import. -
Entering Abstract Base User Data - IntegrityError: UNIQUE constraint failed
My goal is to create a user account model with AbstractBaseUser. My application requires data that fits into multiple categories. i.e. name city age because there are a lot of questions to be asked of the user, I have tried separating each category into a separate form, view, and template. For example: models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) Name = models.CharField(max_length=30, unique=False) City = models.CharField(max_length=30, unique=False) Age = models.CharField(max_length=30, unique=False) forms.py: class NameForm(forms.ModelForm): class Meta: model = Account fields = ('Name',) class CityForm(forms.ModelForm): class Meta: model = Account fields = ('City',) class AgeForm(forms.ModelForm): # . . . views.py def NameView(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): Name = request.POST['Name'] form.save() return redirect('City') else: form = NameForm() return render(request, 'account/Name.html', {'form': form}) def CityView(request): if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): City = request.POST['City'] form.save() return redirect('Age') else: form = CityForm() return render(request, 'account/City.html', {'form': form}) def AgeView(request): # . . . I was expecting that I would be able to upload segments of user data in separate pages, however, after uploading the first page "Name", and attempting to upload the second page "City", I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: account_account.email … -
Showing certian categories first while iterating
Currently I order my categories by doing "categories": category.objects.order_by('-title') I want to have full control over what order each object appears. I was thinking of having a rank attribute rank = models.IntegerField() however I feel like there could be 2 category objects with a rank of '1' which doesn't make sense. -
Failing To Display Media File Django
I have created a model called Product that takes in an ImageField that will be upload on a function I created: class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99) image = models.ImageField(upload_to=upload_image_path, null= True, blank=True) def __str__(self): return self.title return self.image def __unicode__(self): return self.title I have also created my MEDIA_ROOT and STATIC_ROOT below is code from main urls however I also defined this two on the settings.py: if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So I am able to upload Image from the admin and it uploads properly to the media_root that I created. When I try calling/displaying the image it render nothing I do not know where I could have made a mistake {% load static %} {{ object.title }} <br/> {{ object.description }} <br/> {{ object.image.url }}<br/> <img src="{{ object.image.url }}" class='img-fluid'/> but the {{ object.image.url }} actually gives me the exact path of the Image which should make sense for the the picture to rendered. This is the the result output that I was telling about, that I'm getting the image url but I can not display the Image -
Django+Supervisor+NGINX on Ubuntu server 18.04. Attempt to write a read only database
I am trying to deploy my website in Django+Supervisor+NGINX on Ubuntu server 18.04. gunicorn.conf.py bind = '127.0.0.1:8000' workers = 3 user = "nobody" Here is my .conf (supervisor): [program:ako] command=/home/oleg/dj/venv/bin/gunicorn ako.wsgi:application -c /home/oleg/dj/ako/ako/gunicorn.conf.py directory=/home/oleg/dj/ako user=nobody autorestart=true redirect_stderr=true stdout_logfile=/home/oleg/dj/ako/ako_supervisor.log stderr_logfile=/home/oleg/dj/ako/ako_supervisor.log autostart=true autorestart=true startsecs=10 conf. NGINX server { listen 80; server_name 95.217.187.37; access_log /var/log/nginx/example.log; location /static/ { root /home/oleg/dj/ako/rsf/; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } When I try to launch gunicorn with a stopped supervisor: sudo service supervisor stop on the root of my project gunicorn ako.wsgi:application everything properly works : Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64) (venv) root@t-20200417:~/dj/ako# gunicorn --bind 0.0.0.0:8000 ako.wsgi [2020-04-18 13:44:15 +0200] [1768] [INFO] Starting gunicorn 20.0.4 [2020-04-18 13:44:15 +0200] [1768] [INFO] Listening at: http://0.0.0.0:8000 (1768) [2020-04-18 13:44:15 +0200] [1768] [INFO] Using worker: sync [2020-04-18 13:44:15 +0200] [1771] [INFO] Booting worker with pid: 1771 The website normally runs under http://95.217.187.37/rsf/f_size_water/ and everything properly works. When I start supervisor sudo service supervisor start the website is still reachable, static links are still working, but the dynamic content does not work. When a user in his browser changes the language in the menu "homepage language … -
Can't install django using pip. I have tried many things but nothing worked
ERROR: Exception: Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 548, in site_packages_writable return all( File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "c:\program files\python38\lib\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "c:\program files\python38\lib\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\program files\python38\Lib\site-packages\accesstest_deleteme_fishfingers_custard_zsocdh' -
How to access Pivot Table ahead in Django Models
I have 3 models as following class User(models.Model): name = models.CharField(max_length=20, unique=True) class Job(models.Model): name = models.CharField(max_length=20, unique=True) class Slot(models.Model): name = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField(Job, related_name = 'slots') As you can see I am able to create Pivot table for Job_slot, with the Primary key of that Table I need to create a table between User and job_slot, where I can have something like following Thanks in advance for solving this complex problem That I am trying to solve for more than 5 hours!! -
How do I create an API endpoint with django rest framework jwt for when user is logged_in?
I am trying to create an endpoint for when a user is logged in to check the status of user is logged in react js. For my backend, I use django rest-framework. Here is the backend code. serializers.py: from rest_framework import serializers; from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) # handle signups only class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) inst = self.Meta.model(**validated_data) if password is not None: inst.set_password(password) inst.save() return inst class Meta: fields = ('token', 'username', 'password') urls.py: The following code is where I would create the endpoint from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import verify_jwt_token urlpatterns = [ path('api-auth/', include('rest_framework.urls')), # path('rest-auth/', include('rest_auth.urls')), # path('rest-auth/registration/', include('rest_auth.registration.urls')), path('token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), path('login/', include('login.urls')), path('admin/', admin.site.urls), path('api/', include('menus.api.urls')), path('phlogapi/', include('phlogfeeder.phlogapi.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am confused on how to create a endpoint with jwt. -
django ORM annotate of sum of integers divide by sum of floats some how fail
class CSVFile(models.Model): installs = models.fields.IntegerField() spend = models.fields.FloatField() # this give me weird error! CSVFile.objects.annotate(metric=Sum('installs') / Sum('spend')) # but this will fix it! any idea why? CSVFile.objects.annotate(metric=Sum('installs', output_field=FloatField()) / Sum('spend')) sum of integers divide by sum of floats some how fail! database is SQLite django 3.05 -
Add data from request POST into a table template [Django, Python]
I create a table show book info from SQLite database and I'm trying to create an "Add New Book form" to make it add a new book into a table database. How can I add a book and then make it show into the table Book Info ? <div class="container-fluid"> <!-- Add Book --> <div class="add-book"> <h1>Add a Book</h1> <form action="/add_book" method="POST" class="add_more_book"> {% csrf_token %} <p> <label for="title" id="title">Title:</label> <input type="text" name="title" class="form-control" id="input-title" /> </p> <p> <label id="desc" for="desc">Description:</label> <textarea class="form-control" name="description" id="input-desc" rows="3"></textarea> </p> <button type="submit" class="btn shadow btn-primary" id="addbtn"> Add </button> </form> </div> <!-- End of Add Book --> <!-- Book info --> <div class="book-info"> <form action="/" method="POST"> {% csrf_token %} <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Action</th> </tr> </thead> <tbody> {% for i in all_books_info %} <tr> <th scope="row">{{i.id}}</th> <td>{{i.title}}</td> <td><a href="/books/{{i.id}}">Views</a></td> </tr> {% endfor %} </tbody> </table> </form> </div> -
PyCharm Doesn't Recognize Installed Django App
I created a Django project and then started and app, but in project_name/project_name/urls.py, PyCharm doesn't recognize my app_name when I say from app_name import views. But running the project from the command line works. Ideas? I'm using a virtualenv and the Anaconda distribution of Python 3.7.3. Pycharm 2020.1 on Windows. -
multiline chart.js + Django graph does not rendering properly
i have spent the whole day trying to figure out what is going on with this graph not rendering in html. I can't find out what I am doing wrong here. the closest post that I found was this one Django and Chart.js Not Rendering Graph Correctly the help provided there does not do the trick. My underlying issue is that I am not sure how to pass my data inside of the graph. here is my js script function setChart(){ var ctx5 = document.getElementById('myChart5').getContext('2d'); var myChart5 = new Chart(ctx5, { type: 'line', data: { labels: ["days-15","days-14", "days-13","days-12","days-11","days-10","days-9","days-8","days-7","days-6","days-5","days-4","days-3","days-2","days-1"], datasets: [{ label: 'Number of orders placed', data: [ {% for dr in tableau1 %}{{ dr.number_of_orders_placed}}, {% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 }, { label: 'purchased_quantity', data: [{% for dr in tableau1 %}{{ dr.purchased_quantity}},{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 }, { label: 'sold_quantity', data: [{% for dr in tableau1 %}{{ dr.sold_quantity}},{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 } ], options: { scales: { yAxes: … -
on Django, how can i pull data from database to a new html template from a html form, using a non logged in user input?
I have a form that is saving the data to the database and i want to open the template with the values from the database that I already calculated on models.py and saved to the database, this is the first tool I am developing on python so maybe I am asking the wrong question. So far the info that I want to pull is already saved on the Django Database. I want to pull the data from the "current user" form submission. so my question is how do I call current user DB info to the template when they click "get an estimate". This is what I have on views: class RackView(TemplateView): template_name = 'estimate/estimate_details.html' def get(self, request): form = RackForm() racks = Rack.objects.all() users = User.objects.all() args = {'form': form, 'racks': racks, 'users': users} return render(request, self.template_name, args) def post(self, request): form = RackForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user #try changing here to "pk" or "id" instead of user if it doesnt work or try dreating a user with name and email post.save() text = form.cleaned_data['post'] form = RackForm() args = {'form': form, 'text': text} return redirect('estimate_details: estimate_details') def estimate_details(request,pk=None): if pk: user = User.objects.get(pk=pk) else: … -
Django Admin Panel multiple choice all selected
I am adding a model to my admin panel in Django. It looks like this.. class Property(models.Model): event = models.ManyToManyField(Event) name = models.CharField(max_length=255) applicable_devices = models.ManyToManyField(Device) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = models.CharField(max_length=255) For the field event it corresponds to another model of mine. In the admin panel it gives me a mutliple choice field to select the ones it applies to. I am trying to find a way to make it select all of them by default. When I going to be adding these properties, it will be applying to all events the majority of the time. I am just trying to save some clicks from selecting all. -
send list of object with data attr in django template
I built an image sharing website with django and jquery and I want when clicking on image rise comment of image with modal but for doing so we need to send list of my comment of image. If we want to send only one object we can use data-* attribute and jquery but for sending a list of objects this mehod doesn't work any more. Is this any way for sending list of object with data-* attribute? -
Django case when else in filter
I need a similar code to this SQL: SELECT * FROM tab WHERE a = CASE WHEN x IS NULL THEN b ELSE c END my attempt, but to no success: model.objects.filter(a=Q(Case(When(x__isnull=True, then='b'), default='c'))) when I try to run, I get this error: Traceback (most recent call last): File "<input>", line 2, in <module> File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1340, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q check_filterable=check_filterable, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1249, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1058, in resolve_lookup_value value = value.resolve_expression(self, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query_utils.py", line 95, in resolve_expression check_filterable=False, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q check_filterable=check_filterable, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1237, in build_filter arg, value = filter_expr TypeError: cannot unpack non-iterable Case object -
How to handle user reports for content e.g. inappropriate posts and profiles?
My Django app will allow users to report inappropriate posts and profiles etc. I want to be able to store these reports so that they can be reviewed by an admin. The ways I'm thinking of doing it is to either create a table in the database and store it there or just store it in a CSV / text file. Is there a better way to handle this feature? -
Passing Javascript variables to python main.views in Django
I am trying to send a variable from javascript to a python function in main.views, and I am using the Django web framework. I am very new to web development and I would really appreciate it if you showed some code for how to do it. Here is my variable (in home.html): <script> var my_var = 10; </script> and I need to send this to a function in main.views. My main.views looks like this so far: from django.shortcuts import render def homepage(request): return render(request, "main/home.html") def get_var(request): my_var = # I WOULD LIKE TO RECEIVE THE VARAIBLE HERE print(my_var) and so far here is my main.urls: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path("", views.homepage, name="homepage"), ] Thanks for the help! -
getting 'bytes' object has no attribute 'encode'
my task is : upload a CSV file in Django model my model.py is given below from django.db import models # Create your models here. class Chart(models.Model): date=models.DateTimeField(blank=True,null=True) open=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) high=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) low=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) def __str__(self): return self.str(date) class NSEBHAV(models.Model): symbol=models.CharField(max_length=20,null=True,blank=True) series=models.CharField(max_length=2,null=True,blank=True) open=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) high=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) low=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) last=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) prev_close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) tottrdqty=models.IntegerField(null=True,blank=True) tottrdval=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) timestamp=models.DateTimeField(blank=True,null=True) totaltrades=models.CharField(max_length=20,null=True,blank=True) isin=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.symbol my view.py is given below import csv,io from django.shortcuts import render from django.contrib import messages from .models import NSEBHAV,Chart # Create your views here. def upload_nse(request): template='upload.html' data=NSEBHAV.objects.all() prompt={ 'order': 'Order of the CSV should be (symbol,series,open,high,low,close,last,prevclose,tottrdqty,tottrdval,timestamp,totaltrades,isin', 'profiles': data } if request.method=='GET': return render(request,template,prompt) csv_file=request.FILES['file'] print(csv_file) # if not csv_file.name.endwith('.csv'): # messages.error(request,'This is not csv file') data_set=csv_file.read().encode('utf-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quotechar="|"): _, created = NSEBHAV.objects.update_or_create( symbol=column[0], series=column[1], open=column[2], high=column[3], low=column[4], close=column[5], last=column[6], prevclose=column[7], tottrdqty=column[8], tottrdval=column[9], timestamp=column[10], totaltrades=column[11], isin=column[12] ) context = {} return render(request, template, context) csv.file sample is error screenshot my html file is is given below: thanks in advance . if i use encode is is giving same error and also i want to check type of uploaded file is csv or not -
[Django][ModelForm] Objects from ModelForm are saved properly under debugger, but in normal mode some fields are not saved
I am giving up slowly, please help! I have three-step form to create two objects Pet and LostPet. Step1: Field1 - Pet.name Field2 - Pet.type Field 3 - LostPet.owner_name Field 4 -LostPet.event_date etc. Step2: additional info about Pet Field1 - Pet.chip_number Field2 - Pet.color Step3: Thank you page In Step1 I am just displaying form, In Step2 I am creating Pet object only with name, type and I save it: if request.method == 'POST': form = LostPetSteModel1a(request.POST, instance=pet) if form.is_valid(): pet.save() I also create LostPet object linked with brand new Pet: lostpet_form = LostPetStepModel1b(request.POST, request.FILES, instance=lostpet) lostpet.pet = pet lostpet.save() In the last step I am fetching Pet object from DB and update with additional fields from form2: pet = Pet() pet_form = AnimalLostPetStep2(request.POST, instance=pet) pet_db = get_object_or_404(Pet, id=request.session['pet']) pet.animal_id = pet_db.animal_id pet.pk = pet_db.pk pet.name = pet_db.name pet.save() Under debugger session, everything works ok, In the normal runserver mode I don't have few fields saved. Basically it is email address from LostPet model and all the additional fields from Step2. As I mentioned when I debug it step by step, it works ok. All the fields are properly filled and saved to the database. Do you know what is … -
Iterate over lists of form fields in a template
I am attempting to group my form fields so that I can iterate over each group separately within my template: # app/forms.py from django import forms class CustomForm(forms.Form): field1 = forms.FieldClass(label="Field 1") field2 = forms.FieldClass(label="Field 2") field3 = forms.FieldClass(label="Field 3") field4 = forms.FieldClass(label="Field 4") group1 = [field1, field2] group2 = [field3, field4] # app/templates/app/formTemplate.html <form method="POST"> <div> {% for field in form.group1 %} <p style="display: block"> {{ field.label }} <span style="float: right"> {{ field }} </span> </p> {% endfor %} </div> <div> {% for field in form.group2 %} <p style="display: block"> {{ field.label }} <span style="float: right"> {{ field }} </span> </p> {% endfor %} </div> </form> As far as I am aware, this ought to display as: Field 1 INPUT FIELD 1 HERE Field 2 INPUT FIELD 2 HERE Field 3 INPUT FIELD 3 HERE Field 4 INPUT FIELD 4 HERE But what I get instead is: Field 1 <django.forms.fields.CharField object at ...> Field 2 <django.forms.fields.CharField object at ...> Field 3 <django.forms.fields.CharField object at ...> Field 4 <django.forms.fields.CharField object at ...> Additionally, if I use {% for field in form %} instead of {% for field in form.groupX %} it will render as expected (except that it will have … -
Django 3.0.5 with mod_wsgi: AttributeError: 'HttpResponse' object has no attribute '_resource_closers'
I'm getting an error when I deploy Django 3.0.5 under mod_wsgi: AttributeError: 'HttpResponse' object has no attribute '_resource_closers'. I'm running: Python: 3.6.8 Django: 3.0.5 Apache: 2.4.6 mod_wsgi: 4.6.2 Here's the basics of the view causing the error; nothing too exotic (I've simplified the code around meetings_struct): class MeetingsAPIView(MeetingsBaseView): def get(self, request, *args, **kwargs): meetings = self.get_meetings() meetings_struct = [] for meeting in meetings: meetings_struct.append({ "id": meeting.id, "name": meeting.title, "slug": meeting.slug, }) return HttpResponse(meetings_struct, content_type="application/json") If I activate the venv and use runserver manually on the server on port 80, the same view does not give an error. When the same code and venv are running under Apache, here's the error from Apache's logs: [Sat Apr 18 16:11:30.683980 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] mod_wsgi (pid=4154): Exception occurred processing WSGI script '/var/django/sites/mysite-prod/config/wsgi.py'. [Sat Apr 18 16:11:30.684834 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] Traceback (most recent call last): [Sat Apr 18 16:11:30.684891 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] File "/var/django/sites/mysite-prod/venv/lib64/python3.6/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ [Sat Apr 18 16:11:30.684903 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] response = self.get_response(request) [Sat Apr 18 16:11:30.684925 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] File "/var/django/sites/mysite-prod/venv/lib64/python3.6/site-packages/django/core/handlers/base.py", line 76, in get_response [Sat Apr 18 16:11:30.684933 2020] [wsgi:error] [pid 4154] [remote … -
django redirecting http to https
I'm trying to redirect www.example.com and http://www.example.com to https://www.example.com. In the settings file, I've added : SECURE_SSL_REDIRECT = True SECURE_SSL_HOST = 'https://www.example.com' but it redirects toward https://true.com. I've added : SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True no to avail.