Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django return HttpResponse when database fail to connect or timeout
My Django App is hosted using Zappa (lambda) and using AWS Aurora Serverless database. Currently the coldstart for the database is quite long such that the django app will return a json {"message": "endpoint request timeout"} and it does not look nice and may give the message that the website is totally down. I don't want to change the database (yet) because it seems like the best option for my use case. Telling the user to try again in about a minute is good enough. I want to have something like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '...', 'USER': '...', 'PASSWORD': os.getenv('db_password'), 'HOST': '...', 'PORT': '3306', }, 'OPTIONS': { 'timeout': 30, 'html_when_error': 'templates/sorry.html', }, } I have looked at this to create a custom middleware but not sure how to try it. -
Render Django-Forms Inside Of Bootstrap Modal
I am new to django and I am trying to get a django form to render inside of a bootstrap modal. Any Help is greatly appreciated. Thank you. Let me know if there is any clarification that its needed, or additional code. Again, I really appreciate any help. forms.py from django import forms from login.models import User class PersonForm(forms.ModelForm): firstName = forms.CharField(max_length=30, help_text="Enter Your First Name$ lastName = forms.CharField(max_length=30, help_text="Enter Your Last Name") emailAddress = forms.CharField(max_length=30, help_text="Enter Email Addres$ password = forms.CharField(max_length=30,min_length=6,) class Meta: model = User fields = ('firstName', 'lastName', 'emailAddress', 'password') views.py from django.template import RequestContext from django.shortcuts import render_to_response from login.forms import PersonForm def add_user(request): form = PersonForm() return render(request, 'base.html', {'form':form}) def registration(request): return render_to_response('base.html', {'form': PersonForm()}) base.html <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Log in </h4> </div> <div class="modal-body"> <form id="person_form" method="post" action="add_user" > {{ form.as_p }} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Log In</button> </div> </div> </div> </div> -
TypeError: t.map is not a function - react-dom.production.min.js:4483
I am having issue deploying a react project to heroku, i checked my heroku logs and i see that heroku is having problem runing npm build, after googling around i found out that i need to degrade my react-scripts from 3.1.2 to 3.0.1 and heroku build it successfully. But Heroku is still display "Application error", so i had to run build myself locally,am getting a blank page and i see on my chrome console that error: TypeError: t.map is not a function - react-dom.production.min.js:4483 -
Django MultipleChoiceField Initial Not Working
I have a MultipleChoiceField in a form and form some reason I can't seem to pass in initial values for editing. What am I doing wrong, this appears correct but it is not actually selecting anything? self.fields['disabilities'] = forms.MultipleChoiceField( required=False, initial=['mobility', 'vision'], choices=[ ['mobility', 'Mobility'], ['vision', 'Vision'], ['hearing', 'Hearing'], ['other', 'Other'] ]) -
Domain name stuck on nginx welcome page, when pointing namesilo domain name to AWS ec2 Instance without using route 53
I am trying to point my own domain name bought from Namesilo to AWS EC2 instance but having a problem that I can visit my Django web app by going to EC2 pubic IP, but if I go to my domain name, it stops in Nginx welcome page. I do not understand what is going on. my Nginx configuration file is: server { listen 80; server_name Public_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/my_first_django_project/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/my_first_django_project/myproject/app.sock; } } The creation of A record in Namesilo: enter image description here The result when I go to my domain name and EC2 public IP: enter image description here Does anyone have any ideas? -
User model with Alluth in djnago?
I have a costume user model in which i added a role field to. If i add an allauth social login with Facebook will the role field be ask asked upon login with Facebook? -
How to pass file contents to serializer?
I'm a new at django. I need to implement two POST options; one from url parameters and the other from file data. eg, curl -X POST localhost:8000/api/test?key=value OR curl -X POST -F "file=@myfile.json" localhost:8000/api/test I tested with below but failed. class TestEntryView(ListCreateAPIView): queryset = TestEntry.objects.all().order_by('-id') parser_classes = (MultiPartParser, FormParser,) serializer_class = TestEntrySerializer def perform_create(self, serializer): if self.request.FILES.get('file'): file_obj = request.FILES['file'] filename = '/api/mytest/.temp/testfile' with open(filename, 'wb+') as temp_file: for chunk in file_obj.chunks(): temp_file.write(chunk) with open(filename, 'r') as temp_file: data = json.load(temp_file) serializer.save(**data) serializer.save() => perform_create() is not getting called due to validating field failed. Is there recommended way for this purpose? -
How to fix fields clashes when using models multi-inheritance in django
Let's say we have a parent abstract model AModel that defines a field foo: class AModel(models.Model): class Meta: abstract = True foo = models.TextField(max_length=500, db_index=True) And we have two abstract model classes BModel and CModel those inherit from AModel: class BModel(AModel): class Meta: abstract = True class CModel(AModel): class Meta: abstract = True And we have a model class DModel that inherits from BModel and CModel: class DModel(BModel, CModel): The problem here is that foo field will clash with itself because it's defined in the two parent model classes. How to solve this problem? Is there a "Django" way to prevent this behavior? -
in __getitem__ raise KeyError(key) from None
I'm currently following a tutorial in which the database password is hidden/activated as a variable in the environment activate file. In the Django local_settings.py, the password is supposed to be retrieved like this: "PASSWORD": os.environ['DATABASE_PW'], However, this gives me the error: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\User\Desktop\blog\project\project\settings.py" , line 325, in <module> exec(open(f, "rb").read()) File "<string>", line 21, in <module> File "C:\Users\User\Envs\blog\lib\os.py", line 678, in __getitem__ raise KeyError(key) from None KeyError: 'DATABASE_PW' In the environment activate file, the password is saved as: export DATABASE_PW = 'dbpass' The server has not been running during setting the password, the error happens when I try to run python manage.py runserver. I have also deactivated and re-activated the environment before trying to run the server. What's missing to make it work? -
Django: Using save method instead of auto_now and auto_now_add. What are the pros and cons
I found in a post that instead of using auto_now for modified_date field and auto_now_add for created_date field its preferred to assign the timezone.now() for modified and created date in the save method of the model. def save(self, *args, **kwargs): if not self.id: self.creation_date = timezone.now() self.modified_date = timezone.now() super().save(*args, **kwargs) What is the benefit of this over the auto_not/add. -
Taking a form response, making an api call then displaying the api call in Django
I'm trying to have a Django form capture data from a user's input, take the input to make an API call to Aylien API and display the raw json result on the same page. I'm able to take the form input and successfully make an API call & get the JSON to print on the console, but am having a hard time displaying the call's result on the page. I keep getting UnboundLocalError: local variable 'api_response' referenced before assignment error. Code below models.py from django.db import models # Create your models here. class News(models.Model): title = models.TextField(max_length=120) form.py from django import forms from .models import News class NewsForm(forms.ModelForm): class Meta: model = News fields = [ 'title'] views.py from django.shortcuts import render from .models import News from .form import NewsForm import requests import aylien_news_api from aylien_news_api.rest import ApiException def news_create_view(request): ## link form to model for gathering search term from user form = NewsForm(request.POST) if form.is_valid(): # create an instance of the aylien api class api_instance = aylien_news_api.DefaultApi() ## build opts for api call from the response from the user opts = { 'title': form.cleaned_data['title'], 'language': ['en'], 'not_language': ['es', 'it'], 'published_at_start': 'NOW-7DAYS', 'published_at_end': 'NOW' } try: # List the stories … -
Django REST framework JSONParser().parse(request) raising error
In Django view, I am trying this- @csrf_exempt def customer_list(request): """ List all customers, or create a new customer. """ if request.method == 'GET': snippets = Customer.objects.all() serializer = CustomerSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CustomerSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) On posting data from postman,I get JSON parse error - Expecting value: line 1 column 1 (char 0) -
The empty path didn't match any of these
Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/ The empty path didn't match any of these. from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("projects/", include("projects.urls")), ] -
Start a Django Channels Worker within the same process
I have to set up a worker which handles some data after a certain event happens. I know I can start the worker with python manage.py runworker my_worker, but what I would need is to start the worker in the same process as the main Django app on a separate thread. Why do I need it in a separate thread and not in a separate process? Because the worker would perform a pretty light-weight job which would not overload the server's resources, and, moreover, the effort of making the set up for a new process in the production is not worth the gain in performance. In other words, I would prefer to keep it in the Django's process if possible. Why not perform the job synchronously? Because it is a separate logic that needs the possibility to be extended, and it is out of the main HTTP request-reply scope. It is a post-processing task which doesn't interfere with the main logic. I need to decouple this task from an infrastructural point-of-view, not only logical (e.g. with plain signals). Is there any possibility provided by Django Channels to run a worker in such a way? Would there be any downsides to … -
Effecient way to fetch related models count in Django ORM
I'm working on Django 1.10 and PostgreSQL9.6 I have two models in my project: Order and Customer. Also I'm using Django's auth.User to store login credentials. Here is a code snipped: from django.contrib.auth.models import User from django.db import models class Order(models.Model): created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='created_orders') # ... other fields ... class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # ... other fields ... Now, I need to show a table of customers and show a number of orders created by each of them. The staight forward code is: for customer in Customer.objects.all(): print(customer.user.created_orders.count()) Now I need to avoid N+1 problem and make Django to fetch all data with constant number of queries. I've tried to write something like: query = Customer.objects.select_related('user').annotate( orders_count=Count('user.created_orders') ) But this gives me an error like Cannot resolve keyword 'user.created_orders' into field. Can you help me with this? -
How to set SECRET_KEY environment variable in the development platform of Saleor
I'm setting up a Saleor in my local machine. I need more instructions how and where to place environment variable for SECRET_KEY. I have installed the additional software needed to run Saleor, and completed steps 1-3 in the installation process. I am new to this platform. Please advise how to go about setting SECRET_KEY environment variable. The guide has no detailed process. Please help, thank you in advance! -
How to create a dropdown menu in django which is to be populated from database
Can anyone please provide me the minimal example for creating a drop down menu in django template whose values are to fetched from a database using orm. -
Is it possible to create an edit form using crispy form?
I've a form named "CarForm". I 've created a "Create Form" to create car record using crispy form. I would like to ask is it possible to display the detail and update the car record using the same form? Here is the code for CarForm: from .models import * from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, HTML, Row, Column from crispy_forms.bootstrap import PrependedAppendedText, PrependedText, FormActions from django.urls import reverse class CarForm(forms.ModelForm): note = forms.CharField(widget=forms.Textarea()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['note'].required = False self.fields['policy_num'].required = False self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_action = reverse('create') self.helper.layout = Layout( Row( Column('reg_num', css_class='form-group col-md-6 mb-0'), Column('make', css_class='form-group col-md-6 mb-0'), Column('year', css_class='form-group col-md-4 mb-0'), Column('color', css_class='form-group col-md-4 mb-0'), Column('cc', css_class='form-group col-md-4 mb-0'), Column('engine_num', css_class='form-group col-md-6 mb-0'), Column('chasis_num', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'note', Row( Column(PrependedAppendedText('price_buy', 'RM','.00'), css_class='form-group col-md-6 mb-0'), Column(PrependedAppendedText('price_sell','RM','.00'), css_class='form-group col-md-6 mb-0'), Column('policy_num', css_class='form-group col-md-12 mb-0'), Column('owner_name', css_class='form-group col-md-4 mb-0'), Column('owner_ic',css_class='form-group col-md-4 mb-0'), Column('owner_phone', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), FormActions( Submit('submit', 'Create'), ) ) class Meta: model = Car exclude = ['date'] -
How to clear input formatting in ckeditor django?
Need to format all input data to the ckeditor rich field. Tried to do next in my config.js config.pasteAsPlainText = true; and config.forcePasteAsPlainText = true; but all my input text doesn't clear its formatting. I need to clear all styles, colors, etc. How I can implement this ? -
Hosting a Kerberos-enabled Python/Django Web Application on Windows Server
.. I am moving to Python/Django from .NET for my upcoming project. The application must be Kerberos enabled for SSO login and the credentials need to be further delegated to another server where my Oracle DB resides. I would like to find out the best way to setup my Kerberos in a Django app hosted on Apache2.4 on my Windows Server 2012. So far i have managed to deployed a bare Django app on an Apache web server on my Windows Server VM. I need to get the client web browser to negotiate with the Apache web server and achieve the handshake. I have also tried to look into mod_auth_kerb, however it seems that it is mainly compatible with Linux. Would appreciate if any experts can provide their expertise especially in the area of Kerberos auth with Django/Apache on Windows Server. Thanks a lot. -
Making stored function based confirmation / callback system work with multiple processes in django + nginx
Our callback system worked such that during a request where you needed more user input you would run the following: def view(req): # do checks, maybe get a variable. bar = req.bar() def doit(): foo = req.user do_the_things(foo, bar) req.confirm(doit, "Are you sure you want to do it") From this, the server would store the function object in a dictionary, with a UID as a key that would be send to the client, where a confirmation dialog would be shown. When OK is pressed another request is sent to another view which looks up the stored function object and runs it. This works in a single process deployment. However with nginx, if there's a process pool greater than 1, a different process gets the confirmation request, and thus doesn't have the stored function, and can no run. We've looked into ways to force nginx to use a certain process for certain requests, but haven't found a solution. We've also looked into multiprocessing libraries and celery, however there doesn't seem to be a way to send a predefined function into another process. Can anyone suggest a method that will allow us to store a function to run later when the request … -
How to add CSRF token to Angular 8 post request from Django 2.2
I have an application with Django backend and angular frontend. Now, these are connected with each other, I can get data from Django and show in Angular. As well Send a post request to Django. But the issue is with CSRF token in Django. I disable the CSRF middleware in Django and the request process completely, but I know this is insecure. Method to do a post request. loadQuestion(id): Observable<any> { const body = {'choice': 'teseted with post method'}; return this.http.post(this.baseUrl + id + '/vote', {headers: this.header, withCredentials: true, }); } I did some changes according to this link. HttpClientXsrfModule.withConfig({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' }) but I get this error. app.module.ts:26 Uncaught TypeError: _angular_common_http__WEBPACK_IMPORTED_MODULE_3__.HttpClientXsrfModule.withConfig is not a function So I changed it based on this Link HttpClientXsrfModule.withOptions({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' }) This is my Django function to return data, as I said when I disabled CSRF middleware is working fine So I should fix the CSRF issue and passing it with Angular request. def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=4) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return HttpResponse("You didn't select a choice.") else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect … -
Static files on password_reset_confirm in django project page do not load
I am trying to load static files in a django project. I make a system of registration, login and password change. In the case when I go to the pages of my project, static files are loaded. However, if I reset my password and later go to the password change page (http://127.0.0.1:8000/password_reset_confirm/MQ-set-password/) django does not load static files. I am using django 2.2.6, python 3.7.3. Project structure -project -core models.py forms.py views.py ... -settings settings.py urls.py ... -static ... -templates ... manage.py ... urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth.views import PasswordResetView, PasswordResetCompleteView, PasswordResetConfirmView from django.conf.urls import url from core import views urlpatterns = [ path('', views.home, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.LoginView.as_view(), name="login"), path('password_change_form/', views.LoginView.as_view(), name='password_change_form'), path('password_change_confirm/', views.LoginView.as_view(), name='password_change_confirm'), path('password_reset/', PasswordResetView.as_view(), name='password_reset'), url(r'password_reset_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_done/', PasswordResetCompleteView.as_view(), name='password_reset_done'), path('secret/', views.secret_page, name='secret'), path('admin/', admin.site.urls) ] password_reset_confirm {% extends 'base.html' %} {% block content %} <h2>Set new password</h2> {% if validlink %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% else %} <p style="color:red;">Invalid token.</p> <p> <a href="{% url 'password_reset' %}">Request a new password reset token</a> </p> {% endif %} {% endblock %} -
How to get image url or download url of images in pages API where image is created by a streamfield?
In my wagtail application I have a streamfield that is used to upload an image using ImageChooserBlock along with a title and text. That means in the single streamfield I have a title, a text and an image upload inputs. I'm trying to get the image url in the rest framework's pages API (localhost:8000/api/v2/pages/[page-id]). But this pages api only gives the image id of the uploaded images as follows { "type": "avengers", "value": { "title": "Tony Stark", "avengers": [ { "image": 1, /******* this is the image id returned ********/ "title": "Iron Man", "text": "Iron man is now in framework" } ] }, "id": "2f27cb24" } If I access the images api(http://localhost:8000/api/v2/images/1/) I'm getting the download_url as follows { "id": 1, "meta": { "type": "wagtailimages.Image", "detail_url": "http://localhost/api/v2/images/1/", "tags": [], "download_url": "/media/original_images/avenger.jpeg" }, "title": "avenger.jpeg", "width": 400, "height": 400 } My question is how I can get the download_url or the image url in the pages API (localhost:8000/api/v2/pages/[page-id]) My streamfields blocks.py for the avengers block is as follows class AvengersBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text="Add your title") Avengers = blocks.ListBlock( blocks.StructBlock( [ ("image", ImageChooserBlock(required=True)), ("title", blocks.CharBlock(required=True, max_length=40)), ("text", blocks.TextBlock(required=True, max_length=200)) ] ) ) class Meta: # noqa template = "streams/Avengers_block.html" icon = … -
How to limit the number of items in a ListBlock?
I want to limit the number of entries a ListBlock can have. I know this is possible in StreamField with max_num but I can't see a way to do the same for ListBlocks. We need to use ListBlocks as they are more user friendly for our users than StreamField. An example of the code: class TextQuestionBlock(blocks.StructBlock): question_text = ShortcodeRichTextBlock() correct_answer = blocks.CharBlock(label="Correct Answer", required=True) false_answer = blocks.ListBlock(blocks.CharBlock(label="False Answer(s)", required=True)) We want to limit the number of false answers a user can inout I want to limit the user tro 3 false answers. Currently they can add as many as they like.