Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I stop the significant amount of [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header from strange sites I'm getting?
Since adding the option to email me (the admin) when there are problems with my Django server, I keep getting a LOT of the following emails (20 in the last hour alone). [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'staging.menthanhgiadalat.com'. You may need to add 'staging.menthanhgiadalat.com' to ALLOWED_HOSTS. I've set my server up to have the following at the top of the file in my sites-enabled nginx config as I read (somewhere on SO) that this would may prevent me from getting these types of emails: server { server_name _; return 444; } But it hasn't done anything. In the next server block I have the IP address and domain names for my site. Could this be causing the problem? This 'staging' site isn't the only domain I'm being asked to add to my ALLOWED_HOSTS. But it is, by far, the most frequent. Can I stop this type of alert being sent? Can I stop it from being raised? Is there something I've configured incorrectly on my server (I'm ashamed to admit I'm pretty new at this). Thanks for any help you might be able to give. -
Accessing .count() and .all() inside the model
Can I access .all() or . count () inside the model in models.py file? I'm working on a poll app and I want on field value dynamically to save the .count() of it's many to many field. -
Choice field not getting updated Django
I am trying to update my choice field on form submission but somehow its not getting updated, It representing a blank value in Django-admin contact_no = request.POST['contact_no'] password = request.POST.get('password') user_type = request.POST.get('user_type') print(user_type) user = User(gender=gender, email=email, username=username, first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, contact_no=contact_no,user_type=user_type) user.set_password(password) user.save() Model Definition USER_TYPE = (('HR', 'recuriter'), ('job seeker', 'job_seeker')) user_type = models.CharField(max_length=255, choices=USER_TYPE) -
How can I have an atomic block of code that doesn't access the database in Django?
I am working on a project that uses Django and Django REST Framework. In one of the views there's a method F() that does the following: Fetches data from the database (read operation) Sends a create (POST) request to a 3rd party API. (although not local, this is a write operation and this is where a race condition might take place) Returns JSON data I'd like F() to be atomic, in other words, if the server receives multiple requests at the same asking for this view, the server should handle one of requests to the fullest, and after that, handle the second request to the fullest. How can this be achieved? I have read that Django provides transactions.atomic() but this guarantees atomicity of database transactions, what I need is atomicity for a whole block of code regardless of whether it accesses the database or not. -
DRF: only for representation purpose. How to combine two serializers
I have class Serializer1(serializers.ModelSerializer): class Meta: model = Model1 fields = ("first_name","last_name") class Serializer2(serializers.ModelSerializer): class Meta: model = Model2 fields = ("phone","email") Now I want to show both the serializers as one only for representation purpose like { first_name: last_name: phone: email: } How can do that -
React.js: Unhandled Rejection (TypeError): Cannot read property 'error' of undefined
hello i'm just gettin the error "Unhandled Rejection (TypeError): Cannot read property 'error' of undefined " and this is my Home.js import React ,{useState, useEffect} from 'react' import {GetProducts} from '../core/helper/coreapicalls' export default function Home() { const [Products , setProducts] = useState([]); const [Error , setError] = useState(false); const LoadAllProducts = ()=>{ GetProducts() .then(data =>{ if(data.error){ setError(data.error); console.log(Error) } setProducts(data); }) } useEffect(()=>{ LoadAllProducts() },[]); return ( <div> <h1>Home Component</h1> <div className="row"> {Products.map((product,i)=>{ return( <div key = {i}> <h1>{product.name}</h1> </div> ) })} </div> </div> ) } and this is the API fetch code import {API} from '../../backend'; export const GetProducts = ()=>{ return fetch(`${API}product`,{method : "GET"}) .then(response =>{ return response.json(); }) .catch(error=>{ console.log(error); }); }; API is just an environment variable setting the api link : localhost:8000/api/ -
Image url from S3 is not working in Django template
My django back-end and website is hosted in heroku. My media files are hosted in Amazon S3. I have no issue with uploading image to S3. But when I try to embed image url from S3 into img tag, then I have problem. It does not show image. <img src="{{ taxi.user_photo.url }}" alt="Photo of user"> here is the url that is returned: https://elasticbeanstalk-us-west-2-865036748267.s3.amazonaws.com/media/user_photo/default_taksist.png?AWSAccessKeyId=AKIA4S2BVIXV43WWVZG4&Signature=En2f5F65B61oaYexN2HIIcWIgME%3D&Expires=1631531071 In this link there are KeyId and Signature, I have no idea why it is like that. And, here is my S3 bucket policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::elasticbeanstalk-us-west-2-865036748267/*" } ] } I checked other answers in stackoverflow, they did not help much. Base point is that I have a url but that is not working somehow. Any help of yours is appreciated, thanks for your time. -
Deploy a private server [closed]
I'll host my Django web app on DigitalOcean droplet it will be a website for small business but the problem here that I need to make the server only accessible from certain devices in the company, even with a domain I don't want the website to be public for everyone. I've also looked for Nginx deny and allow ip addresses but the devices ip's addresses changes and they are not static so this step is not working or maybe I'm doing it wrong... So is there any ideas how to achieve that? Thanks. -
Template not found when i run python manage.py runserver on pydriod 3 app
Ive been trying to create a blog with django using my phone nd so far until yesterday it has been a success. I was creating my home page yesterday and when I run python manage.py runserver it returns a template not found error. What can be the issue. This is my views.py ''' from django.shortcuts import render Create your views here. def home(request): returnrender(request,'newfile.html') ''' This is my urls.py ''' from django.urls import path from . import views urlpatterns = [ path('', views.home, name="homepage"), ] ''' This is my settings.py ''' """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve().parent.parent Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-@o12m78t3=13)@m-o^-ejlp@g!-0gz64fiwx%+raw753+=g2)r' SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
redirect is not working in context processors.py
I am building a Blog App and I am trying to redirect when posts are less than 1. But when i use return redirect('home') then it is keep showing dictionary update sequence element #0 has length 0; 2 is required Then i tried to google it than I found that I can't use redirect simply in context_processsors But then i found THIS post similar to this issue. So i think i should wrap the function into another function But it is still showing the same error. def blogRedirect(request): blog = Blog.objects.filter(isnull=True).order_by('id') counts = Blog.objects.filter(isnull=True).count() if counts >=1 : return redirect('home') return { 'blog':blog } Than i wrapped this function into this :- def redirectFunc(request): def blogRedirect(request): blog = Blog.objects.filter(isnull=True).order_by('id') counts = Blog.objects.filter(isnull=True).count() return { 'blog ':blog } if counts >=1 : return redirect('home') It also showed the same error I have tried many times but it is still showing that error. Any help would be much appreciated. Thank You. -
django Build form with variable number of fields
Im trying to build a form in django that allows me to imput the composition of a sample. This is done at present with a CoiceFild that contains all Elements form the Periodic table and a corosponding input Field for the concentration. The problem is that this solution only allows a fixed number of components. But i dont know in advanced how many components are in any given sample. How could i implement this? -
Render Django multi-steps forms
I want to create a multi-steps (model)form: my objective is to have it split in 4 pages, each with a save/update function and the possibility to entierly skip a page (when i have only optional fields). I created a models.py with 4 classes(and relative urls, views, etc..) and tried to use createview, listview and even formsets for grouped-forms (to keep pk for the entire 4 pages session), but I can't render it. What is the best way to render it? Thanks in advance! PS. I do not wish to use Django-tools-wizard module if possible, having already crispy-forms and other modules, as I don't know for certain it will be compatible with the already working ones. -
Django rest framework queryset passing problem
I am having a problem for some days but never get any solution, I tried different approach but not success. I want to pass multiple queryset in the same view or path. @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) related = Product.objects.filter(category=product.category).exclude(_id=pk).order_by('?')[:4] print(related) serializer = ProductSerializer(product, many=False) return Response(serializer.data) I want to pass related product queryset which is related here in the same view. In the first section I will show product details which is working and in the next section I want to show related but now How can I apply that?? I got some solution which told me to go for serializers and change there. But I don't think so because I tried there but how it is possible. So anyone have any better solution. my related object has the same serializer which is productserializer. but eventually it is related product. #this is my serializer class class ProductSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_user(self, obj): user = obj.user serializer = VendorSerializer(user, many=False) return serializer.data -
ForeignKey Assignment - Django
although this is a stupid question I am going to go ahead and ask. I currently have models for 'clients' and 'emails' within Django. I am wondering if the correct cardinality would be to have a ForeignKey pointing toward an instance an email through the 'clients' model. I.e, I have an 'emails_sent' value that points toward an instance within the 'email' model. -
Send notification to users when a file is shared with them in Django
The goal of the Django web application is to allow a user to share files with other users registered in the application. Users have different roles and responsibilities. The default user can only upload a document and forward/share it with another user on the system. Other users can only see a file/document when it has been shared with them. When a file is shared, the recipient is supposed to receive a notification on the system and also via email. My blocker comes when implementing this logic. The sender can upload files, but I can't figure how to implement how they should send them to a receiver and create a notification for receivers. The assumption is, receiver (s) are known and already registered in the system. Any ideas on how to implement this are most welcome. I have the following models: User: a custom model to accommodate different user roles Files: - holds file details Shared:- should contain details of the file shared, sender, receiver, and any comments sent with the file. Notification: handles notifications for users on files shared with them. -
Conditional fields serializer Django
I have a view like this: class UserDetail(generics.RetrieveDestroyAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = User.object.all() serializer_class = UserSerializer def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return generics.get_object_or_404(User, id=item) serializer like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'city'] and urls like this: path('<uuid:pk>', UserDetail.as_view(), name='user_detail') Can I using just one view and one serializer fetch in one case all data (id, fist_name, last_name and city) and in other case just the city by json? Or maybe I have to create for it especially a new view and serializer like this: class UserCity(generics.RetrieveDestroyAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = User.object.all() serializer_class = UserJustCitySerializer def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return generics.get_object_or_404(User, id=item) and class UserJustCitySerializer(serializers.ModelSerializer): class Meta: model = User fields = ['city'] -
How can i fix Page not found 404 in django?
Hi ive been coding my first website and then try running the product page I get this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products Using the URLconf defined in myshop.urls, Django tried these URL patterns, in this order: admin/ The current path, products, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. how can I solve this? Here is my code... my views page code from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello world') def new(request): return HttpResponse('New Products') productsurls code from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] myshopurls """myshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a … -
query a datetime field with just date in django
I am trying to query datetime field in django like the following: http://127.0.0.1:8000/mr-check/?cname=4&date=2021-09-13+00:09 and views: cname = request.GET['cname'] date = request.GET['date'] # try: items = MaterialRequest.objects.filter(owner=cname).filter(delivery_required_on=d) models: delivery_required_on = models.DateTimeField(default=datetime.now) now obviously I don't have an exact instance with 2021-09-13+00:09 but I have instances for the same date, how do I query a datetime field with just date? -
Why am I getting a page not found 404 error
I am trying to create a change password and change username for my users, but it came out as a page not found 404 error shown below, where do I do wrong, it seems ok to me: urls.py urlpatterns = [ path('forget/', views.forget, name='forget'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('change-password/', views.password_change, name='password_change'), path('reset-password/', views.PasswordReset.as_view(), name='password_reset'), path('reset-password-done/', views.PasswordResetDone.as_view(), name='password_reset_done'), path('reset-password/<uidb64>/<token>/', views.PasswordResetConfirm.as_view(), name='password_reset_confirm'), path('reset-password-complete/', views.PasswordResetComplete.as_view(), name='password_reset_complete'), ] views.py def forget(request): msg = None # Get userid from session userid = request.session.get('userid') print(userid) # Get user object from User database user = get_object_or_404(User, id=userid) if request.method == 'POST': # check for the post request body form = ForgetForm(request.POST, instance=user) if form.is_valid(): user = form.save() print(form.cleaned_data.get('password1')) msg = 'user password updated' return redirect('/login') else: msg = 'form is not valid' else: form = SignUpForm() return render(request, 'forget.html', {'form': form, 'msg': msg}) forms.py class forgetForm(forms.Form): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) password1 = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) password2 = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) Let me know if you guys need any more stuff from me -
django unexpected keyword from form helper
forms.py class EinheitsJobForm(forms.Form): all_Verarbeituns_parameters = generateParameterDropdownList() all_pulver_parameter = generatePowederParameterDropdownList() PulverParameter = forms.ChoiceField(choices= choicefieldArray, label="Zugehörige Pulverparameter") VerarbeitungsParameter = forms.ChoiceField(coices= choicefieldArray, label="Zugehörige Verarbeitungsparameter") Fertigung = forms.ChoiceField(choices=choicefieldArray,label="Fertigungs Methode") Jobdauer = forms.TimeField() Geometrie = forms.FileField() Bauerfolg = forms.ChoiceField(choices=choicefieldArray, label="Bauerfolg") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout("Parameter", "Fertigung", "Jobdauer", "Bauerfolg", "Geometrie", Submit("submit", "submit", css_class="btn-success")) error message File "C:\Users\Klaus\PycharmProjects\Materials\productionviewer\urls.py", line 3, in <module> from . import views File "C:\Users\Klaus\PycharmProjects\Materials\productionviewer\views.py", line 6, in <module> from .forms import MaterialInputForm, ProductionParameterForm, ChemischesZusammensetzungForm, EinheitsJobForm File "C:\Users\Klaus\PycharmProjects\Materials\productionviewer\forms.py", line 116, in <module> class EinheitsJobForm(forms.Form): File "C:\Users\Klaus\PycharmProjects\Materials\productionviewer\forms.py", line 121, in EinheitsJobForm VerarbeitungsParameter = forms.ChoiceField(coices= choicefieldArray, label="Zugehörige Verarbeitungsparameter") File "C:\Users\Klaus\PycharmProjects\Materials\venv\lib\site-packages\django\forms\fields.py", line 783, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'coices' when i try to run the code stated above i allways get this error message, i cant find annything wrong with the formclass, it also works with the same syntax in another form. please help -
Django Model Form not saving to database (No error message)
As per the above (title) my Django form is not saving, however, it does redirect to the correct page, the entry does not show on the admin page. Please see the below code : Views.py: def newSetting(request): form = SettingsForm() if request.method == 'POST': form = SettingsForm(request.POST) if form.is_valid(): form.save() return render(request , 'main/newSetting.html' , {'form':form}) .HTML: {% extends "main/base.html"%} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> <style > .row_container{ line-height: 500%; } </style> {% block content %} <form class="" action="{% url 'settingsHome' %}" method="post"> {% csrf_token %} {{ form.Complex }} <br> <br> <div class="row_container" name='TRB-YTD'> <div class="row mb-.1"> <div class="col" style="left-align"> {{ form.Trial_balance_Year_to_date }} </div> <div class="col-11"> <p> Trial balance YTD</p> </div> </div> </div> <div class="row_container" name="TRB-MONTH"> <div class="row "> <div class="col" style="left-align"> {{ form.Trial_balance_Monthly }} </div> <div class="col-11"> <p> Trial balance Monthly</p> </div> </div> </div> <div class="row_container" name="IS-YTD"> <div class="row "> <div class="col" style="left-align"> {{ form.Income_Statement_Year_to_date }} </div> <div class="col-11"> <p> Income Statement YTD</p> </div> </div> </div> <div class="row_container" name="IS-MONTHLY"> <div class="row "> <div class="col" style="left-align"> {{ form.Income_Statement_Monthly }} </div> <div class="col-11"> <p> Income Statement Monthly</p> </div> </div> </div> <div class="row_container" name="AGE-ANALYSIS"> <div class="row "> <div class="col" style="left-align"> {{ form.Age_Analysis }} </div> <div class="col-11"> <p> Age Analysis</p> </div> </div> </div> … -
How to count true boolean field in queryset with extra field boolean_count with each object but count should be the same for each record in django
Model.objects.filter().values('id', 'username', 'email', 'is_boolean').annotate(boolean_count=Count('is_boolean', filter=Q(is_boolean=True))) and I am getting count 1 in each record, but if I am doing Model.objects.filter().values('is_boolean').annotate(boolean_count=Count('is_boolean', filter=Q(is_boolean=True))) I am getting right count for true and 0 for false but I want right count for all and with all first query. means if out of 3, 2 are is_boolean true then count should be 2,2,2 for all with other fields. I don't know how to achieve it. I am not using aggregate because it is returning only counted value but I also want model's other field too. Thanks. -
Serving multiple domains with Django and Apache maps to one location only
I am attempting to setup Django to serve multiple sites (in the below configuration I am using examples www.domain1.com and www.domain2.com). I have installed Apache2 successfully, configured wsgi.py successfully (or so it seems). I have built my appache configuration file to attempt the following mapping: www.example1.com to serve from /var/www/mysite1 www.example2.com to serve from /var/www/mysite2 DNS A records for both example1.com and example2.com point to the same IP address. The trouble with my setup as it exists is that both domain1.com and domain2.com map to the Django residing at /var/www/mysite1, despite the fact that I have (in theory) set them to map to their respective locations. My apache config files are as follows, and both of the files (mysite1.conf and mysite2.conf) have had symlinks made for them using a2ensite: #/etc/apache2/sites-available/mysite1.conf WSGIDaemonProcess mysite processes=2 threads=25 python-home=/var/www/mysite1/myenv1 python-path=/var/www/mysite1/myenv1/mys ite1 WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite1/myenv1/mysite1/mysite1/wsgi.py <VirtualHost *:80> ServerName domain1.com ServerAlias xx.xx.xx.xx DocumentRoot /var/www/mysite1 ErrorLog ${APACHE_LOG_DIR}/mysite1-error.log CustomLog ${APACHE_LOG_DIR}/mysite1-access.log combined Alias /robots.txt /var/www/mysite1/myenv1/mysite1/static/robots.txt Alias /favicon.ico /var/www/mysite1/myenv1/mysite1/static/favicon.ico Alias /static/ /var/www/mysite1/myenv1/mysite1/static/ <Directory /var/www/mysite1/myenv1/mysite1/mysite1> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite1/myenv1/mysite1/static> Require all granted </Directory> </VirtualHost> #/etc/apache2/sites-available/mysite2.conf WSGIDaemonProcess mysite2 processes=2 threads=25 python-home=/var/www/mysite2/myenv2 python-path=/var/www/mysite2/myenv 2/mysite2 WSGIProcessGroup mysite2 WSGIScriptAlias / /var/www/mysite2/myenv2/mysite2/mysite2/wsgi.py process-group=mysite2 WSGISocketPrefix /var/run/wsgi <VirtualHost *:80> ServerName domain2.com … -
AWS lightsail windows server sll certification install for django application
I am very new to AWS so I use AWS lightsail windows server to host a Django application. now to make my domain secure I need to add ssl certificate but don't know how to add an SSL certificate in AWS lightsail windows 16 server. -
raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
I am trying to host a django website in gcloud... i did some changes in settings.py file this is my code DATABASES = {"default": env.db()} # If the flag as been set, configure to use proxy if os.getenv("USE_CLOUD_SQL_AUTH_PROXY", None): DATABASES["default"]["HOST"] = "127.0.0.1" DATABASES["default"]["PORT"] = 5432 after adding this code into settings.py file i am facing below error File "C:\Users\CHANDU\Downloads\Unisoftone\unisoftone\website\website\settings.py", line 99, in <module> DATABASES = {"default": env.db()} File "C:\Users\CHANDU\AppData\Local\Programs\Python\Python38-32\lib\site- packages\environ\environ.py", line 208, in db_url return self.db_url_config(self.get_value(var, default=default), engine=engine) File "C:\Users\CHANDU\AppData\Local\Programs\Python\Python38-32\lib\site- packages\environ\environ.py", line 281, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable