Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vue.js "npm run build" but Vue.js not bound to DOM / working
Newbie to Vue.js here. On Mac OS using versions: $ npm --version 4.6.1 $ vue --version 2.8.1 I'm using the webpack-simple init with the vue-cli for vue 2.0. I've created a folder within my Django project folder for vue stuff called frontend. Directory structure: $ tree -L 1 ../ ../ ├── README.md ├── asnew │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── settings.py │ ├── templates │ └── index.html │ ├── urls.py │ ├── views.py │ ├── wsgi.py ├── frontend │ ├── node_modules │ ├── package.json │ ├── src │ ├── App.vue │ ├── assets │ ├── components │ │ └── SearchPageResult.vue │ ├── main.js │ └── webpack.config.js ├── manage.py ├── media ├── requirements.txt ├── static └── staticfiles Then basically in my index.html Django template I have the following code: <script src="{% static 'js/vue/build.js' %}"></script> <div id="app"></div> Once rendered this turns into the full path: <script src="/static/js/vue/build.js"></script> which I create with npm run build and I verified does actually get loaded/imported by the browser. I run the heroku CLI as the devserver. I build like this: $ cd frontend $ npm run build > vue-asnew@1.0.0 build /Users/me/MyProject/frontend > cross-env NODE_ENV=production webpack --progress --hide-modules Hash: d5e16854b8f88beea3e9 Version: webpack … -
How to add highchart in my view.py?
Anyone have idea on how to add high chart in view.py? which mean my data are filter base on the python code and from the dataframe convert to highchart. -
KeyError at /login u'message'
def loginUser(request): if request.method != 'POST': return redirect('/') attempt = User.objects.validateUser(request.POST) if attempt['status'] == True: request.session['user_id'] = attempt['user'].id return redirect('/books') else: messages.add_message(request, messages.ERROR, attempt['message'], extra_tags="login") return redirect('/') KeyError at /login u'message' Request Method: POST Request URL: http://127.0.0.1:8000/login Django Version: 1.11 Exception Type: KeyError Exception Value: u'message' -
Django CRUD update object with many to one relationship to user
I followed along the awesome tutorial How to Implement CRUD Using Ajax and Json by Vitor Freitas. For my project I have an object with a many to one relationship with the user that I want users to be able to add and update. I can add the object, but when I try to update it throws a ValueError: Cannot query "Case object": Must be "User" instance. views.py def case_update(request, pk): case = get_object_or_404(Case, pk=pk) if request.method == 'POST': form = CaseForm(request.POST, instance=case) else: form = CaseForm(instance=case) return save_case_form(request, form, 'cases/includes/partial_case_update.html') It breaks when I try to save the edit, but I am struggling to see a way around this. To edit this case, I need the form to be an instance of this particular case as the user may have many cases. When I set the instance to user, nothing happens, when I remove the instance altogether it obviously just makes a copy of the case so I have two of the same cases. I can post more code if necessary. Thank you -
how to configure django with mysql using pymysql (python 3.5)
having much trouble getting mysql(5.6) to connect with django (1.11) using python 3.5.2 in ubuntu(16.04) venv. im trying to use pymysql because it works great with flask applications, just not django yet. mysqlclient failed install and has other dependencies (ive read django docs yes) so would prefer avoiding that module. this really should work since it works flawless in flask and others seem to have it working. heres what Ive tried and found: # first steps pip install pymysql mysql -u root -p CREATE DATABASE djang0 CHARACTER SET utf8 COLLATE utf8_bin; # manage.py try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djang0', 'USER': 'root', 'PASSWORD': 'mypasswd', 'HOST': '', 'PORT': '3306', } } # current models.py Post class for blog class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() image = models.ImageField(upload_to='uploads', blank=True) # error - full here https://dpaste.de/vtEH [Thu Apr 27 18:58:00.010964 2017] [wsgi:error] [pid 22811:tid 3049028416] [remote 192.168.0.3:52267] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. [Thu Apr 27 18:58:00.010967 2017] [wsgi:error] [pid 22811:tid 3049028416] [remote 192.168.0.3:52267] Did you install mysqlclient or MySQL-python? -
Can't understand relationship of Celery Tasks to Django
I am using Django to listen to voice commands. I was going to use Celery as a way to run a seperate process for listening, and a seperate process for executing commands. When I had set up Django with Celery, I had envisioned starting Django (./manage.py runserver) and having those two processes initiate at startup. But so far I see that the Celery app is started via the shell, and Django speaks to it seperately. A HUGE part of my learning curve here is understanding what relationship Django has to Celery. I had intended to have everything running within the Django environment -- ie, not having Django run beside Celery. Can someone tell me where I've become confused? -
Getting "AttributeError: 'str' object has no attribute 'regex'" in Django urls.reverse
As in the title, I'm getting AttributeError: 'str' object has no attribute 'regex' I've seen many valid answers to this, but none of them applied to my code as they identified issues in the urls.py file. My issue is in the views.py file. I get the exception when using reverse to generate a redirect URL: HttpResponseRedirect(reverse('changetracker:detail', args)) When I use 'changetracker:detail' in other functions, I don't get the exception. -
Django ORM poor performance compared to raw sql
I'm using Django ORM for data query and I get almost 2 million rows in this table.I tried app_count = App.objects.count() and from django.db import connection cursor = connection.cursor() cursor.execute('''SELECT count(*) FROM app''') The mysql slow_query log gave me Time: 2017-04-27T09:18:38.809498Z User@Host: www[www] @ [172.19.0.3] Id: 5 Query_time: 4.107433 Lock_time: 0.004405 Rows_sent: 1 Rows_examined: 0 use app_platform; SET timestamp=1493284718; SELECT count(*) FROM app; This query took avg more than 4 seconds, but when I used mysql client and mysql shell to do this query mysql> select count(*) from app; +----------+ | count(*) | +----------+ | 1870019 | +----------+ 1 row in set (0.41 sec) Just take me 0.4 second, 10X difference, Why and how to improve it. -
Basic URL Django Issue
This basic url issue is giving me a headache. I have two links I wish to take a fictitious user to: localhost/prediction and localhost/prediction/. The first works, the second doesn't with an error saying that the site doesn't exist. Any clue as to why? URl Patterns: urlpatterns = [ # ex: /prediction/ url(r'^', views.post_list), # ex: /prediction/<number>/ url(r'^(?P<number>[0-9]+)/$', views.show_body) ] View: def show_body(request, number): return HttpResponse(number) -
Selenium python ajax query during page load takes very long time to return
Its a simple page load with the following JS code: $(document).ready(function () { set_initial(); ajax_query(); }); It takes like 5 minutes for selenium to get back a response when the ajax query is executed. Any ideas why this would happen? -
error during Django 1.8 test with multiple databases
I'm moving a Django 1.8 project from a single database setup to a writer/reader setup. I ran into the issue described in Django bug 23718 but the work arounds described didn't seem to help. Has anyone run into similar issues? Relevant code segments are below: Router: class DatabaseRouter(object): """Router to handle separation of reads and writes.""" def db_for_read(self, model, **hints): """Reads go to a read replica.""" return 'read' def db_for_write(self, model, **hints): """Writes always go to default.""" return 'default' def allow_relation(self, obj1, obj2, **hints): """Allow relations bet/n objects in the same DB cluster.""" db_list = ('default', 'read') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """All models end up in this pool.""" return True relevant DB settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASS, 'HOST': DB_WRITE }, 'read': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASS, 'HOST': DB_READ, 'TEST': { 'MIRROR': 'default', }, } } DATABASE_ROUTERS = ['my_project.routers.DatabaseRouter'] work around replication test case: class ReplicationTestCase(TestCase): @classmethod def setUpClass(cls): super(ReplicationTestCase, cls).setUpClass() connections['read']._orig_cursor = connections['read'].cursor connections['read'].cursor = connections['default'].cursor @classmethod def tearDownClass(cls): connections['read'].cursor = connections['read']._orig_cursor super(ReplicationTestCase, cls).tearDownClass() Anything pop out? I'm happy to provide stacktraces from … -
djano-filters return only one object after filtering
I`m using django-filters to filter in my app, however it returns me only one result after filtering. There are more objects in db and I can see them when not using filters. Thank you a lot in advance for any help! models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class Bancnote(models.Model): Dollar= 'Dolar' Euro= 'Euro' TYPE_CHOICES = ( (Dollar, 'Dollar'), (Euro, 'Euro') ) type = models.CharField(max_length=11, choices=TYPE_CHOICES, default=HRYVNA) par = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000000) size = models.CharField(max_length=7) sign = models.CharField(max_length=20) desc = models.TextField(max_length=200) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) + ' ' + self.type) filters.py from django import forms import django_filters from .models import Bancnote class BancnoteFilter(django_filters.FilterSet): type = django_filters.ChoiceFilter(choices=Bancnote.TYPE_CHOICES, widget=forms.RadioSelect(attrs={'class': 'radio'}), label='Choise', empty_label=None) class Meta: model = Bancnote fields = ['type'] views.py from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, render_to_response from django.template import RequestContext from django.shortcuts import render from .models import Bancnote from .filters import BancnoteFilter def index(request): bons_list = Bancnote.objects.all().order_by('par') bons_filter = BancnoteFilter(request.GET, queryset=bons_list) return render(request, 'catalogue/index.html', {'filter': bons_filter}) def image(request): bons = Bancnote() variables = RequestContext(request, { 'bons': bons }) return render_to_response('catalogue/bon_detail.html', variables) urls.py from django.conf.urls import url from django.views.generic import DetailView from catalogue import views from catalogue.models import Bancnote urlpatterns = [ … -
looping through list in python changes order
I thought list order python is immutable. When I do the following, the order of the list changes. for v in values_list: v.is_connected = True How can I prevent this? -
Schedule Django Celery periodic tasks to run from time to other time
How can I accomplish to run Django Celery tasks to be running only from Mon to Friday and on those days only from 9am to 5pm EST. celery.py from celery.schedule import crontab app.conf.beat_schedule = { 'compute-every-5-seconds': { 'task': 'sum', 'schedule': crontab(), }, } What parameters should I add to crontab() that it would run those days and between only those hours? -
makemigrations permisseion denied
i guess i'm stuck at a big problem. i had to delete the migrations directory in my django app and i thought when i run python manage.py makemigrations the directory will be created back, however i got an error django.db.migrations.graph.NodeNotFoundError: Migration shoppingcart.0001_initial dependencies reference nonexistent parent node (u'student', u'0001_initial') what i did after is recreate the migrations directory and put inside all the migrations files and run makemigrations but i'm having another error IOError: [Errno 13] Permission denied: u'/edx/app/edxapp/edx-platform/common/djangoapps/student/migrations/0007_auto_20170427_1816.py' -
UnicodeDecodeError updating elasticsearch index with haystack
I've got haystack & elasticsearch setup on a project running; django 1.10 django-haystack 2.6.0 elasticsearch 5.3.0 requests-aws4auth 0.9 Haystack settings; HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'https://search-proj-dev.eu-west-1.es.amazonaws.com/', 'INDEX_NAME': 'myproj_dev', 'TIMEOUT': 60, 'KWARGS': { 'port': 443, 'http_auth': awsauth, 'use_ssl': True, 'verify_certs': True, 'connection_class': elasticsearch.RequestsHttpConnection, } }, } But I'm getting issues with unicode characters when trying to update the search index; Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 214, in handle self.update_backend(label, using) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 257, in update_backend commit=self.commit, max_retries=self.max_retries) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 84, in do_update backend.update(index, current_qs, commit=commit) File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 190, in update bulk(self.conn, prepped_docs, index=self.index_name, doc_type='modelresult') File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 194, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 162, in streaming_bulk for result in _process_bulk_chunk(client, bulk_actions, raise_on_exception, raise_on_error, **kwargs): File "/Users/mwalker/Sites/proj/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 91, in _process_bulk_chunk raise e elasticsearch.exceptions.ConnectionError: ConnectionError('ascii' codec can't decode byte 0xe2 in position 2509: ordinal not in range(128)) caused by: UnicodeDecodeError('ascii' codec can't decode byte 0xe2 in position … -
got an unexpected keyword argument 'user'
I'm trying to understand why my code isn't work fine. This is the models: class Usuario(models.Model): user = models.OneToOneField(User,default=None) nombre = models.CharField(max_length=100) correo = models.CharField(max_length=300) tel = models.CharField(max_length=100) cp = models.CharField(max_length=100) def __unicode__(self): return self.nombre This is the view: def RegistrosUsuarios(request): if request.method == "POST": nombre = request.POST['nombre'] correo = request.POST['correo'] contrasena = request.POST['contrasena'] mailused = None try: mailused = User.objects.get(email=correo) except User.DoesNotExist: print("Usuario no existe") if mailused is None: user = User.objects.create_user(username=correo, email=correo) user.set_password(contrasena) user.save() ultimoUser = User.objects.all().last() usuario = Usuario(user=ultimoUser,nombre=nombre,correo=correo) usuario.save() user = authenticate(username=user.username,password=contrasena) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse("inactive user") else: return HttpResponseRedirect('/') else: return HttpResponseRedirect('/') else: return HttpResponseRedirect('/') The form: <form action="/RegistrosUsuarios/" method="post" enctype="multipart/form-data" autocomplete="off"> {% csrf_token %} <div class="modal-body"> <div class="md-form"> <input maxlength="500" name="nombre" type="text" placeholder="Nombre" required="required" style="width: 25%;"> <label for="nombre" style="color: #000!important;display: none;" class="active"></label> </div> <div class="md-form"> <input type="email" name="correo" id="correo" required="required" placeholder="Correo" style="width: 25%;"> <label for="correo" style="color: #000!important;display: none;" class="active">Email</label> </div> <div class="md-form"> <input type="password" name="contrasena" id="contrasena" required="required" placeholder="Contraseña" style="width: 25%;"> <label for="contrasena" style="color: #000!important;display: none;" class="active">Contraseña</label> </div> <div class="input-field" style="border-top:0px ;align:center;" align="center"> <button type="submit" name="action" class="btn waves-effect waves-light" style="border: 2px solid #000;color: #000!important; width: 15%;background-color:transparent!important;font-family: Geomanist-Regular;letter-spacing: 0px;font-size: 1.1rem; ">REGISTRARSE</button> </div> </div> </form> the url: … -
Django channels would not start redis server using CHANNEL_LAYERS
I am trying to replicate Mikhail Andreev chat with Django channels posted here: https://gearheart.io/blog/creating-a-chat-with-django-channels/ and when I run the server: $ 'python3 ./manage.py runserver' the redis server does not start. Here is the full message: Performing system checks... System check identified no issues (0 silenced). April 27, 2017 - 20:59:01 Django version 1.10.3, using settings 'multichat.settings' Starting Channels development server at http://127.0.0.1:8000/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the server with CONTROL-C. 2017-04-27 20:59:01,278 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-04-27 20:59:01,279 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-04-27 20:59:01,282 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-04-27 20:59:01,282 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-04-27 20:59:01,283 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-04-27 20:59:01,283 - INFO - server - Using busy-loop synchronous mode on channel layer 2017-04-27 20:59:01,284 - INFO - server - Listening on endpoint tcp:port=8000:interface=127.0.0.1 2017-04-27 20:59:01,294 - ERROR - server - Error trying to receive messages: Error 61 connecting to localhost:6379. Connection refused. Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/redis/connection.py", line 439, in connect … -
Django Admin - Two databases but can only see permissions for one
I have two datbases set up in m settings.py. On my admin page I can see and edit both databases. However I can only set permissions for the default database. Is this normal? How can I see permissions for the second database? Note: I am talking about the default permissions on the admin page. I haven't made any custom ones. -
Child object by Parent
Here's the deal, I have three classes: class Interaction(models.Model): user = models.ForeignKey( User, verbose_name="Usuário" ) created = models.DateTimeField( verbose_name="Criado em", auto_now_add=True ) value = models.FloatField( verbose_name="Valor", default=0 ) class PostInteraction(Interaction): #some atributes class NewsInteraction(Interaction): #some atributes And i make the query: interactions = Interaction.objects.all() for interaction in interactions: #??? How can I tell which child class by parent class without doing a query? -
Python/Django - Testing against a list
I'm new to testing in python and testing in general and looking for a way to write one test function and run this function multiple times against different elements of a tuple. More precisely, there is a tuple consisting of different database queries which i all want to test. The results of all those queries share the same pattern so i guess it's reasonable to reuse the code testing those results. As far as i know, it is considered bad practice to pass arguments to a unittest which seems reasonable too. This leaves me a bit clueless. Writing one function for every single query would be hard to maintain, because new queries are added to this tuple constantly. I also would like to obtain detailed results (FAIL or ok) for every single element of the tuple via python manage.py test myapp -v=2, therefore putting the complete tuple in one execution of a function seems like a bad approach too. Like the headline suggests, my code lives in a django environment. I'd be happy to use the django testing framwork so i can execute this test using python manage.py test. What would be a good approach to implement this test? -
Display time stored in database in HTML (django)
I'm building a bus booking website using Django. Users fill From, To, Bus type(ordinary or Volvo) and date. Results display the buses available on that route on that particular date. I made three tables - Bus, Route, and Frequency. You can check my models.py and views.py here - https://dpaste.de/Oi6a I convert the date to the corresponding day of the week. I have filtered out the buses, However, I want to display time on the template. This is part of my views.py code: def select(request): bus_type = request.GET.get('bus_type') bus_from = request.GET.get('bus_from') bus_to = request.GET.get('bus_to') date_string = request.GET.get('date') date = datetime.strptime(date_string, '%Y-%m-%d') day = calendar.day_name[date.weekday()] kwargs = { '{0}__range'.format(day): ["00:00:00", "23:59:59"],} qs = Frequency.objects.filter(bus__type_of_bus=bus_type, bus__route__location_from=bus_from, bus__route__location_to=bus_to, **kwargs) context = {'qs': qs, 'date':date_string,} template = 'select.html' return render(request, template, context) As you can see qs filters the buses available and is then passed to the template. This is a part of the template: <div id="pricing-table" class="clear"> {% for info in qs %} <div class="price_block"> <h3>{{ info.bus.type_of_bus }}<span>{% if info.bus.type_of_bus == 'Volvo' %} Rs 550 {% else %}Rs 330 {% endif %}</span></h3> <a href="{% url 'book:seats' %}"rel="follow" rel="noreferrer" class="signup" type="submit">Book</a> <ul> <li><b>Bus Number -</b> {{ info.bus.bus_number }}</li> <li><b>Route -</b> {{ info.bus.route }}</li> <li><b>Date -</b> … -
Plugin Like Django Activity Stream For Flask [on hold]
Django has awesome plugin named Django Activity Stream. From doc: Django Activity Stream is a way of creating activities generated by the actions on your site. I want to know if there is a plugin like Django Activity Stream for flask. (I couldn't find any for flask) -
Upgrading Django-cms from 2.4 to 3.3 - migration problems
I'm trying to upgrade Django-cms from 2.4 to 3.3 (and django==1.9). But when i'm trying to run manage.py migrate. Table 'cms_pageuser' already exists But when I'm resetting all migrations. I'm getting the errors that django-cms is missing tables e.g. is_home. It seems that already existing tables and missing tables are both in the initial migration file? So I can't run it, but I also can't fake it ... Any ideas? -
Highcharts not displaying in a django app
I am trying to create data visualization dashboard in a django project am working on, i am using highchart js to achieve this.My problem is even after following the documentation, my data is not been displayed even as a simple line chart.I am sure am missing something, kindly need help. my models class Company(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=50) email = models.EmailField(max_length=75) city = models.ForeignKey(City) sector = models.ForeignKey(Sector) description = models.TextField() def __unicode__(self): return self.name class Feedback(models.Model): PENDING,RESOLVED = range(2) FEEDBACK_STATUS = ( (PENDING,'Pending'), (RESOLVED, 'Resolved'), ) title = models.CharField(max_length=100) feed_back = models.TextField(verbose_name='feed back') date_posted = models.DateTimeField(verbose_name='date posted',auto_now_add=True) customer = models.ForeignKey(Customer) company = models.ForeignKey(Company) status = models.PositiveSmallIntegerField(null = True ,choices=FEEDBACK_STATUS, blank = True) # status = models.BooleanField(default=False) objects = FeedbackManager() def __unicode__(self): return self.title views.py def chart_data(request): """ this model holds the data visualization datasets """ company = Company.objects.get(pk=1) feedbacks = Feedback.objects.filter(company=company) feeds = feedbacks.count() return render_to_response('cfback/dashboard.html',RequestContext(request, {'company':company, 'feeds':feeds})) and on the template side i have the following code base.html https://codeshare.io/5w9wDD and the dashboard.html is https://codeshare.io/5zlKvk you'll note on the dashboard.html i am testing with on of the demo charts from highcharts and calling a variable from my model to test if anything is been displayed the rest are …