Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Constraint Issue When Loading .sql file into Postgres DB
I performed a pg_dump on the entirety of my production database, and tried to upload it locally on a newly migrated clean Postgres DB. When I do psal db_name < data.sql, I get errors like this insert or update on table "vehicle_vehicle" violates foreign key constraint "vehicle_vehi_vehicle_make_id_265a8146_fk_vehicle_vehiclemake_id" DETAIL: Key (vehicle_make_id)=(788) is not present in table "vehicle_vehiclemake". When a table with foreign keys is attempted to be loaded, and another table it has foreign key relationships to hasn't been uploaded yet, does Postgres stop what its doing and starts to load that table ? How does loading data tackle this issue, is it one the user to dump the data table by table, and load them one at a time ? -
Django DisallowedHost at /, adding it causes connection to be refused
I'm facing a Django DisallowedHost error, googling the solution lead me to add the domains in question to the ALLOWED_HOSTS list in settings.py. However, doing so causes the connection to flat out refuse to connect, and seemingly force https. DisallowedHost Error log: https://pastebin.com/sEg73qmV django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'www.davixxa.net'. You may need to add 'www.davixxa.net' to ALLOWED_HOSTS. This being the specific error of interest. Any help would be greatly appreciated -
validate and submit Django form (django-crispy-forms) with Ajax
I'm very new at django and web development. I need help submitting Django form (using django-crispy-forms) with Ajax How do I: 1 validate input 2 submit without reloading 3 display errors in case of validation failure Right now i can submit the form and it saves the entries into the database but reloads the entire page in the process. i have included relevant snippets of my code below // forms.py class SubscriptionForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SubscriptionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.template_pack = 'bootstrap3' self.helper.form_tag = True self.helper.form_id = 'sub-form-1' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/inline_field.html' self.helper.layout = Layout( Div(Div(css_class='sub-form-notifications-content'), css_class='sub-form-notifications'), InlineField('name', id='subName'), InlineField('email', id='subEmail'), FormActions(Submit('submit', 'Notify me', css_class='form-control')), ) class Meta: model = Sub fields = "__all__" def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError( _("This email address is already in use. Please supply a different email address.")) return self.cleaned_data['email'] // views.py from django.shortcuts import render, redirect from .forms import SubscriptionForm from .models import Sub def index(request): if request.method == 'POST': sub_form = SubscriptionForm(request.POST) if sub_form.is_valid(): sub_form.save() # return redirect('landing:landing') else: sub_form = SubscriptionForm() return render(request, 'landing/index.html', {'sub-form': sub_form}) // template ... {% crispy sub-form %} ... -
Django Rest Framework - How to route to a function view
I am using Django with Django Rest Framework. Django==2.0.2 djangorestframework==3.7.7 I am trying to route to a function view. My current setup looks like this: - project - project - urls - app - urls - views In project/urls, I reference the app's urls like this: url(r'^app_api/', include('app_api.urls', namespace='app_api')) In app/urls, I route to the views like this: router.register(r'', views.app_api, base_name="app_api") url(r'', include(router.urls)), In app/views I have defined a function called app_api and decorated it with api_view. @api_view(['GET']) def app_api(request): If I run the server and curl http://localhost:8080/app_api/ for example, I get a response with status 200 and a empty JSON. "GET /app_api/ HTTP/1.1" 200 2 {} I do not understand why this is happening. If I use a class based viewset, it works, but not with a function view. What is the correct way of routing to a function view when using Django Rest Framework? Thanks! -
How to expand existing input formats in forms.datetime field?
I'd like to add custom input format for my DateTimeField. Is it possible to add custom input without hardcoding default inputs? class CustomForm(forms.Form): updated = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ']) I want to add the option that is above and this solution don't look good: class CustomForm(forms.Form): updated = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y']) -
Running WhiteNoise locally for Django development
I'm trying to serve static files on a Django project with DEBUG = False. I found the WhiteNoise project and configured it according to the docs, and my project works great when deployed to Amazon Web Services. However, when I try to run the project locally, the static files aren't served. I've tried running python3 manage.py runserver --nostatic and also adding 'whitenoise.runserver_nostatic' in INSTALLED_APPS per the docs here. The static files still aren't being served locally, though. Does anyone know if there are some other settings or configurations I should be changing? -
Unity 2017.3 HTTP POST request always empty when it hits web app (Django)
I'm trying to use Unity 2017.3 to send a basic HTTP POST request from Unity scripting. I want to send an image data, which I can access in my script either as file.png or in a byte[]. I am only posting to a local server running Python/Django, and the server does register the POST request coming in - but no matter what I do the request arrives empty of any content, body, files or raw data at my web app. IEnumerator WriteAndSendPng() { #extra code that gets bytes from a render texture goes here #can verify that drawing.png is a valid image for my purposes System.IO.File.WriteAllBytes("drawing.png", bytes); List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add( new MultipartFormFileSection ("drawing", bytes, "drawing.png", "image/png") ); UnityWebRequest www = UnityWebRequest.Post("http://127.0.0.1:8000/predict/", formData); yield return www.SendWebRequest(); if(www.isNetworkError || www.isHttpError) Debug.Log(www.error); else Debug.Log("Form upload complete!"); } I'm following the docs and there are a bunch of constructors for MultipartFormFileSection, most of which I feel like I've tried. Also tried UploadHandlers, or the old AddBinaryField WWW API - still the request is always empty when it hits my app... I thought it might be a Django issue, but posting to the same app w/ Postman or from other sources, it … -
How to get checkbox values in django application
I am trying to use a check box control in a simple django application. Code Logic seems to be fine, But I am getting an empty fruit list ([None, None]). I don't know why it's not working, Can anybody point out the mistake. Thanks in advance index.html <div class="form-check"> <input class="form-check-input" type="checkbox" value="Apple" id="apple"> <label class="form-check-label" for="apple">Apple</label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="Mango" id="mango"> <label class="form-check-label" for="mango">Mango</label> </div> view.py if request.method == 'POST': fruit = [] fruit.append(request.POST.get('apple')) fruit.append(request.POST.get('mango')) -
django-tagging Error in formatting: AttributeError: 'NoneType' object has no attribute '_base_manager'
Struggling to understand an error with a Django application django-tagging (v 0.4.6) using Django 1.11.9 and Django Grapelli 2.10.1 It has a basic installation and I can use it just find to tag the models within my application. The default install includes two admin objects - Tagged Items and Tags. Tags works just fine however Tagged Items returns this error: AttributeError at /admin/tagging/taggeditem/ 'NoneType' object has no attribute '_base_manager' Here's a screen shot: Just wondering if anyone is familiar with this particular set up and can suggest how to address this problem? -
maximum page size queryset in generic views django rest
How can we achieve page_size=max for generic API view in Django rest framework? ?page_size=max work with drf-extensions but only for Viewsets not with generics ListAPIView. Can someone confirm how can we do this? Thanks in advance for the help. -
Unable to connect to Amazon Aurora with PgAdmin
I created an Amazon Aurora Postgres DB on my AWS account, and am now trying to connect to it using PgAdmin. I enter in the db name, username, password, and host, and port. When I try to connect I get this issue. Unable to connect to server: could not connect to server: Operation timed out Is the server running on host "host_name.us-east-2.rds.amazonaws.com" (IP Address) and accepting TCP/IP connections on port 5432? I'm new to Amazon Aurora, and am not sure what my next step has to be to connect. I read the documentation, but can't find what I'm looking for. I'm also getting the same error when I try to connect to it with my production server that houses my Django application. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname.us-east-2.rds.amazonaws.com', 'PORT': '5432' } } And I'm getting a similar issue django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "hostname.us-east-2.rds.amazonaws.com" (IP Address) and accepting TCP/IP connections on port 5432? -
why we create polls/urls.py module in app directory even we can do the whole thing in project's mysite/urls.py?
Code below in my polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), # name='whatever_name' path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results', views.results, name='result'), path('<int:question_id>/vote', views.vote, name= 'vote'), ] then i delete the file and add everything in mysite/urls.py which is the root urls module, and it was working fine from django.contrib import admin from django.urls import path,include from polls import views urlpatterns = [ path('polls/', views.index, name='index'), path('polls/<int:question_id>/', views.detail, name='detail'), path('polls/<int:question_id>/results/', views.results, name='result'), path('polls/<int:question_id>/vote/', views.vote, name= 'vote'), path('admin/', admin.site.urls), ] -
Add to django project an e-mail account
I would like to know if there is any way to add an e-mail account into a django project with all its functionalities; send, receive, bin... And if so where can I find a tutorial or guide to develop it? -
ManytoMany field django template when models are in different apps
My question is similar to this. I have 2 models linked with m2m field and I want to render the field in template. How can I do this when my 2 models are in different apps: apps/qapp/models class Area(models.Model): name = models.CharField(max_length=100, primary_key=True) def __unicode__(self): return self.name apps/worksheets/models class Place(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, primary_key=True) area = models.ManyToManyField(Area,related_name='area') -
Django crashes when I run makemigrations and migrate
When I want to update my code on server, I obtain this error after python manage.py migrate: ... File "/home/ubuntu/casista-root/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/ubuntu/casista-root/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "properties_property" does not exist LINE 1: SELECT "properties_property"."locality" FROM "properties_pro... I've tried deleting all migrations and recreate it, but when I execute python manage.py makemigrations the error appears another time. I've also tried to drop and create database but it seems that never work to solve the issue. Is the first time it crashes.. am I making something wrong? -
Getting None from form in Django
In one of my django I have a form that creates a new product in the database: views.py class ProductCreateView(LoginRequiredMixin, CreateView): template_name = "products/my-products.html" model = Product form_class = AddNewProductForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return HttpResponseRedirect("/my-products/") forms.py AVAILABLE_YEAR_CHOICES = list(range(1960, 2051)) class AddNewProductForm(forms.ModelForm): class Meta: model = Product fields = ["date", "time", "title", "desrciption"] widgets = {'date': forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)} Using the above, everything works perfectly. I wanted to add the current date and time to the date and time widgets, so I tried the following: forms.py class AddNewProductForm(forms.ModelForm): date = forms.DateField(label='date', initial=datetime.date.today(), widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES)) time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M")) class Meta: model = Product fields = ["title", "desrciption"] When I use this, I get an error that the date field is None. I am not sure why this is really happening. Using just the fields in Meta works, but doing something custom gives None. -
How to use bootstrap checkbox control in django
I am using check box control in a simple django application. When I use the standard check box control, I can get the desired values in views.py. But I fail to get the values when I use bootstrap check box control. Logic seems to be fine, I don't know why it's not working. Can anybody point out the mistake, Thanks in advance. Standard Way <input type="checkbox" name="fruit" value="Apple"> Apple <input type="checkbox" name="fruit" value="Mango"> Mango Bootstrap Way <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="fruit"> <label class="form-check-label" for="fruit">Apple</label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="fruit"> <label class="form-check-label" for="fruit">Mango</label> </div> view.py if request.method == 'POST': fruit = request.POST.getlist('fruit') -
which Database to use for eCommerce
My company is branching out to eCommerce in 2019 and I had a few questions. 1) We currently use Oracle DB 10g for our database needs, but is it possible to use the same oracle database but through the web? 2) If it is not possible, what are some of the most reliable/best DB for eCommerce? I have heard that MongoDB and Django are very popular. I am fairly new to SQL but I have grown to love it and I would love to help my company with parts of the eCommerce platform if possible. Thank you! Edit: If this question is not fit for this website, please let me know which site I could put it on. -
Working with database objects per FK / user in Django
I have a question about handling objects per user with forms. I want to interact only with the objects related to the logged in user. If I submit a form it checks every object in the database and gives a returned 2! error when there are 2 objects with the same product_id. I use the product_id field for the barcode and they are unique per product and some users work with the same product. I try to find a way to isolate the user objects first and then work with the database. Or is there another way to handle this issue? As far as I found out, objects.filter(user=request.user) will not work, because I need the objects.get to match the barcode_input of the form field with a certain database field in order to reduce the quantity. I searched a lot before asking this question, but i'm out of technical keywords to search for. models.py class ProductModel(models.Model): user = models.ForeignKey(User) sku = models.CharField(max_length=100) product_id = models.CharField(max_length=30, unique=False) category = models.ForeignKey(ProductCategories, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) amount_sold = models.IntegerField(default=0) def __str__(self): return self.product_line forms.py class ScanProductForm(forms.Form): barcode_input = forms.CharField(widget=forms.TextInput(attrs={'autofocus': 'autofocus'})) amount_input = forms.IntegerField(initial=1) def clean_barcode_input(self): barcode_input = self.cleaned_data['barcode_input'] qs = ProductModel.objects.filter(product_id=barcode_input) if qs.exists(): return … -
Deploying Django Project with Supervisor and Gunicorn getting FATAL Exited too quickly (process log may have details) error
Im trying to launch my django project using this tutorial. I am currently setting up gunicorn and supervisor. These are the configs... Here is my Gunicorn config: #!/bin/bash NAME="smart_suvey" DIR=/home/smartsurvey/mysite2 USER=smartsurvey GROUP=smartsurvey WORKERS=3 BIND=unix:/home/smartsurvey/run/gunicorn.sock DJANGO_SETTINGS_MODULE=myproject.settings DJANGO_WSGI_MODULE=myproject.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- This is my supervisor config: [program:smartsurvey] command=/home/smartsurvey/gunicorn_start user=smartsurvey autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/smartsurvey/logs/gunicorn.log When Ive saved my supervisor, i run sudo supervisorctl reread followed by sudo supervisorctl update. These throw no errors. I then run sudo supervisorctl status smartsurvey, which gives the error smartsurvey FATAL Exited too quickly (process log may have details) This is my first time putting my project on the internet so help would be appreciated! Thanks -
How to configure domain name in apache2 server?
I have deployed two Django sites using Apache2, that can can be access through these links given bellow http://93.188.167.63/cholera/ http://93.188.167.63:8080/pep_learn/ This is my "000-default.conf" file. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/myproject/DATAPLO/static <Directory /home/myproject/DATAPLO/static> Require all granted </Directory> <Directory /home/myproject/trytable> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/myproject:/home/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/myproject/trytable/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, … -
Django button redirection errors
I am trying to allow the user to click a button and be redirected to a page that allows them to update that post. The button is the "update button". The behaviour I am observing is that I am being redirect to the post with the lowest pk that the user authored, when I would like to infact to redirected to the corresponding post (to that view v it is attached). I introduced a link below for debugging and the link below redirects me to the correct page. {% extends "uv/base.html" %} {% block content %} View List {% if view_c_list %} <ul> {% for v in view_c_list %} <li> Title: <a href = "{% url 'uv:view_C_info' v.pk %}">{{v.title}}</a></br> Author: {{v.author}} </br> Piece: {{v.view_text}} {% if user == v.author %} <form action="{% url 'uv:view_C_delete' v.pk %}" method="POST"> {% csrf_token %} <input type = "submit" id="delete_button" value="delete"></input> </form> <form action="{% url 'uv:view_C_update' v.pk %}" id="update">{% csrf_token %}<input type="submit" id="update_button" value="update_{{v.pk}}" form="update"></input></form> <a href = "{% url 'uv:view_C_update' v.pk %}"> Update </a> {% endif %} </li> {% endfor %} </ul> {% else %} <p>That's all folks.</p> {% endif %} {% endblock %} -
Django+Docker+SSL: How to force CSRF to work with HTTPS on Nginx+Gunicorn+Docker stack?
Problem started when after accessing my host via https I encountered that DRF serializes my image it shows url with http:// prefix. Then I've modified next files: nginx.conf server { server_name core.antu.ge; charset UTF-8; ssl on; listen 443 ssl; ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; access_log /var/log/nginx/core.access.log; error_log /var/log/nginx/core.error.log; location /static/ { autoindex on; root /; } location / { proxy_pass http://web:8000; proxy_pass_header X-CSRFToken; proxy_set_header X-Forwarded-Protocol https; proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } settings.py if not DEBUG: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True As a result, I have https prefix in drf as I want but when I perform any POST request I get that error: P.S I'm not going to disable csrf middleware or write csrf_exempt! -
ImagePath changes on display and doesn't find image
In my Django Application, I am trying to display an image on a page. I am querying for the image url in my views.py. It prints:profile_pics/BRICKS_white_small.png. The image is located in nightplus/media/profile_pics. In my index.html I am trying to display this image. First of all I'm printing the path on the page, which looks promising: <p>Url: {{picture_url}}</p> prints: Url: profile_pics/BRICKS_white_small.png Now using: img src="nightplus/{{ picture_url }}" alt="profile_pic"></img it doesn't display anything other than the alt attribute. The Console says: Not Found: /index/nightplus/profile_pics/BRICKS_white_small.png I imagine the /index/ part is added for some reason. also "media" is cut off. Is there a way to change this? -
Django cmd color output with colorama
colorama allows colored text output in cmd for python. And it's working. import colorama colorama.init() print('[31mThis outputs red text![39m') And we can set color output for django runserver by setting environment var in cmd with set DJANGO_COLORS=light. I added import colorama and colorama.init() in the beginning of manage.py. But it's not working. Is it possible to make Django dev server output colored logs to cmd using colorama?