Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Overcoming 'choices' must be an iterable containing (actual value, human readable name) tuples without Foreign Key?
I'm hoping this has been done before - essentially, and hopefully I explain this correctly, what I'd like is a model with some choices (as below). I want to circumnavigate the 'choices' must be an iterable containing (actual value, human readable name) tuples error when adding a third or fourth value to the choice tuple for a model. Those choices not only effect directly the field for which you're selecting from, but also another few fields. I've seen things where the slug field is auto populated from e.g., a blog post title, but does any method exist for tying multiple fields to a certain choice? class Location(models.Model): SERVICE_CHOICES = ( ('bus_station', 'Bus Station', '#cdcdcd'), ('cafe', 'Café', '#cdcdcd'), ('cinema', 'Cinema', '#cdcdcd'), ('gardens', 'Public Gardens', '#cdcdcd'), ('library', 'Library'), ('public_services', 'Public Services'), ('railway_station', 'Railway Station'), ('restaurant', 'Restaurant'), ('school', 'School'), ('shop', 'Shop'), ('supermarket', 'Supermarket'), ('tourist_attractions', 'Tourist Attractions'), ('transit_station', 'Transit Station'), ('walks', 'Walks'), ('woodland', 'Woodland'), ) locale_descriptor = models.CharField("Locale Descriptor", max_length=50, default='') latitude = models.DecimalField("Latitude", max_digits=10, decimal_places=7) longitude = models.DecimalField("Longitude", max_digits=10, decimal_places=7) title = models.CharField("Title", max_length=60, default='') description = models.TextField("Description") service_type = models.CharField("Service Type", max_length=80,choices=SERVICE_CHOICES, default='public_service') Would anyone know how to auto populate a field dependent on these choices?? -
Django model field verbose name in template array
How would you approach getting a Field verbose name to show up in a template when you are iterating over the fields via a custom array? Suppose you have #models.py class Letter (models.Model): a = models.CharField(max_length=1, verbose_name=u'The Letter and Vowel A') b = models.CharField(verbose_name=u'The Letter and Consonant B') ... y = models.CharField(verbose_name=u'The Letter, Consonant, and sometimes Vowel Y') def vowel_array(self): return [self.a,self.e,self.i,self.o,self.u,self.y,] # [a,e,i,o,u,y] # but there is no context to the field name (model.a, model.e, ...) nothing special in the view: ... return render(request, 'app/view.html', { 'language' : language, 'letters' : letters, }) and in the template {% for letter in letters.vowel_array %} <div>{{letter}}:{{letter.verbose_name}}</div> <!-- for 'a' => A:The Letter and Vowel A --> {% endfor %} The trouble I am having in this answer is that I don't know how to pass the context of the 'field_name' in the iterated function. ie {% get_verbose_field_name letters "which_letter_model_field_name" %} My current implementation seems problematic? def vowel_array(self): return [ [self.a, self._meta.get_field('a').verbose_name.title()], [self.e, self._meta.get_field('e').verbose_name.title()], [self.i, self._meta.get_field('i').verbose_name.title()], [self.o, self._meta.get_field('o').verbose_name.title()], [self.u, self._meta.get_field('u').verbose_name.title()], [self.y, self._meta.get_field('y').verbose_name.title()] ] and {% for letter in letters.vowel_array %} <div>{{letter.1}}</div> <!-- for 'a' => The Letter and Vowel A --> {% endfor %} Notes : using Django 1.11 and Python 2.7 -
Different languages in django WITHOUT using translation
I want a project in english and spanish, but I want to have MY translations inst of using django's. So, is it possible and practical? Where would these copies be located and how do I switch betweem them in my templates? How do I work with my database for translations? Do you think django's translator works well and maybe I'd better use it? -
Django bulk_create pairs of one-to-one objects
I have pair of one-to-one relationships, say: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(models.Model): place = models.OneToOneField(Place, on_delete=models.CASCADE) Suppose I want to (in my view) create several Restaurants at once, but these restaurant don't have associated Places yet. Is it possible to use bulk_create in such a way (i.e. using only O(1) queries)? Unfortunately I am stuck with MySQL, so I can't simply bulk_create the Place and access that ID list. -
Django, UnboundLocalError: local variable 'nombre' referenced before assignment in view.py
im having a problem with a with a post request of a form, this is how the models.py is: class Invitaciones(models.Model): class Meta: verbose_name_plural = "Invitaciones" tipos_cedula = ( ("Venezolano", "Venezolano"), ("Extranjero", "Extranjero"), ) estados = ( ("Disponible", "Disponible"), ("Usado", "Usado"), ) def random_string(): return str(random.randint(10000, 99999)) año = int(datetime.datetime.now().year) nombre = models.CharField(max_length=300, null=False, blank=False) apellido = models.CharField(max_length=300, null=False, blank=False) tipo_cedula = models.CharField(choices=tipos_cedula, max_length=50, null=False, blank=False) cedula = models.PositiveIntegerField(null=False, blank=False) codigo = models.CharField(max_length=99999999, default = random_string, null=False, blank=False, editable=False) usuario = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) estado = models.CharField(max_length=250, choices=estados, default="Disponible", null=False, blank=False) fecha = models.DateField(default=timezone.now, validators=[validators.MaxValueValidator(datetime.date(año, 12, 31),message="No puedes elegir una fecha que este mas alla de este año"), validators.MinValueValidator(datetime.date.today(),message="No puedes elegir una fecha anterior a la de hoy")]) envio = models.DateField(auto_now=True) def __str__(self): return '%s %s %s %s %s' % (self.usuario, self.nombres, self.apellidos, self.cedula, self.codigo,) And this is how the views.py is: from cuentas.models import Invitaciones from cuentas.forms import InvitacionesForm from django.views.generic import TemplateView from django.contrib import messages from django.shortcuts import render, redirect, HttpResponse, render_to_response class InvitacionesView(TemplateView): template_name = 'socios/pases.html' def get(self, request): form = InvitacionesForm() invitaciones = Invitaciones.objects.all() args = {'form': form, 'titulo': 'Pases de Invitación', 'invitaciones': invitaciones} return render(request, self.template_name, args) def post(self, request): form = InvitacionesForm(request.POST) … -
django ORM AND-lookups on ManyToMany
How do I implement AND-lookups on Q() of the same field. I tried: Foo.objects.filter(Q(name='any'), Q(name='some')) and Foo.objects.filter(Q(name='any') & Q(name='some')) However they both deliver empty querysets. I am aware, that this will work: Foo.objects.filter(name='any').filter(name='some') However when creating more complex queries where Q1, Q2, Q3 are Q() objects then Foo.objects.filter(Q1).filter(Q2).filter(Q3) could deliver different results than Foo.objects.filter(Q2).filter(Q3).filter(Q1) due to the order in which the filter is applied.