Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot end "Invalid HTTP_HOST header:" emails [Django/Nginx]
I have been following the Stack Overflow responses about how to end the "Invalid HTTP_HOST header:" emails I receive through Django, but I have not had any luck. I have added the following to my Nginx sites-available configuration, but it hasn't had any effect. This is my current configuration: server { server_name ceemess.com www.ceemess.com; client_max_body_size 4g; location /static/ { alias /webapps/ceemess/cemess/frontend/; } if ( $host !~* ^(ceemess.com|www.ceemess.com)$ ) { return 444; } location / { proxy_set_header Host $host; proxy_pass http://0.0.0.0:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_http_version 1.1; proxy_set_header Connection ""; add_header P3P 'CP=ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; if ( $host !~* ^(ceemess.com|www.ceemess.com)$ ) { return 444; } } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/ceemess.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/ceemess.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.ceemess.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = ceemess.com) { return 301 https://$host$request_uri; } # managed by Certbot if ( $host !~* ^(ceemess.com|www.ceemess.com)$ ) { return 444; } server_name ceemess.com www.ceemess.com; listen 80; return 404; # managed by Certbot } As you can … -
Polymorphic relationships in Django
In Django, how can I create a model that belongs to several models without having to create a foreign key field for each model? Example: An Observation model that is related to any model that can be Observable (Request, Document, Quiz, etc). I've tried contenttypes and it works fine in the shell but I've had problems working with serializers in django rest framework and I'd like to know if there's another way to do it or some package that is useful. Thank you. -
How to connect two existing tables by selected field with django?
I want to make a relationship one to one between the tables by a selected field. I have parcel data with identification field and table with permission attributes containing other data, referencing to parcel identification ield. I am trying to connect these tables with one to one: class Parcels(models.Model): identification = models.CharField(max_length=100,unique=True) area = models.FloatField() class Permissions(models.Model): permission_number = models.Charfield(max_length=40) identification = models.CharField(max_length=50) parcels = models.One(Parcels, to_field='identification',null=True, blank=True, on_delete=models.CASCADE) then I am encapsulating the Parcel serializer in Permissions serializer to be sent to django REST_API. However this does not work. The idea here is that I am periodically adding Permission data to database and need to automatically join the parcel data by identification number. How can I do it in django? -
nginx + uwsgi Django REST response body missing only on some corporate networks
I have a React + Django application deployed using nginx and uwsgi on a single centOS7 VM. The React app is served by nginx on the domain, and when users log in on the javascript app, REST API requests are made to the same nginx on a sub domain (ie: backend.mydomain.com), for things like validate token and fetch data. This works on all recent version of Firefox, Chrome, Safari, and Edge. However, some users have complained that they could not log in from their work network. They can visit the site, so obviously the javascript application is served to them, but when they log in, all of the requests come back with status 200, except the response has an empty body. (and the log in requires few pieces of information to be sent back with the log in response to work). For example, when I log in from where I am, my browser's network tab looks like the screenshot below: You can see that the validateToken end point responds with status=200, and a json object with few parameters. But when one of the users showed me the same from their browser, they get Status=200 back, but the Response is empty. … -
Celery task in which need to update field after 1 month pass after creation
Idea is create celery task, in which after 1 month from creation (created_at field) update price field with 5% discount. Model: class Product(models.Model): price = models.DecimalField(max_digits=15, decimal_places=2, help_text="Current price of products") old_price = models.DecimalField(max_digits=15, decimal_places=2, help_text="Old price of products", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) -
Ruby to Django Conversion
I want to convert a backend written in Ruby to Django. I know Django, I already familiarize myself with Ruby syntax but I am sure it is not enough. I appreciate any tips and advice. Thank you -
No redirection occurs after form validation
Faced a problem that I can't solve, who knows, please help.I have 2 forms on the page, these forms are from two different models (User and Profile). The problem is that one form always fails validation, even if it is filled out correctly, because of this I cannot use success_url, and I really need to redirect the user to a new slug, how can I redirect the user differently? For some reason after the first check my object disappears, if I use the condition "if object.user == user", without this condition the object appears file views.py: class ProfilePage(FormView): template_name="market/profile.html" form_class=ProfileUpdateForm second_form_class= UserUpdateForm success_url="profile" def get(self, request, *args, **kwargs): context = self.get_context_data(object=get_object_or_404(Profile,slug=self.kwargs['slug'])) print(context) return self.render_to_response(context) def get_context_data(self, **kwargs): context = super(ProfilePage,self).get_context_data(**kwargs) context['UserUpdateForm'] = UserUpdateForm( prefix='UserUpdateForm', data = self.request.POST if bool(set(['UserUpdateForm-submit-counter-bid', 'UserUpdateForm-submit-approve-bid', 'UserUpdateForm-submit-decline-further-bids']).intersection( self.request.POST)) else None, instance=self.request.user, ) context['ProfileUpdateForm'] = ProfileUpdateForm( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) return context def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) if context['UserUpdateForm'].is_valid(): context['UserUpdateForm'].save() elif context['ProfileUpdateForm'].is_valid(): context['ProfileUpdateForm'].save() return self.render_to_response(context) file profile.html: <p>{{object}}</p> {% if object.user == user %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ UserUpdateForm.as_p }} <input type="submit" name="{{ UserUpdateForm.prefix … -
DRF: How to prefetch a queryset for my properties?
I have a lot of properties on my model Author. Each of them uses self.book_set. class Author(models.Model): #.... @property def book_impressions(self): return self.book_set.aggregate(Sum("impressions").get("impressions__sum") or 0 @property def book_reach(self): return self.book_set.aggregate(Sum("reach").get("reach__sum") or 0 # more @property here... class Book(models.Model): author = models.ForeignKey(Author) reach = models.IntegerField() impressions = models.IntegerField() # .... I have a view responsible for retrieving a single Author. As you might imagine the database is hit very often. Where is the right point to insert my prefetch_related? -
Formatting checkboxes in django
i'm trying to add some checkboxes into my form and to make them look nice. The thing is that when I use {{form.checkBoxFilter}} the output is like: I would like to have them inline and readable, unfortunately using crispy forms renders them too close to each other. I found that looping through elements will place them inline but still they're close to each other (their labels are much longer than shown below). {% for x in filter.weights%} {{x}} {%endfor%} Where to put my css in this case? -
Best way to use simple asynchronous queues in django?
I need my django view function to trigger a task which will then run in the background, not blocking the response. def my_task(client_information, unique_id): # task #do something that takes a while def my_view(request): # django view client_information = request.GET.get('whatever') # get some information passed from the client unique_id = generate_unique_id() # generate a unique ID for this task start_task(client_information, unique_id) # the interesting part: start the task with client information and unique id, but non blocking return JsonResponse({'id': unique_id}) I read about celery, but the code I saw looked overkill as I don't need any further communication between the processes and I really want a as lightweight as possible solution. -
Django rest framework with dynamo db
I am new to django rest framework and has some knowledge about it .I did worked with sqlite and postgres Sql database connection,but currently I have given the task in which I need to use DynamoDb with Django rest framework. Are there any proper ways to connect the django rest framework to Dynamo db in settings.py file? because there is no official document about this, and I came across only few vedios where they have explained connecting with mangoDb(noSql) but not with dynamo Db. Any helps will be appreciated. Thanks in advance. -
Django render 2 html files separately on the same page
Background: I am using Django to build my website but am having problems extending some of my pages with a header because of conflicting packages. I am using TinyMCE to render some text and Materialize to make a navbar. The problem is that materialize uses li and some other properties for rendering some stuff so it alters them. This causes problems because now the same property is being called by 2 different packages to do 2 different things. Here is an example: This code will create a navbar using materialize: $(document).ready(function(){ $('.sidenav').sidenav(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <nav class="red" style="padding:0px 10px; position: fixed;"> <div class="nav-wrapper"> <a href="#" class="brand-logo">Web Zone</a> <a href="#" class="sidenav-trigger" data-target="mobile-nav"> <i class="material-icons">menu</i> </a> <ul class="right hide-on-med-and-down " > <li><a href="#">Home</a></li> <li><a href="#">Video</a></li> <li><a href="#">Service</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </div> </nav> <ul class="sidenav" id="mobile-nav"> <li><a href="#">Home</a></li> <li><a href="#">Video</a></li> <li><a href="#">Service</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> And this will create some bullet points: <ul> <li>Bullet 1</li> <li>Bullet 2</li> <li>Bullet 3</li> <ul> But if I try and render them together this is the result: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <nav class="red" style="padding:0px 10px; position: fixed;"> <div class="nav-wrapper"> <a … -
Django: Difficulties by uploading an image
return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type int) This is what I get by sending this API request to the server: I've added this code because without it raises errors as these: File "/home/dziugas/winteka/winteka/main/serializers.py", line 31, in create type=validated_data['type'], KeyError: 'type' I fixed it with this: if validated_data['user']: user = Users.objects.all().filter(pk=validated_data['user']) if not user: return JsonResponse({'error': 'user was not found'}, status=404) But as I said, I get errors when trying to create a new object. This is my serializer: class ReportSerializer(serializers.ModelSerializer): class Meta: model = Reports fields = ('status', 'type', 'user', 'attached_message', 'attached_photo', 'date_created') def create(self, validated_data): if validated_data['user']: user = Users.objects.all().filter(pk=validated_data['user']) if not user: return JsonResponse({'error': 'user was not found'}, status=404) report = Reports( status=validated_data['status'], type=validated_data['type'], user=user, attached_message=validated_data['attached_message'] or None, attached_photo=validated_data['attached_photo'], date_created=validated_data['date_created'], ) And this is my model: class Reports(models.Model): # Report fundamental stuff public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) status = models.IntegerField(choices=StatusTypes, blank=False, null=False, default=0) type = models.IntegerField(choices=ReportTypes, blank=False, null=False, default=10) # User Module user = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='+', null=False) # Post Required Stuff reports = models.IntegerField(blank=False, null=False, default=0) upvotes = models.IntegerField(blank=False, null=False, default=0) downvotes = models.IntegerField(blank=False, null=False, default=0) comments = models.ManyToManyField('main.ReportMessages', related_name='+') attached_message = models.CharField(max_length=300, null=True, blank=True) attached_photo = models.ImageField(null=False, blank=False, … -
Unable to create a new session key. It is likely that the cache is unavailable
I am running bitnami/redis helm chart in my kubernetes cluster. my django app is using it as a session cache. CACHES = { 'default': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis-service:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } heres how my session_engine variable looks like SESSION_ENGINE="django.contrib.sessions.backends.cache" This setup worked just fine when I was running redis as a single replica deployment. when I switched to bitnamis helm chart (with sentinel) I started getting this error intermittently. Unable to create a new session key. It is likely that the cache is unavailable. If I switch over to single pod Redis deployment it works fine. but using a bitnami helm chart seems to be causing this issue. I can confirm I can reach the Redis cluster from my Django pod. what's more confusing is it's causing intermittently. any help will be much appreciated. -
How to take a string as input in django?
I'm working on a Django project where I have to take a Product name from the search bar & pass the name through a python script where the script will scrape some data from a website & store it in a list. Then it will go to the result.html page & show the data. How should I take the product name from the search box & where should I place the python script? How can I loop over the list data & show it in the result.html ? -
All the datas are populated into a single row
I am a beginner in scraping. I have scraped some data. Here are two problems: All of the data are populated into a single row and every time when I refresh the page, each time the data is saved into the database. import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup from .models import Content toi_r = requests.get("some web site") toi_soup = BeautifulSoup(toi_r.content, 'html5lib') toi_headings = toi_soup.findAll("h2", {"class": "entry-title format-icon"})[0:9] toi_category = toi_soup.findAll("a", {"class": ""})[0:9] toi_news = [] toi_cat =[] for th in toi_headings: toi_news.append(th.text) for tr in toi_category: toi_cat.append(tr.text) #saving the files in database n = Content() n.title = toi_news n.category = toi_cat n.save() -
Django rest: Dynamically include or exclude Serializer class fields
I want filds of serializer dynamical include or exclude.In application after each lesson there will be a quiz but there are moments there are no quiz of the lesson, for this I need to create dynamic fields for Serializers. I try by docs DRF. But my code doesnt work quiz/models.py class Quiz(TrackableDate): name = models.CharField(max_length=100) description = models.CharField(max_length=70) slug = models.SlugField(blank=True, max_length=700, default=None) is_active = models.BooleanField(default=False) def __str__(self): return self.name course/views.py class AuthLessonDetailSerializer(AuthLessonSerializer): quiz = serializers.CharField(source='quiz.slug') class Meta(LessonSerializer.Meta): fields = AuthLessonSerializer.Meta.fields + \ ('description', 'link', 'quiz') def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super( ).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) error Got AttributeError when attempting to get a value for field `quiz` on serializer `AuthLessonDetailSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Lesson` instance. Original exception text was: 'NoneType' object has no attribute 'slug'. -
Can't import ObtainAuthToken
I am new to Django. In the course that i'm using he is importing ObtainAuthToken like this: from rest_framework.authtoken.views import ObtainAuthToken But when i try to do the same thing i get this exception: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. What am i doing wrong? I have added both my app and 'rest_framework' to my Installed_Apps. If this needs clarification i can send my views and urls files also. Thanks :) -
How do websites like ytmate download the video in the browser
I have been trying to make a web app for a little college project. The app is just like ytmate.com where you can download youtube or other platform’s video on your local machine. I am using Django and pytube to make the app. The problem is, the app does not download the video from the browser. It just downloads it in the path the app is in. The problem with this is that when the app will be deployed, anyone who uses it will keep on downloading the app on the external server the app has been hosted on. How can I make sure it downloads in the browser of the user and not on the server? I already thought of first downloading the app on the server and return the file in the user’s browser by using content headers. But that’s not the optimal solution and it will slow down the process. I just need some guidance on how this app can be implemented. Sorry about not posting the code. I just need to know how this app could be implemented. -
How to generate a MongoDB file from Postgres data
how to generate a MongoDB file from Postres data Or more exactly generate a JSON file (from Django using Postgres as Database) to integrate it via an API-Rest in a MongoDB database. -
Apache logs with WSGI ModuleNotFoundError
According to Bitnami's documentation, I've followed their desired steps Enable WSGI configuration for the Django application Enable predefined virtual hosts for a Django project Configure Django project for public access Create a custom virtual host In the end of the documentation, it states You should now be able to browse to your project at http://SERVER-IP/PROJECT/APP. In this case SERVER-IP: 35.178.211.120 PROJECT: tutorial APP: hello_world If I go to the following locations http://35.178.211.120/ http://35.178.211.120/tutorial/ http://35.178.211.120/tutorial/hello_world I get Internal Error 500. If I check the logs /home/bitnami/stack/apache2/logs [Tue Sep 29 18:33:16.858668 2020] [wsgi:error] [pid 1473] [remote 109.51.236.49:57609] ModuleNotFoundError: No module named 'PROJECT' -
Django URL tag not working - NoReverseMatch
I know we aren't supposed to use stackoverflow for debugging but i've been trying to fix this in the last 10 hours and I feel hopeless, my apologies. #main project urls.py: urlpatterns = [ ... path('accounts/',include('employee.urls')), ... ]... #employee.urls: urlpatterns = [ ... path('employees/', views.display_employees), path('edit/<str:employee_ssn>/', views.edit_employee), ... ] #views.py - edit_employee being used only for testing by now def display_employees(request): logged_user = request.user queryset = Employee.objects.filter(company=logged_user.company) context = { 'employees': queryset } return render(request, 'employees.html', context) def edit_employee(request, employee_ssn): context = {} emp = Employee.objects.filter(ssn=employee_ssn) context = { 'employee_list': emp } return render(request, 'edit-employee.html', context) #employees.html <ul> {% for obj in employees %} <li>{{ obj.name }}</li> <li>{{ obj.ssn }}</li> <li>{{ obj.email }}</li> <li><a href="{% url '/accounts/edit/' obj.ssn %}">edit</a></li><br> {% endfor %} </ul> #edit-employee.html <ul> {% for obj in employee_list %} <li>{{ obj.name }}</li> <li>{{ obj.ssn }}</li> <li>{{ obj.email }}</li> {% endfor %} </ul> When it is clicked on edit it says: Exception Type: NoReverseMatch Exception Value: Reverse for '/accounts/edit/' not found. '/accounts/edit/' is not a valid view function or pattern name. But if the url http://localhost:8000/accounts/edit/<employee_snn>/ is typed on the browser, edit-employee.html renders normally. It also says the error is in my base template at line 0 -
Float() argument errors in Django
I was trying to integrate the Machine Learning algorithm in Django. But I am having the following error: I don't know why I am getting this error though I have passed the value properly as far as I am aware of. Here I have included the codes too: Index.html file: Views.py file: Please help me out with this problem. -
Django changing datefield to arrayField
I'm currently migrating my whole project to PostgreSQL. I have 2 fields that I'd like to change to ArrayField, but I encountered this error. Here's the former code: weight = models.FloatField(max_length=20, blank=True, null=True) date = models.DateField(auto_now_add=True) Here's what I've changed: weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True) ) date = ArrayField( models.DateField(auto_now_add=True) ) (ArrayField is imported) When I'm trying to use makemigrations there are no errors. But, when I use the migrate command I get this error django.db.utils.ProgrammingError: cannot cast type date to date[] -
how to repeat a peice of code in django html?
i am new to django and i have a peice of code that i need to repeat it for 10 times but i dont know how to make it repeatable. here you can see the code i wanna use 10 times.it is for <<region 1>> and i want to use it to make region 1 to region 10.all the "1"s in "href" and "id" and ... should be replaced by 2,3,4,...,10 . <div class="card"> <div class="card-header background"> <a class="card-link text-dark" data-toggle="collapse" href="#collapseOne"> Region 1 </a> </div> <div id="collapseOne" class="collapse show" data-parent="#accordion" > <table class="table table-striped table-condensed "> <thead> <tr> <td scope="col" class="text-secondary"></td> <td scope="col" class="text-secondary ">MeterNumber</td> <td scope="col" class="text-secondary text-center">Data</td> <td scope="col" class="text-secondary text-center">Chart</td> <td scope="col" class="text-secondary text-center">Detail</td> </tr> </thead> <tbody> {% for each in objectlist %} {% if each.region == 1 %} <tr> <td style="width: 7%" scope='row' class="align-middle pl-3"> {% load static %} <img src="{% static "images/meter.svg" %}" alt="My image" height="35" width="35">{% if each.mode == 2 %}<span class="dot-online padding-0 align-bottom"></span>{% endif %}{% if each.mode == 1 %}<span class="dot-notconf align-bottom"></span>{% endif %}{% if each.mode == 3 %}<span class="dot-maintenance align-bottom"></span>{% endif %} <td style="width: 12%" class="text-secondary align-bottom table-row" id="{{ each.id }}" data-href="http://127.0.0.1:8000/specificMeter/" ><h6> {{ each.MeterBodyNumber }} </h6></td> <td style="width: 22%" class="text-secondary …