Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error 500: Internal Server Error
The website was running without any problem. I recently updated wcgi.py and production.py, and now I get a 500 error. Here's the detailed response: Error 500: Internal Server Error The server encountered an internal error and was unable to complete your request. Error message: (none) Some possible causes of this could be: The script/program that was executed contains errors Or The permissions for the script are not properly set. The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script. How could I fix this problem? -
Django: Encrypted password to legacy (not auth_user) table
Django noob. Exported and imported tables from MySQL to PostgreSQL. The table for clients and customers is called users. Trying to update the password for the test account to what Django uses for encryption using python manage.py shell. Tried the following which obviously wouldn't work because the hashing algorithm isn't being imported in: from account.models import Users user = Users.objects.filter(pk=2) user.set_password('new_password') Errors because there is no attribute 'set_password'. Fine. Try what all the tutorials say: from django.contrib.auth.models import User User.objects.filter(pk=2) Queryset [] User.objects.all() Then it returns the only user in auth_user table. So basically, how do I use Django's encryption against the legacy users table? It appears that in Django clients and customer accounts go in auth_user table? I thought of that table as more for users who should have access to /admin and that clients/customers who use the app go in a different table. -
Error after installing django cors header
i've installed django corsheaders from reference , is below my code : INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'ms', 'transaksi') MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware') CORS_ORIGIN_ALLOW_ALL= True when i run program, python manage.py runserver and then there is an error : File "/usr/local/lib/python2.7/dist-packages/corsheaders/checks.py", line 14, in AttributeError: 'module' object has no attribute 'register' how to solve that ? -
Django MySQL Warning: (1292, "Incorrect datetime value
I upgrade Django 1.9.8 to 1.10.4,Sometimes, runserver will print: /usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py:110: Warning: (1292, "Incorrect datetime value: '%2017-01-04%' for column 'recorded_dt' at row 1") return self.cursor.execute(query, args) /usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py:110: Warning: (1292, "Incorrect datetime value: '%2017-01-04%' for column 'create_dt' at row 1") return self.cursor.execute(query, args) /usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py:110: Warning: (1292, "Incorrect datetime value: '%2017-01-04%' for column 'recharge_dt' at row 1") return self.cursor.execute(query, args) /usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py:110: Warning: (1292, "Incorrect datetime value: '%2017-01-04%' for column 'in_dt' at row 1") return self.cursor.execute(query, args) /usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py:110: Warning: (1292, "Incorrect datetime value: '%2017-01-04%' for column 'out_dt' at row 1") Django 1.9.8 Do not have this problem. My env: Django1.10.4, Python3, mysqlclient 1.3.9 and MySQL56。 datetime store in mysql is 2017-01-04 not %2017-01-04%,it look like mysql LIKE statement,but why throw a warning ? -
pytest/celery - Failed: Database access not allowed
I'm having some trouble getting pytest to test a celery task that's part of a django project. The only way I can get it to work is to import the task in the test method. # tasks.py from __future__ import absolute_import import logging import django django.setup() # flake8: noqa from .celery import app from .models import Run from celery.exceptions import TaskError @app.task(bind=True, throws=(TaskError,)) def get_runs_task(self, testrun_id=None): ... return True Works: # test_tasks.py # flake8: noqa from django.test import override_settings import pytest @override_settings(CELERY_ALWAYS_EAGER=True) @pytest.mark.django_db def test_get_runs_one(): from ami.tasks import get_runs_task result = get_runs_task.delay(testrun_id='123456') assert result.successful() Displays Failed: Database access not allowed, use the "django_db" mark... error: # test_tasks.py # flake8: noqa from django.test import override_settings import pytest from ami.tasks import get_runs_task @override_settings(CELERY_ALWAYS_EAGER=True) @pytest.mark.django_db def test_get_runs_one(): result = get_runs_task.delay(testrun_id='123456') assert result.successful() Any help would be greatly appreciated, thanks. -
How to compare a var with an integer (0) in Django Template?
I cannot figure this one out and it is driving me nuts! Seems so simple but I must be missing something. I am trying to compare a count (integer) with 0, if the value of the count is 0 then print a message using noty. Here is my code: var count = 0; {% for inf in prospect.prospect_industries.all %} {% if inf.is_interested %} count = count + 1; {% endif %} {% endfor %} displayNotification(count + " " + zero); //I see 0 0 in the message {% if count == 0 %} displayNotification("Count is 0!!!!"); {% endif %} What am I missing? I tried using "0" |add:0 to convert the count variable but nothing works, it just never goes inside the if checking if count == 0. Thanks for the help! -
Adding public attribute in Django model
giving users the option of making a topic public. This would require an attribute called public as part of the Topic model (this should be set to False by default) and a form element on the new_topic page that allows the user to change a topic from private to public[enter link description here][1] from django.db import models from django.contrib.auth.models import User class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..."enter code here -
Heroku: error running django migrations
I'm writing a django app that is currently deployed on heroku. The latest migrations I have made throw an error which I don't understand, see below. This error does not appear locally, maybe that is because I use sqlite locally and postgres on heroku, but that is only a guess. I generated the migration locally and pushed it. I use django 1.10 and a virtual environment with python 2.7. Here is my terminal ouput when I try to run the migration: heroku run python manage.py migrate Running python manage.py migrate on ⬢ limitless-lake-59470... up, run.3202 (Free) Operations to perform: Apply all migrations: admin, auth, contenttypes, jobs, sessions Running migrations: Applying jobs.0015_auto_20161230_2039...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, … -
Modifying the Wagtail publish dropdown (per app)
I'd like to reconfigure the default "Publish" menu. The default configuration is this: I'd like to make Publish the default action, and move it to the top. I'd also like to remove Submit for Moderation, as our site has no current need for that feature. Ideally, I'd love to be able to override the menu config on a per-app basis - we will likely have other sections of our site in the future where we want a different config. Is this possible? -
How to define ModelForm for multiple fields with the same name?
I want to define a ModelForm to validate a form which have severalchoice` fields , like this: <form role="form" action="/create/poll" method="post"> {% csrf_token %} <input type="text" name="title"> <input type="text" name="choice" ><br> <input type="text" name="choice" ><br> <input type="text" name="choice" ><br> <button type="submit">Submit</button> </form> Since Poll and Choice are differnt models, I have define two ModelForms as: class PollForm(forms.ModelForm): class Meta: model= Poll fields= ('title',) class ChoiceForm(forms.ModelForm): class Meta: model= Choice fields= ('choice',) The view: def create_poll(request): form = PollForm() args = {} if request.method == 'POST': print request.POST pform = PollForm(request.POST) cform = ChoiceForm(request.POST) if pform.is_valid(): poll = pform.save(commit = False) poll.title = pform.cleaned_data['title'] poll.creator = request.user poll.pub_date = timezone.now() poll.save() if cform.is_valid(): #This condition not met for c in cform: if c != "": choice = cform.save(commit = False) choice.poll = poll.id choice.choice = cform.cleaned_data['c'] choice.save() The problem is that the choices are not saved because ChoiceForm is not validated. How can I fix this? -
Looking for wagtail modeladmin PermissionHelper example
In "wagtail_hooks.py" I have the code below. As wagtail admin I can see the StudentModelAdmin, but as a user with restricted access to the admin interface I can't. I would like to allow users with wagtail admin access and the specific permission below to access the student model admin. How do I go about creating the "CourseRegisterPermission" class? from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register) from wagtail.wagtailcore import hooks from .models import Participant @hooks.register('register_permissions') def view_course_registrations(): return Permission.objects.filter(codename="view_course_registrations") class CourseRegisterPermission(PermissionHelper): # how do I allow users with the permission to view course registrations # to see the 'StudentModelAdmin" below? class StudentModelAdmin(ModelAdmin): model = Participant menu_label = "Student Registrations" menu_icon = "group" search_fields = ('name', 'supervisor_name') list_display = ('name', 'email') list_filter = ('course',) permission_helper_class = CourseRegisterPermission I tried to find some examples of wagtail PermissionHelper but wasn't able to find any. Any hint would be appreciated! -
Django: Adding db_index to existing table
I have a Django model where I want to add a db_index=True to a field after the table was created. I figured out that Django doesn't create a migration, thus the index is not created. If the table is nonexistent and first created, Django creates the index. I've read Django : db_index and makemigrations, but I wonder if it's a good idea to manually create a migration file? I'm using MySQL. What's the Django best practice on this? -
Django 1.10 Apache2 mod_wsgi IOError: failed to write data
I have a django site with django version 1.10.5 djangorestframework==3.5.3 This website hosts files segregated by components for the users to be able to download them. Since yesterday, I am seeing the following issue. For a couple of components, lets say 'a' and 'b', I am not able to download the files onto a Linux box. For the rest of the components, I am able to download the files. The reason I say linux is because.. I downloaded the same files to my macbook and I am able to download without any issues. On the Linux boxes, I see the following error: 2017-01-05 15:06:18 (5.50 MB/s) - Read error at byte 10357143/35563520 (Connection reset by peer). Retrying. And on the server side(Initially was running django development server, now replaced with mod_wsgi and apache2): [Thu Jan 05 15:21:18.588286 2017] [:error] [pid 24756] [remote 10.11.30.20:52525] mod_wsgi (pid=24756): Exception occurred processing WSGI script '/var/www/xyz/wsgi.py'. [Thu Jan 05 15:21:18.588407 2017] [:error] [pid 24756] [remote 10.11.30.20:52525] IOError: failed to write data I thought it was an issue with the client. But I see the same issue with wget, curl, httpie I already scanned all the relevant content that google returns for such errors with python/Django/wsgi/apache2 … -
If item has field then display field Django
So i made a model where putting in a picture is optional ... Now what I'm trying to do is display ALL posts as part of the home screen including ones that don't have an image (where the user left the image blank) How do I go about doing this? If anyone could help that would be great!! Thanks! This is what I have so far: HTML: {% for post in posts.all %} <a href="{% url 'postDetail' post.id%}"><h3>{{post.title}}</h3></a> <h4><span class="glyphicon glyphicon-time" aria-hidden="true"></span> {{post.pubDatePretty}}</h4> <br /> {% if POST HAS IMAGE %} <img src="{{ post.image.url }}" class="img-responsive center-block" style = "max-height:150px;"/> {% endif %} <br /> <p>{{post.summary}}</p> <br /> <br /> <br /> {% endfor %} Model Page: from __future__ import unicode_literals from django.db import models class Post(models.Model): title = models.CharField(max_length=250) pubDate = models.DateTimeField() image = models.ImageField(upload_to='media/', null=True, blank=True) body = models.TextField() def __str__(self): return self.title def pubDatePretty(self): return self.pubDate.strftime('%b %e %Y') def summary(self): return self.body[0:100] -
Django 1.10 authentication on all apps
My Django project is a single web site which has the following directory structure: project -- main_folder -- settings.py -- views.py -- urls.py [1] -- ... -- app_folder -- views.py -- urls.py [2] -- ... -- not_app_folder -- views.py -- urls.py [3] -- ... -- manage.py I use this code in urls.py [1] to authenticate a user: from django.contrib.auth import views as auth_views ... urlpatterns = [ url(r'^login/$', auth_views.login), ... ] I have a code that successfully worked on all of my web-site pages with Django 1.9 (a template method {% if user.is_authenticated %} returns true on all pages). After upgrade authentication works well on all urls from urls.py [1] file, but when I move to pages mentioned in urls.py [2] (it is an application directory) or urls.py [3] (it is a simple directory), template method {% if user.is_authenticated %} returns false (I have the same template for all pages). What has changed in Django 1.10 and how to keep authentication alive on any page of a web-site? -
Django formset - not setting initial data when data is passed
I am creating form using Django Form wizard and formsets. initial_data_set = [] for x in some_list: initial_data_set.append({ 'title' : x.title, }) data = { 'form-TOTAL_FORMS': '5', 'form-INITIAL_FORMS': '5', 'form-MAX_NUM_FORMS': '', } formset_class = formset_factory(TitleForm, extra =0) formset = formset_class(data=data, initial=initial_data_set) return formset I was able to see initial data in my form when I was not passing 'data'. However, not passing data was giving me formset.is_valid as False and there was None in the cleaned_data. So I created data{} and passed it as per the documentation here - https://docs.djangoproject.com/en/1.7/topics/forms/formsets/#understanding-the-managementform Since I started passing data, form is not getting populated with initial data. I have put debug statements in formsets.py under BaseFormSet() class. It is getting both data and initial data that I am passing. I have been struggling with this for few days. Any help on how I can populate my form and get cleaned data will be great. -
Django DRF - Auto Increment Field set Start value
I'm new to Django DRF and looking for a solution to set start value for auto increment field in the model. The default value starts from 1. I want to set the start value as a 5 digit number. Any help appreciated. -
Cannot retrieve specific data from django?
I'm trying to create a simple page containing 1 video and as many comments as it has and each comment replies I basically created three models, one for Video, one for comment and one for reply. then I tried to retrieve the data in the view file. I successfully retrieved video and comments but failed to retrieve replies of each comment. I'm using django 1.10.4 models.py class Video(models.Model): title = models.CharField(max_length=120) embed_code = models.CharField(max_length=500) slug = models.SlugField(null=True, blank=True) category = models.ForeignKey("Category", null=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) active = models.BooleanField(default=True) featured = models.BooleanField(default=False) free_preview = models.BooleanField(default=False) share_message = models.CharField(max_length=150, default=default_share_message) objects = models.Manager() # activemodel = ActiveModel() featuresandactive = Features() class Meta: unique_together = ('slug', 'category') def __str__(self): return self.title def get_absolute_url(self): try: return reverse('video_detail', kwargs={'vid_slug':self.slug, 'cat_slug':self.category.slug}) except: return "/" class Comment(models.Model): user = models.ForeignKey(MyUser) path = models.CharField(max_length=350) video = models.ForeignKey(Video, null=True, blank=True) text = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) active = models.BooleanField(default=True) objects = CommentManager() def __str__(self): return self.text class Reply(models.Model): user = models.ForeignKey(MyUser) comment = models.ForeignKey(Comment,null=True, blank=True) text = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) active = models.BooleanField(default=True) objects = ReplyManager() def __str__(self): return self.text views.py def video_detail(request, … -
Using ReactJS with WebSockets to communicate with Django server
I am trying to connect Django with ReactJS over websockets. The problem is I don't know how to use websockets with ReactJS. how to add onmessage, onopen, (...) to ReactJS components? how to update a ReactJS component after onmessage event? I can't seem to find any documentation/tutorials that would help me. Is there a library/framework that would help me in this? -
Django session causes angular with JWT "token missing or incorrect" error
Setup An angular application (~1.5) and django with django (1.9.9) rest framework (3.5.3) running on a server with nginx serving the client directly as static files from / and the api through uwsgi from /api djangorestframework-jwt is in use to provide and validate the JWT tokens for the client. Reproducing the error: User logs into the client front end (angular app) successfully. User clicks a link and GETs some data from the api. User clicks to edit the data and changes form data and PUTs it to the api All is well User gots to /api and logs in via the DRF browsable API with same username and password Goes back to / and tries to submit a form with PUT again. Angular forwards the following error from the django server. {"data":{"detail":"CSRF Failed: CSRF token missing or incorrect."},"status":403, JWT..., "statusText":"Forbidden"} Finding the cause Trying to narrow down the issue, I find that there is no csrf cookie nor session cookie found after logging in with the client app. I'm using JWT for authentication, so it shouldn't need any session. The JWT token is being saved to local storage, not cookies. After logging into the /api or /administration applications which are … -
meta tags does not work for homepage only
On django/angular site og meta tags only doesnt work for homepage "/". Every other page shows nicely when i use facebookexternalhit crawler with curl. Doing snapshots with grunt im getting error 'waiting for body to show timed out'. One of things i managed to get og meta tags "working" was to add {% csrf_token %} tag and but then everything from goes into . Nothing really makes sense. I literally try'ed every answers i've found by googling. And result is still same. Either og meta tags doesnt work for homepage or after adding csrf_token tag they work but they're shown in body. To point out i did resave every html template in both utf8 or utf8bom and no success. -
Difference between data migration and simple function in Django
example from https://docs.djangoproject.com/en/1.10/topics/migrations/#data-migrations What is the benefit of writing a data migration and migrate it over writing a simple function to modify necessary data? def combine_names(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Person = apps.get_model("yourappname", "Person") for person in Person.objects.all(): person.name = "%s %s" % (person.first_name, person.last_name) person.save() class Migration(migrations.Migration): initial = True dependencies = [ ('yourappname', '0001_initial'), ] operations = [ migrations.RunPython(combine_names), ] in this example we could just run the code below and run it. from models import Person for person in Person.objects.all(): person.name = "%s %s" % (person.first_name, person.last_name) person.save() -
Haystack error with Django 1.4.7
this is my settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.humanize', 'haystack', 'principal' ) I get this error when I try to Execute the app: “Error: No module named apps” Help please :( -
Django decorators which checks a global variable
There is a global variable responsible for the condition of the site. The website either on or off. I need that every view was to check the global variable. For something like that respond with @login_required. There is a check code: if SITE_STATUS: #do something else: return render_to_response("site_offline.html") How to add this decorator? -
I created users in my project's app now how can i migrate them to actually django admin 'Users'?
Because of being a new comer in django i created the users in my app rather than in the actually django Users.Now how can i migrate my model to django admin Users so that i can let user login and out using inbuilt functions. here is my admin page: Django Admin