Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Once again, UnicodeEncodeError (ascii codec can't encode)
I'm running python 3.6 + gunicorn + django 2.0.5 in docker container with some cyrillic project and that's what I see when I try to log cyrillic strings in console with Django. 'ascii' codec can't encode character '\u0410' in position 0: ordinal not in range(128) Also this what happens in shell Python 3.6.5 (default, May 3 2018, 10:08:28) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> :�ириллица The same time, when i'm running python 3.5 outside docker container, everything is ok: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> Кириллица Any ideas how to make python 3.6 inside docker work ok with cyrillic strings? -
Custom endpoint, API REST FRAMEWORK
Estoy intentando hacer un endpoint para la home, que muestre la data de tres models diferentes 'webinars, slide, academy' . Estos models no estan relacionados. Recomendaciones de donde leer o Que se hace en un caso así Serializer: class HomeSerializer(serializers.Serializer): slide = SlideBannersSerializer(read_only=True) academy = AcademySerializer(read_only=True) webinars = WebinarsSerializer(read_only=True) view: class HomeListView(APIView): serializer_class = HomeSerializer permission_classes = (IsAuthenticatedOrReadOnly,) -
Fixing ManagementForm-data
I have some code which looks like this: <table> {% for n in model %} {% for i in formset.forms %} {% if forloop.parentloop.counter == forloop.counter %} <tr> <th>{{ n }}</th> {% for j in i %} <th>{{ j }}</th> {% endfor %} </tr> {% endif %} {% endfor %} {% endfor %} </table> I really want to keep it this way, because this is the presentation I've been asked for. However, I keep getting the "ManagementForm-data missing or tampered with" error, obviously because I'm messing with the formset. Is there a smart way to fix the managementform-data so my POST will go through, or do I have to reformat my template completely? (Yes, I am aware that my code contains an ugly, inefficient hack. Please feel free to suggest an alternative.) -
Unresolved Error in Django Model Testing
from django.test import TestCase from .models import Publisher class PublisherModelTestCase(TestCase): def setUp(self): Publisher.objects.create(name = 'some random test title',website = 'cn@gmail.com') def test_publisher_title(self): obj = Publisher.objects.get(website = 'cn@gmail.com') self.assertEqual(obj.name,'some random test title') def test_str_representation(self): obj = Publisher.objects.get(name='some random test titile') self.assertEqual(obj,obj.__str__()) I have created this testcase for my Model, but despite of working in python shell, its showing error when i run the above code. Please be correcting me where am i doing wrong.. models.py class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=100) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField(blank=True) class Meta: ordering = ["-name"] def __str__(self): return self.name Its saying object which i am creating through setUp function doesnt exist.But in python shell its creating the object with same values. ERROR: test_publisher_title (cbv.tests.PublisherModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\django\blog_env\mysite\cbv\tests.py", line 13, in test_publisher_title obj = Publisher.objects.get(website = 'cn@gmail.com') File "D:\django\blog_env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\django\blog_env\lib\site-packages\django\db\models\query.py", line 403, in get self.model._meta.object_name cbv.models.DoesNotExist: Publisher matching query does not exist. ====================================================================== ERROR: test_str_representation (cbv.tests.PublisherModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\django\blog_env\mysite\cbv\tests.py", line 17, in test_str_representation obj = Publisher.objects.get(name='some random test titile') File "D:\django\blog_env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, … -
Makemigrations gives ValueError: too many values to unpack
I have a working project and I would like to add one new field to one of the models. I have added the new field and ran the makemigrations command and then I got ValueError: too many values to unpack This is the model: class Line(models.Model): name = models.CharField(max_length=250, null=False, blank=False, unique=True) label_name = models.CharField(max_length=250, null=True, blank=True, unique=True) and I wanted to add this field: link = models.CharField(max_length=500,null=True,blank=True, unique=True) Then I ran makemigrations command, and got this exception exception: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pycharm\django_manage.py", line 52, in <module> run_command() File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pycharm\django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "C:\Python27\lib\runpy.py", line 176, in run_module fname, loader, pkg_name) File "C:\Python27\lib\runpy.py", line 82, in _run_module_code mod_name, mod_fname, mod_loader, pkg_name) File "C:\Python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "F:\cellular_resolution_map_of_larval_zebrafish\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\makemigrations.py", line 105, in handle loader.project_state(), File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 338, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Python27\lib\site-packages\django\db\migrations\graph.py", line 280, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) … -
Fix My Form, Please
I've been struggeling with a couple of user profile related problems for just about two months now, and whenever I try to read tutorials, articles and assorted documentation snippets, I seem to dig myself even deeper into this pit of confusion in which I currently reside. I've reached a point where it has become futile to investigate further, I feel, thusly I turn to you in the hopes that someone might shed a bit of light over my conundrums. Firstly, I've made a profile page for the user, and the idea is that said user should be able to edit his profile via a form on the front end. Fairly basic stuff. Attempting to edit or fill in the user profile details in the admin: Great succes. Via the vital front end page, no such luck. It appears that the page spits out a generic form and then just ignores the input upon submission. - How can I hook it up, so that it actually changes the user info, when I submit data via the form? What am I missing here? Secondly, and at least equally importantly, I am absolutely lost in terms of authenticating a new user via email. … -
Is it okay to use multi inheritance in Django?
I just want to know if it will be good to use multi-inheritance in Django for an e-commerce website for long run. I read in some articles that multi inheritance is too slow to be used for a high traffic site. -
Django Calculated Field Does Not Appear in Migrations
I'm using the example from Django's docs and trying to create a calculated field in a Django Model. However, the fields don't show up in the migrations and then of course do not show up in the database. Here's my models.py from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" @property def full_name(self): "Returns the person's full name." return '%s %s' % (self.first_name, self.last_name) And the migrations file: class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('birth_date', models.DateField()), ], ), Am I misinterpreting the property attribute? If so, how would one get a calculated field to appear in the database? -
Prevent Gunicorn 30 seconds timeout using AJAX on Django
I configured my Django app with Gunicorn (in a virtual env) and Lighttpd. When I process a lot of data, a 500 error occurs. It is due to a default Gunicorn timeout set to 30 seconds. I tried to use AJAX thinking of solving this issue but the only (wrong) way I found to solve the issue is to add a --timeout of 300 seconds in my costom systemd service: [Unit] Description=django daemon After=network.target [Service] User=root ExecStart=/root/startDjango.sh [Install] WantedBy=default.target with startDjango.sh: #!/bin/bash /opt/django_apps/venv36/bin/gunicorn --log-file=/opt/django_apps/mydjangoapp/logs/gunicorn.log --bind XXX.XXX.XXX.XXX:YYYY --chdir /opt/django_apps/mydjangoapp mydjangoapp.wsgi --timeout 300 Is there a way to solve this issue without increasing gunicorn timeout? -
Django: generate queryset with duplicates
I need to make a queryset with duplicated items for testing purpose in Django, like: <QuerySet [<MyModel: instance1>, <MyModel: instance1>, <MyModel: instance2>]> What is the simplest way to do it? -
Manager isn't accessible via "model" instances django
I am suffering an error with django and their custom Managers. I have this custom Manager: class CallManager(models.Manager): def get_queryset(self): return super(CallManager, self).get_queryset().filter(is_active=True) class Call(models.Model): ... # Data is_active = models.BooleanField(default=True) # Managers objects = models.Manager() # Default active = CallManager() # Active calls Ok, So now I am trying to retrive data from views.py (call/views.py) # Call list def call_list(request): list = Call.objects.all() # Error here render(request, 'call/call_list.html', {'list': list}) When Call.objects.all() is executed, django shows this message: Manager isn't accessible via Call instances I have no idea about what's happening here. Thanks in advance -
AttributeError: 'module' object has no attribute 'face' even after installed opencv-contrib-python
I got an error while running django server. I installed opencv-python and opencv-contrib-python through pip. Still getting the same error. Any suggestions? -
Beanstalk not running makemigrations
I am trying to deploy my Django server to Amazon through Beanstalk, and so far it's been ok except I've made a few changes to my models and when I deployed the instance on Aws is not updating accordingly. I have followed the guide from amazon and created a file named db-migrate.config with the content container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: myAppName.settings but obviously it doesn't seem to be working. I tried to access my django instance on Aws with eb ssh myAppEnv but when I enter I saw nothing and I couldn't find the code for my django server anywhere, thus i am unable to debug and manually run makemigrations also. Anyone can help me with this? -
make field not fall min value django reflect in sql
Model has: value = models.IntegerField(validators=[MinValueValidator(0)], default=0) this works fine with django admin section, but if you try to reduce value via api, the value can be reduced to negative, so how to i reflect the constrain of min value to mysql database as well? As i dont have database access, so has to do via model only or via django api works as: not actual code, looks like StoreCredits.objects.filter(store_id=store_id).update(value= reduce value here) I dont wanna use PositiveIntegerField as its min limit will be 0, suppose i want min limit to be -100 and if someone tries to update record (reduce value) and the value falls below that it should throw djang.db.DataError or some that i can then handle -
'Status' object is not iterable python Django
my views.py : def responded(request): reply_twt = Reply_twt.objects.all() for tweet in reply_twt: rply_tweet = home_timeline.api.get_status(tweet.tweetid) return render (request, 'analytics/responded.html', {'rply_tweet': rply_tweet}) my html: {% extends 'analytics/header.html' %} {% block body %} {% for tweet in rply_tweet %} {{tweet.text}} {% endfor %} {% endblock %} i need to print multiple tweet.text in for loop and even if i send data to html page it is only data on single tweet. how to resolve this . Thank You in advance -
What is the Google Calendar Id
When I want to create an event, what is the Calendar id I have to give? Google says is the mail but that is common for all calendars I have. In settings it gives me 5 "links" for integrating the calendar: calendar ID which is my mail, "public url to this calendar", "Embed Code", "Public address in ICal format" and "Secret address in ICal format" -
How to predict sales for next month in my django app?
I have sales data since April 2016. The coulumns of my sales table are zone id, zone name, region id, region name, product id, product name, sales, sales date. I want to predict the sales for next month in my django website. -
Customize LogoutView using conditional nextpage
I want to create ca subclass of LogoutView which do different redirections based on where the user is located. I have a variable in context, that tells me where the user is. So if the variable is True I want the user to remain on the same pages, if the values is False to be redirected to Login. Also I want to show the user a message that he has been Logout. -
django and static angular file serve with nginx and gunicorn
accoring this site guide : digital ocean i configed my server but i have a problem when i send request to for example login request to site.com:8000/login. server send no response looks gunicorn not running. but if i change my nginx server listen to 8000 everything will work together correctly.... also problem will fix if i start gunicorn in port 8000 manuly in terminal. by commad: gunicorn --bind 0.0.0.0:8000 academy.wsgi:application how can i fix this ? i dont like start gunicorn in terminal or cange site port to 8000 susyemctl status gunicorn return active status with no error this is my site-enabled config : server { listen 80; server_name mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/vertical/academy; } location / { include proxy_params; #proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/vertical/academy/academy.sock; } } and this is my /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=vertical Group=www-data WorkingDirectory=/home/vertical/academy ExecStart=/home/vertical/academy/uenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/vertical/academy/academy.sock academy.wsgi:application [Install] WantedBy=multi-user.target -
High-quality open-source text-to-speech (TTS) engines written in Laravel/Python
I'm looking for open-source text-to-speech (TTS) engines written in Laravel PHP or Python Django. Ideally with high-quality voices (see quality definition below), but also lower quality alternatives are okay as long as the source is freely available. Does such an open source project exist? PS: The Open source should allow addition/creation of new language. I tried to use Google Cloud Text-to-Speech Api but its functionality(languages included) are inbuilt. In my research, I found Festival and MaryTTS which look too old for me. -
Django pass known exact string as a url parameter
I have two urls in dispatcher pointing the same view path('posts/top/', posts, name='top'), path('posts/new/', posts, name='new'), I want view start as follows: def posts(request, ordering): ... I guess, to pass top and new as a parameter it should be something like: path('posts/<ordering:top>/', posts, name='top'), path('posts/<ordering:new>/', posts, name='new'), But it gives me: django.core.exceptions.ImproperlyConfigured: URL route 'posts/<ordering:top>/' uses invalid converter 'ordering'. So, as a work around I use this, but it looks a little bit dirty: path('posts/top/', posts, name='top', kwargs={'order': 'top'}), path('posts/new/', posts, name='new', kwargs={'order': 'top'}), What is the right way to do it? -
Acquiring CSRF token from Django when index.html is served by nginix
I have a React SPA with a Django backend. Like most SPAs, there is an index.html file that needs to be served. But the problem is that this file is served with nginx, so user does not obtain csrf token required to make api calls. I don't really want to serve index.html, as it would require separating the file from the rest of npm run build output and break the "just put it in /static/ directory" workflow, and also for caching reasons. Is there any other workaround? -
Submit form that uses Intercooler in Django StaticLiveServerTestCase
I am trying to write a selenium test for the submission of a form which uses intercooler.js when it is submitted. The main problem I am having is that when I navigate to the page, the form has class="disabled", which is not expected behaviour, and I can't submit the form. The relevant part from the intercooler docs says: By default, intercooler will apply the disabled class to the element that triggers an intercooler request. This can be used to give a visual hint to the user that they should not click or otherwise trigger the request again, and is Bootstrap-friendly. However, it seems to me that the disabled class is being added to the form element before I actually submit the form, and as I understand it should only be added after a request is in-flight. The form currently looks like this: <form ic-post-to="/dashboard/calculate/2/exports/" ic-select-from-response="#content" ic-target="#content" method="post" ic-src="/dashboard/calculate/2/exports/" ic-verb="POST" ic-trigger-on="default" ic-deps="ignore" class="disabled"> <input type="hidden" name="csrfmiddlewaretoken" value="..."> <input type="submit" name="new" value="New" class="btn btn-primary float-right ml-1" id="submit-id-new"> </form> I have tried adding explicit and implicit waits so that the entire page will load but the problem is still there. Any help with this would be much appreciated. -
update not throwing integrity error (OneToOneField)
Update not giving me integrity error on one-to-one-field key: Model looks like: store = models.ForeignKey(Store, on_delete=models.CASCADE, db_index=True) credit_type = models.OneToOneField(CreditType, on_delete=models.CASCADE) value = models.IntegerField(validators=[MinValueValidator(0)], default=0) and api looks like: curd = 'add' operate = {'add': operator.add, 'delete': operator.sub} try: for index, c_id in enumerate(credit_ids): StoreCredits.objects.filter(store_id=store_id, credit_type_id=c_id)\ .update(value=operate[curd](F('value'), credit_values[index])) except IntegrityError: return {"wrong key entered try again."} return {"success"} Other info: The api function has: @transaction.atomic, and amn't converting POST values to int, though database has int types, It works fine simply adds deletes values, but i want to handle wrong ids. With foreign key it throws integrity error when wrong id is passed, here it throws no error error simply returns 'success' it simply adds values to credit_ids that matches and does nothing with other -
Python Library for Comparing Fingerprints
Is there any library in python that can I easily compare fingerprints? I want to build a student attendance system using fingerprint, my frontend will be ReactJS and Django as backend. Like, you need to save the fingerprints of every student in the database and you will retrieve it for comparing. I already google but there are no specific result for my question.