Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0 not reading POST request correctly (from Unity)
I'm receiving POST requests in a Django app using Python 3.5 (not from a web form, but from a Unity app). My goal is to send image data. I can confirm that Unity is generating the image correctly, and according to their docs I am sending it over correctly. The POST request hits my local server, but Django request.POST and request.FILES are always empty no matter how I structure the request from Unity. However, if I read request.body into a .txt file, I can see what look like perfectly normal requests: --pGBzDSypIQO4aFVbs4sjTmbBN5OpW3Huawm0D0ib Content-Disposition: file; name="drawing"; filename="drawing.png" Content-Type: multipart/form-data ‰PNG IHDR ð ð :R¼ IDATxìØÁ 0±¶ûïœÐ1” // etc... Also tried other headers or sending dummy POST data. Even the simplest form-data fails to populate request.POST: --hwlDqmtVKZ2EPkOJ7GuauDZNlYdE4nf4yNbGt9WR Content-Disposition: form-data Content-Type: text/plain; encoding=utf-8 a=b Does this look improperly formatted to anyone else? No matter how I send stuff as far as I can tell, Django's request.POST does not populate. Any suggestions? Something look out of place in those requests? Know how a Django request needs to look in order to be readable? Would love to know, thanks! -
Image paths in ReactJS not handled by Django
I have recently integrated react with our django application. I have set up the webpack configurations as shown below. I created a Django base template for our React templates to be rendered in. However, I do have an issue with images not showing up or not found by django. (the images urls are set in ReactJS scripts). The webpack setup: webpack.config.js var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') var ip = 'localhost' var baseConfig = require('./webpack.base.config.js') baseConfig.devtool = "#eval-source-map" baseConfig.entry = { App1: [ 'webpack-dev-server/client?http://' + ip + ':3000', 'webpack/hot/only-dev-server', './chalktalk-react/App1', './assets/scss/main.scss', './assets/scss/fonts-icon.scss', './assets/scss/fonts-site.scss' ], }; baseConfig.output.publicPath = 'http://' + ip + ':3000' + '/assets/bundles/'; baseConfig.plugins = baseConfig.plugins.concat([ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new BundleTracker({filename: './webpack-stats-local.json'}), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('developement'), ENDPOINT: JSON.stringify('https://private-44a4c-chalktalkupdate.apiary-mock.com') } }), ]); baseConfig.module.loaders.push( { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader'] } ); baseConfig.resolve.extensions.push('.js') module.exports = baseConfig; webpack.base.config.js var webpack = require('webpack'); var path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const extractSass = new ExtractTextPlugin({ filename: 'style.css', disable: process.env.NODE_ENV === 'development' }); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { context: __dirname, entry: { // Add as many entry points as you have container-react-components here App1: './chalktalk-react/App1', vendors: ['react'] … -
App can't connect to Postgres anymore
I have a Django application that uses Postgres in production, and I'm not sure what happened along the way of me making changes, but the app is crashing because it appears as though it can't connect to the Postgres database. I'm getting this error in the logs Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.4/dist-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: failed to create a backend connection DETAIL: executing failover on backend It was literally working at 3 this morning, super fast speeds, and than when I wake up this morning it decides it doesn't want to connect anymore. Here is my settings configuration file that I use in production. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'socialauto', 'USER': 'socialauto', 'PASSWORD': 'sa48921', 'HOST': '66.175.220.49', 'PORT': '5433', # PGPool } } It's been working for almost a year now, and the only thing I did with it was perform a pg_dump yesterday. At a loss what it could be -.- -
Django & algolia - conditional statements using
I'm hoping this isn't too obscure a question - I'm integrating the Algolia search platform into one of my projects to be able to search seamlessly and effortlessly yadda yadda. Essentially, I'm looking for a mixture of layouts for premium and low position of a business directory within the #hit-template element for Algolia ... Using {% if %} inside verbatim doesn't quite work...so there's clearly something I'm not understand/missing. Could it be purely in the javascript that I need to edit certain things? Not sure! What is {% verbatim %} ?? Not sure?! Can I have a mixture of javascript and html inside a script of type="text/template" ? {% verbatim %} <script id="hit-template" type="text/template"> {% if _highlightResult.is_premium %} <div class="card text-center mb-3"> <div class="crop-height bg-image-card card-header" style="background-image: url('{{ MEDIA_URL }}{{ get_image_url }}'); height: 160px !important;"></div> <div class="card-header" style="color: #fff !important; background-color: {{ brand_colour }} !important; font-size: 1.3rem;"> {{{ _highlightResult.name.value }}} </div> <div class="card-body"> <p class="card-text" style="color: {{ business.brand_colour }} !important;"><a href="https://www.google.co.uk/maps/search/{{ google_maps_location }}" style="color: {{ brand_colour }};"><i class="fas fa-map-marker fa-2x" data-fa-transform="down-6"></i></a></p> <p class="card-text"><small>{{ get_full_address }}</small></p> <p class="card-text p-2">{{ description }}</p> <a href="{{ absolute_url }}" class="btn btn-primary" style="background-color: {{ brand_colour }} !important; border-color: {{ brand_colour }} !important; color: #fff;">Visit Website</a> </div> … -
Error: could not determine PostgreSQL version from '10.1'
my postgres version is 9.6 and psycopg 2 version is 2.7.2 after running command - git push heroku master i am getting this Error: could not determine PostgreSQL version from '10.1' -
How to write a path for categories in Django
I have a little problem. I want to create detail path like /category/subcategory/post/id. Of course I want to use slugs. The template looks like this: For the categories I've create a view and url, but I can't do it for subcategories. Maybe someone can help me and know the solution? My views.py from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): kategorie = Kategoria.objects.filter(parent=None).order_by('name') firmy = Firma.objects.filter().order_by('publish')[:5] context = {'kategorie': kategorie, 'firmy': firmy} return render(request, 'ogloszenia/index.html', context=context) def detale_firmy(request, slug, id): numer_id = get_object_or_404(Firma, id=id) detale_firmy = get_object_or_404(Firma, slug=slug) return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy, 'id': id}) def kategoria_lista(request, slug): #this is code for creating category slug kat_lista = get_object_or_404(Kategoria, slug=slug) return render(request, 'ogloszenia/lista_kategorii.html', {'kat_lista': kat_lista}) My urls.py is: from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<slug>/<id>/', views.detale_firmy, name='detale_firmy'), path('<slug>/', views.kategoria_lista, name='kategoria_lista'), ] in index.html I have: {% for kategoria in kategorie %} <li> <b><a href="{% url 'kategoria_lista' slug=kategoria.slug %}">{{kategoria.name}}</a></b> {% if kategoria.children.count > 0 %} <ul> {% for sub in kategoria.children.all %} <li>{{ sub.name }}</li> {% endfor %} </ul> {% endif %} </li> {% endfor %} And how to include the code to have for example /administracja-i-polityka/administracja-rzadowa/post_name/id ?? My models.py is: … -
Django 1.8 migration strange behaviour
I am trying to modify an existing School app which has sub-apps like students, class, scores etc using django 1.8. My class model: class Class(Object): student = models.ForeignKey(School, related_name='school_student') section = models.CharField() roll = models.IntegerField() When I run python manage.py makemigrations class, I am getting a message No changes detected in app 'class'. But when I run python manage.py makemigrations, the changes are detected and the migration files are created under the school directory but not in the class directory. But when to the above model if I add a meta class. class Meta: unique_together = ('student', 'roll') And now if I run python manage.py makemigrations class, the changes are detected and the migration files are created under the class directory. Can someone tell me why such behaviour? -
Django tree query spanning multi model relation
Please consider code the following code. I'd like to create something like a tree structure (it will be in a table) related to a specific loged-in user. I'd like to have an overviewpage in which all categories are shown for which this user has items in the subcategories. My query works, but gives me all subcategory records and all posible items in those subcategories (so not just the subset for which the user has records. I have another way working by starting with the itemmodel and then going up in the tree, but thats not what i'm looking for (this makes creating a dynamic set of tables far to depended on the django template layer). I've looked at select_related and prefetch, but I can't get close to a solution. Any help would be appriciated. models.py: from django.db import models from model_utils.models import TimeStampedModel from django.conf import settings User = settings.AUTH_USER_MODEL class MainCat(TimeStampedModel): name = models.CharField(max_length=100, unique=True) rank = models.IntegerField(default=10) icon_class = models.CharField(max_length=100, null=True, blank=True) class SubCat(TimeStampedModel): name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField(null=True, blank=True) icon_class = models.CharField(max_length=100, null=True, blank=True) main_cat = models.ForeignKey(MainCat) class Item(TimeStampedModel): user = models.ForeignKey(User, blank=True, null=True) item_name = models.CharField(max_length=100, null=False, blank=False) sub_cat = models.ForeignKey(SubCat, blank=True, null=True) … -
How can I add Python for machine learning recommendations on my website?
I have been recently learning HTML, CSS, PHP, and Ajax for web development to, finally, build a concrete and consistent web application. As I already have a great experience with the MySQL database, I have just taken a Lynda course on Python and machine learning (using Pandas and Numpy). Could you, please, help me by telling how can I add Python (if there is a possibility) to my HTML, PHP, and Mysql development? I am fairly new to it and still adapting. I have been creating machine learning algorithms in Python at PyCharm, but I just work with .csv files, or transfer them to plain html files. I would like to add these algorithms to a usable website so that I can actually start recommending products to clients. I heard about Django, researched online about it a little bit, but I believe it will not assist me in these purposes. Also, are these development tools I am using (PHP, MySQL, and Python) still on use today? I, by using and deepening my knowledge about them, can improve both my capabilities as a programmer, and become a potentially employable student? -
How can I do POST request in django?
with exception of requests, are there other ways for doing a POST HttpRequest? Ican only use django libs, so I cannot import requests. In particular, I would like to pass the username and the password in the post request. something like: data = { "username": "user", "password": "pass", } r = request.POST( data ) Anyone knows?" -
Heroku - When I run 'heroku run python manage.py migrate' I get an error
When I try to migrate my project to heroku by running the above error, I get the following: C:\Users\{MyUser}\Desktop\My Site\mysite>heroku run python manage.py migrate Running python manage.py migrate on ? {project name}... ! ! Cannot run one-off process at this time. Please try again later. C:\Users\{MyUser}\Desktop\My Site\mysite>heroku run python manage.py makemigrations Running python manage.py makemigrations on ? {project name}... ! ! Cannot run one-off process at this time. Please try again later. I have tried 'makemigrations' as well. Is this an error? On my end or Heroku's? -
django user models create_date no such column
this's my model models.py class MyUserManager(BaseUserManager): def create_user(self, email, nickname, password=None, create_date = None) if not email: raise ValueError('Users must have an email address') user = self.model( email=MyUserManager.normalize_email(email), nickname=nickname, create_date = create_date, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, nickname, password, create_date): u = self.create_user(email=email, nickname=nickname, password=password, create_date = create_date, ) u.is_admin = True u.save(using=self._db) return u class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email', max_length=255, unique=True, ) nickname = models.CharField( u'닉네임', max_length=10, blank=False, unique=True, default='' ) create_date = models.DateTimeField( u'가입날짜', max_length = 10, blank = False, default=timezone.now ) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['nickname', 'gender', 'birthday', 'create_date'] As for my problem, the create_date is in the migrate and the error : no search column is set. fix code def create_date(self): return self.create_date After fixed migrations column delete create_date 1) How should I fix? 2) why this error? 3) i'll want to used create_date = models.DateTimeField(auto_now_add = True) -
Django youtube video id models
I'm new to Django and what I'm doing might be totally stupid but here's what it is. I'm trying to display youtube videos in my template by loading their youtube id from the database but no videos are displayed. Any ideas? models.py: from django.db import models class Video(models.Model): video_id = models.CharField(max_length = 30) def __str__(self): return self.video_id views.py from django.shortcuts import render from Videos.models import Video def videos(request): full_list = Video.objects.all() return render(request, context=full_list) template <h1>YouTube list</h1> {% if full_list %} <ul> {% for video in full_list %} <li> <iframe width="560" height="345" src="http://www.youtube.com/embed/{{ video.video_id }}?rel=0" frameborder="0" allowfullscreen></iframe> </li> {% endfor %} </ul> {% else %} <p>No videos available</p> {% endif %} -
html form action condition in python
<form action="{%url if page_related_data.task is view 'insert_register_form_values_in_database' or 'registered_user_data_edited' registered_user_edit_or_delete_all_information.id%}" method="post"> I actually want to use 2 methods insert_register_form_values_in_database; registered_user_data_edited (with argument registered_user_edit_or_delete_all_information.id) but if i want to use them in one html page in one form tag how can i use it. -
How to know which field is saved when only() has been used in Django?
I am using Django 1.11, in one of my models I have added actions when the model is saved. However I don't want these actions to be done when only a part of the model is saved. I know that update_fields=('some_field',) can be used to specify which field must be saved. But, when the object has been fetched in the database using the methods only() or defer() I don't see any information about the fields updated in the save() method, update_fields is empty. Thus my question: How can I get the fields saved by Django when only some fields have been fetched ? -
How does .send() find connected receivers? Django
I have been learning about signals, and am now trying to understand the basic, inner mechanics of how a signal is sent - and received. This post concerns the provided signal-objects(pre_save, post_save...etc), not writing custom ones. Looking within the Django code for the model class, .send() is called on the imported signal 'pre_save'. When reading about .send() within the Signal class (found in dispatcher.py), there is a comment that says: ''Send signal from sender to all connected receivers.'' How exactly does .send() go about finding connected receivers? I have read that .connect() ensures that signals are connected to receivers, through 'signal dispatchers', which are instances of the Signal class. Could a basic explanation be that the connect-method, found in the Signal class, takes the receiver name that is given to it as a parameter - and appends it to the specified list 'self.receivers'? And that that list is later checked to for possible receivers within the .send() method? Because that is the way it appears to me from reading the code. It also seems, if my beginners-eyes have been able to read everything correctly, that an empty list is returned by the .send() method if no receivers are found. Is … -
How to make asynchronous ajax requests if the server side work takes plenty of time to finish?
I need advice or sample code to achieve a task related asynchronous ajax request that server side work takes plenty of time to finish its job. Here is the sample scenario; I've a simple CSV file upload form. User submits file Server starts processing CSV file. Server makes queries to external web apis for each line of CSV file. (additional network request/response delays) Server parses each response (regex calculations, additional delays) and stores data into database. Server produces another output CSV file. If the CSV file contains < 100 rows, it works even without using ajax. However I need to make it asynchronous to be able to feed a lot of rows. The critical part is I don't want to have timeouts as long as server side code is working. I want to be able to update client side regularly about the progress of work (log-like update, for example "x record is saved into database") Can you provide me a working dummy sample code (for example, calculating fibonacci numbers) both client side and server side. (if possible django) Thanks. Kind Regards. -
create table with dynamic rows and columns with django html template
I'm trying to create a table with dynamic rows and columns based on the results list with django html template. The number of records and header number could change. I am using two for loops to get the number of rows and the column number. I'm having a hard time trying to output the actual values in the table. The idea was to "index" from the second for loop and applying it to "each" of first loop. I know that the syntax is definitely wrong, but is something that django can do? If not, is there any suggestions that I can research on how to implement this? Thanks!! list = [ {'header_a': foo1, 'header_b': foo2, 'header_c': foo3}, {'header_a': foo1, 'header_b': foo2, 'header_c': foo3}, {'header_a': foo3, 'header_b': foo3, 'header_c': foo3}, {'header_a': foo4, 'header_b': foo4, 'header_c': foo4}, ] Sample Table header_a | header_b | header_c foo1 | foo1 | foo1 foo2 | foo2 | foo2 foo3 | foo3 | foo3 foo4 | foo4 | foo4 or list_2 = [ {'header_c': c_foo1, 'header_d': d_foo1}, {'header_c': c_foo2, 'header_d': d_foo2}, ] Sample Table 2 header_c | header_d c_foo1 | d_foo1 c_foo2 | d_foo2 <table> <thead> <tr> {% for index in list.0 %} <th>{{ index }}</th> … -
outer array of images in Django serializer
Im trying to call image url by book, this is my model: class Book(models.Model): users = models.ManyToManyField(User) creation_date = models.DateTimeField(default = timezone.now) published_date = models.DateTimeField(default = timezone.now) isbn = models.CharField(max_length = 200) class PhotoBook(models.Model): book = models.ForeignKey(Book, on_delete= models.CASCADE, related_name="photos") image = models.ImageField(upload_to = "cover_page", blank = True, null = True) This is my serializer.py class BookSerializer(serializers.HyperlinkedModelSerializer): users = UserSerializer(many = True, read_only = True) photos = serializers.StringRelatedField(many=True) published_date = serializers.DateTimeField(format="%Y-%m-%d", input_formats=None) class Meta: model = Book fields = ("published_date" , "photos", "users", "isbn", "title_book", "cover_page", "pages" ,"copies", "description", "subtitle") Sure im trying with serializer.StringRelatedField but only get an array of text saying this is an object of Photobooktype. The question is , how can i get the array of images in my serializer, knowing the foreing_key is in the PhotoBook object. -
Fetch images sent to your Telegram Bot using Django
I want to fetch image sent by the user to the telegram-bot. And save this image in the database, just want to see this image in the URL/admin. My models.py from django.db import models # Create your models here. class BotUser(models.Model): chat_id = models.BigIntegerField() step = models.CharField(max_length=50, null=True, blank=True) username = models.CharField(max_length=120, null=True, blank=True) fio = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120, null=True, blank=True) date_wedding = models.DateField(blank=True, null=True) photo = models.ImageField(null=True, blank=True) date_in = models.DateTimeField(auto_now_add=True, auto_now=False, null=True, blank=True) def __str__(self): return 'user_id = ' + str(self.id) + ' chat_id = ' + str(self.chat_id) + ' ' + self.fio + ' ' + self.username class Meta: verbose_name = 'Telegram User' verbose_name_plural = 'Telegram User' And my views.py import telebot and then mes = 'Hello!' bot.send_message(chat_id, mes) mes = 'What is your name?' bot.send_message(chat_id, mes) user.step = 'input_name' user.save() return HttpResponse('OK') if user.step == 'input_name': user.name = text mes = 'What is your city?' bot.send_message(chat_id, mes) user.step = 'input_city' user.save() return HttpResponse('OK') if user.step == 'input_city': user.city = text mes = 'What is your birthday YYYY-MM-DD.' bot.send_message(chat_id, mes) user.step = 'input_date' user.save() return HttpResponse('OK') if user.step == 'input_date': user.date_wedding = text mes = 'What is your photo?' bot.send_message(chat_id, mes) user.step = 'input_photo' … -
What is the best way to get URl of generated file within Celery task
I got a task to make exports of several big tables in DB asynchronous because right now the amount of records is so big that it takes too much time. So I've successfully moved the code of exporting to the Celery task. It exports and saves the file in a folder on a server. But I am not able to get from the task the whole filename, which I could pass to the rest of code and therefore download it after completing the export process because the only thing Celery task can return is only the state of the result of performing the task (done or not yet or failed). I am using Django/Python + Celery + Redis. Thank you for any advice, it already borders me for several days. -
Running management command that take very long in django
I want to call management command from view in Django. The problem is that execution takes very long and nginx gives me 504 or 502 if I increase timeout. Is there a solution for that? -
Django full text search using indexes with PostgreSQL
After solving the problem I asked about in this question, I am trying to optimize performance of the FTS using indexes. I issued on my db the command: CREATE INDEX my_table_idx ON my_table USING gin(to_tsvector('italian', field1), to_tsvector('italian', field2), to_tsvector('italian', field3), to_tsvector('italian', field4), to_tsvector('italian', field5)); Then I edited my model's Meta class as follows: class Meta: managed = False db_table = 'my_table' indexes = [ GinIndex( fields=['field1', 'field2', 'field3', 'field4', 'field5'], name='my_table_idx' ) ] But nothing seems to have changed. The lookup takes exactly the same amount of time as before (again, this is the lookup script). What am I doing wrong? -
Django - override base class model field
I am using Django1.6 i have: class A(Model): att = CharField() class B(A): pass i want to override the behaviour of 'att' (without touching class A): something like: class B(A): @propert def att(self): return self._att + 'thanks' @att.setter def att(self, value): self._att += value how can i do it? i know this is possible from django 1.10 -
Embedding matplotlib moving chart in django template
I am new to python Django framework. I have matplotlib moving or live chart, It should be embedded in django template. I checked many question relevant to this here but none of them is worked for me. Most of us suggested here is displaying as image, but problem is moving chart with default interface like zoom, drag everything to be integrated. i am struggling to solve . I used this code and got to know it will be displaying as image. def simple(request): import random import django import datetime from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig = Figure() ax = fig.add_subplot(111) x = [] y = [] now = datetime.datetime.now() delta = datetime.timedelta(days=1) for i in range(10): x.append(now) now += delta y.append(random.randint(0, 1000)) ax.plot_date(x, y, '-') ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas = FigureCanvas(fig) response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response I used this code for reference. if this is not understandable please comment below, ill try to convey you clearly can any one help me to get fixed this. Thanks in advance.