Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django default data throw an error during migration
I'm using Django 1.7 class MyModel(models.Model): my_random_field_1 = models.ForeignKey( MyOtherModel, null=True, blank=True, related_name="random_1", default=get_random_1 ) my_random_field_2 = models.ForeignKey( MyOtherModel, null=True, blank=True, related_name="random_2", default=get_random_2 ) And 'random functions': def get_random_1(): ob = MyOtherModel.objects.filter(...some filtering...) try: x = ob[0] return x except: return None def get_random_2(): ob = MyOtherModel.objects.filter(...some other filtering...) try: x = ob[1] return x except: return None And when I'm trying to migrate I gave this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'MyOtherModel' Sentry is attempting to send 2 pending error messages Waiting up to 10 seconds But after that, when I open admin panel and go to MyOtherModel I have this random field, and they are properly init by 'ob[0]' and 'ob[1]' -
Django raw SQL queries with ForeignKey
models.py class Author(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) class Exhibit(models.Model): author_id = models.ForeignKey(Author) title = models.CharField(max_length=60) create.sql (PostgreSQL) CREATE TABLE Author ( id serial NOT NULL, name varchar(30) NOT NULL, surname varchar(50) NOT NULL, ); CREATE TABLE Exhibit ( id serial NOT NULL, author_id int NOT NULL, title varchar(50) NOT NULL ); Those are my simplified models(that map one to one with database tables), and I'm performing a raw query that looks like that Exhibit.objects.raw("SELECT * FROM Exhibit WHERE author_id = 1") In result, I get a ValueError - Cannot assign "1": "Exhibit.author_id" must be a "Author" instance. Is there a way to solve that problem without using ORM and Author.objects(and similar stuff) at all, just by querying into database? -
Django Push Notification - Can't read ANPS certificate file
I am trying to implement push notification on my iOS app that uses a Django backend. I will explain some context before, in case it has revealing information. If you want to go to the problem directly, go the The Problem section. Context Following this tutorial, I have been able to verify that my certificates and provision profiles are correctly configured, as my device is in fact receiving push notifications sent by APN Tester Free. Of course, to make any sense, my Django backend will have to send the notifications. For this, I have installed django-push-notifications. In my django settings file, I have set up the paths to the APNS certificate. This file needs to be a .pem file instead of the normal .cer file that the Apple developer portal exports. To convert the .cer file, one can right click the Push Notification Certificate in Keychain Access and export a .p12 file. To convert the .p12 file to the required .pem, one needs to use Terminal, and run the following command: openssl pkcs12 -in [export p12 file].p12 -out [final pem file].pem -nodes -clcerts To make sure, my .pem file is actually working, I used the following command openssl s_client -connect … -
Determine previous field validation errors in Django's 'model.clean'
I can currently make use of the 'form.clean' method to populate a field that's dependent on other fields (or raise a non-field error if one of the source field(s) is invalid). However, to ensure validation is possible when creating instances of models programmatically and without forms, I'd like to move validation to the model itself. My question: Is there a simpler way to check if a previous individual field validation has failed when overriding 'model.clean'? I've tried something like this monstrosity: from datetime import datetime from django.core.exceptions import ValidationError from django.db import models from croniter import croniter, CroniterBadCronError class CronField(models.CharField): def __init__(self, *args, **kwargs): super(CronField, self).__init__(*args, **kwargs) self.is_valid_frequency = False def validate(self, value, model_instance): try: croniter(value, datetime.now()) except ValueError, CroniterBadCronError: raise ValidationError(u'{0} is an invalid cron frequency.'.format(value)) else: self.is_valid_frequency = True class AuditQuery(models.Model): frequency = CronField(max_length=255) next_run_at = models.DateTimeField(blank=True, null=True, editable=False) def clean(self): if not self._meta.get_field('frequency').is_valid_frequency: raise ValidationError(u'Cannot generate next_run_at from frequency of {0}.'.format(self.frequency)) self.next_run_at = croniter(self.frequency, datetime.now()).get_next(datetime) -
Celery breaks inside Django Unittest
How do you test Celery tasks that manipulate Django models with Django standard unittesting framework? I have a Celery task like: def mytask(obj_id): obj = MyModel.objects.get(id=obj_id) obj.dostuff() and I have a unittest like: from django.conf import settings class Tests(django.test.TestCase): def test_mymodel_task(self): settings.CELERY_ALWAYS_EAGER = True self.assertEqual(MyModel.objects.all().count(), 0) obj = MyModel.objects.create(name='abc') self.assertEqual(MyModel.objects.all().count(), 1) mytask(obj.id) If I run this, it fails on the last line with a traceback like: Traceback (most recent call last): File "tasks.py", line 2, in mytask DoesNotExist To summarize, my unittest confirms a record was created, and then immediately after inside the Celery task, it can't find the record that was just created. I also see a bunch of messages about missing tables for various other apps I use, as well as celery_taskmeta. My guess here is that calling a Celery task function, even in a unittest with CELERY_ALWAYS_EAGER = True, actually creates a new processes, and this process is running outside of the Sqlite3-backed transaction Django uses for the unittest. This means the task is essentially running with it's own blank database, making it impossible to test it. Is there anyway to make Celery tasks seemlessly "pass-through" to the Python function without creating a separate process and screwing … -
Django: pass context to ReactJS
I'm working on a Django web app that utilizes ReactJS for the front-end, and I've come across a scenario where I need to pass a Django model object to the React file. Is there any way to do this? Also, I'm using webpack for my react pipeline if that helps. -
Unable to show mysql database on a basic Django based website
I've been following this tutorial:https://www.youtube.com/watch?v=bRnm8f6Wavk to work on creating a basic dynamic website. I managed to create and test for the database on the mysql server. But I'm unable to reproduce that data on the webpage. Following are the codes for files I had to edit: The views.py file : from django.shortcuts import render_to_response from blog.models import posts def home(request): entries = posts.objects.all()[:10] return render_to_response('index.html',{'posts' : entries}) The url.py has the following: from django.conf.urls import url from django.contrib import admin from blog import views urlpatterns = [ url(r'^$', views.home, name='home'), ] The models.py file has the following code from __future__import unicode_literals from django.db import models class posts(models.Model): author = model.CharField(max_length = 30) title = models.Charfield(max_length = 100) bodyText = models.TextField() timestamp = models.DateTimeField() The settings.py has the following database for input: DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Firstblog', 'USER': 'root', 'PASSWORD': '3305', 'HOST': '', 'PORT': '', }} I have edited the html file to say : <title>A BASIC WEBSITE</title> <!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script> <![endif]--> </head> <body> <div class="container"> <h1> Firstblog </h1> {% endfor %} {% for entry in entries %} {{entry.title}} <h3> Posted on {{ entry.timestamp }} by {{entry.author}} </h3> <p>{{entry.body}}</p> … -
Redirect to admin/login results in 302
I'm trying to redirect to the login page when a user is not authenticated. In my settings.py class I have: MIDDLEWARE_CLASSES = [ 'path.to.AuthRequiredMiddleware', ] Here is my class: class AuthRequiredMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect('/admin/login/') return None However this always results in [24/Jan/2017 14:09:07] "GET /admin/login/ HTTP/1.1" 302 0 when the user is not authenticated, does anyone know how to fix this? Changing the redirection URL results in the same issue no matter what it is. I have also tried to use the django.shortcuts import redirect however I got the same 302 result as well from it. -
RoutablePageMixin and breadcrumbs
A standard Wagtail breadcrumb system like this works perfectly if all of your pages are in a tree (parents/children): {% block main %} {% if self.get_ancestors|length > 1 %} <ul class="breadcrumb"> {% for page in self.get_ancestors %} {% if page.is_root == False and page.url != '/' %} <li><a href="{% pageurl page %}">{{ page.title }}</a></li> {% endif %} {% endfor %} <li class="active">{{ self.title }}</li> </ul> {% endif %} {% endblock main %} But it falls down if some of your sub-pages are not actual children, but instead use RoutablePageMixin. Because the routable pages are really different instances of the parent, the breadcrumb trail stops short of making it down to the routable page. I thought I could add some extra info to the context to detect the situation and special-case it, but all of the WT URL methods return the URL of the "parent" page (i.e. the actual instance), and besides there is no programmatic "title" that could be used in the breadcrumb. What's the best way to have a breadcrumb system that works equally well for child pages and routable pages? -
Why does openpyxl take forever to import in django?
I'm writing (or attempting to write) views to handle importing and exporting xlsx files, but the statement import openpyxl never finishes execution in my view (or anywhere else in my Django application). If I run it from ./manage.py shell it works fine—takes a half-second or so, but works. My view is as follows, stripped to barebones to make sure there's nothing weird to interfere: def test_view(request): import openpyxl return HttpResponse('Testing') and the view never loads. I get rid of (comment out) the one line, it works. Same behavior if I try importing at the top of views.py, except then the problem applies to every view. Even if I try to load a subset, like from openpyxl import Workbook, or from openpyxl.workbook import Workbook as suggested here, same deal. Pertinent info: openpyxl 2.4.1 django 1.10.2 python 3.4.3 Any ideas as to what's happening? Any way I can perhaps get an error message to show up to tell me what's going on? -
Raw SQL queries in django
How can I perform the following SQL code in model.py? Any suggestion would be appreciated. SET @SearchName = 'MC06182%'; SET @Searchtype = 'film'; SELECT t1.name, t2.name AS name2, t3.name AS name3 FROM (SELECT name, sources, sample_type FROM inventory_sample WHERE sample_type = @Searchtype ) t1 LEFT JOIN inventory_sample t2 ON t2.ID = t1.sources LEFT JOIN inventory_sample t3 ON t3.ID = t2.sources WHERE t3.Name like @SearchName: -
Serving Static Files for Django Project with Elastic Beanstalk
I have set up a deploy through Elastic Beanstalk for a simple Django app. The site seems to be working, but the static files are not being served correctly (styles and scripts are missing). I have the following code inside .ebextensions/django.config container_commands: 01_collectstatic: Command: python manage.py collectstatic --noinput option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django_by_example_blog/wsgi.py aws:elasticbeanstalk:container:python:staticfiles: /static/: static/ When I deploy with the config above, the site returns "URL not found" for any route. However, when I use the following configuration, the site works but styles are missing. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django_by_example_blog/wsgi.py aws:elasticbeanstalk:container:python:staticfiles: /static/: static/ What can I do to fix this? -
'module' object has no attribute 'about' - Django
I am following a book which teaches how to create a web application with Django. I have completed the first few chapters and created an index view and set up some simple URL mappings. I ran this without error. I am stuck on one exercise which asks me to create a new 'about' view and handle it's URL mapping. I went about the same process as was shown for the index example, however, when I run the server, the following exception is thrown: Unhandled exception in thread started by <function wrapper at 0x03886230> Traceback (most recent call last): File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Patrick\Envs\rango\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "c:\python27\Lib\importlib\__init__.py", line 37, … -
Django custom app config
I would like to run code that will be executed only once in django app. my structure: company project common project_config.py __init__.py init.py: default_app_config = "company.project.common.ProjectConfig" settings.py: .. INSTALLED_APPS = ( "company.project" ) .. ProjectConfig.py: from django.apps import AppConfig class ProjectConfig(AppConfig): name = "company.project" def ready(self): do_something() I don't see that the method of ready() in my config is being called. What is wrong? -
Django url conf understanding the syntax
I've been reading the django docs but it is still unclear. I have this piece of url code: urlpatterns = [ url(r'^$', views.index, name='index'), ] From the docs, I know r means raw string, but what is this: '^$' ??? What does the ^ mean, what does the $ mean? There is no clear explanation on the docs? -
no module name 'django'
I'm fairly new to Python and I am trying to create a website using Python 3.5. When I run the code: from django.db import models # Create your models here. class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model""" return self.text I get the message: Traceback (most recent call last): File "models.py"/ line 1, in (module) from django.db import models ImportError: No module named 'django' I tried installing django in the virtual environment again and got the message: Requirement already satisfied: Django in c:\users\owner\documents\learning_log\11_env\lib\site-packages What am I doing wrong? -
Django how to cache class based views
I used to have this view: @cache_page(60) def get_cat_type(request): return HttpResponse(json.dumps(CatType.objects.page_through(0, to_display=True), cls=DjangoJSONEncoder), content_type='application/json') But now that I converted this to the class based view for the Django Rest Framework: class CatTypeView(generics.ListAPIView): serializer_class = CatTypeSerializer queryset = CatType.objects.filter(to_display=True).all() I can no longer simply add the cache decorator to the class. How would I cache that view? I don't want to use the cache middleware for this because I only cache a few views. -
django extend URLField to build URIField
Django model field URLField uses URLValidator, which, by default has a list called schemes with value ["http", "ftp", ...] I need to extend this URLField for allowing input type="url" and browser validation, and also, I need add more schemes to this list, like [default values + "ipp", "smb", ...] class URIField(models.URLField): defaults_validators = [URIValidator()] class URIValidator(validators.URLValidator()): message = "invalid URI" self.schemes += ['ipp', 'smb', ...] super(URIValidator, self).__init__(schemes=self.schemes) This works when URIField class extend from CharField, but does not work when extend from URLField. Also, if it extend from CharField I can not get browser validation because input will be type="text" and not "url". -
Django: Get list of latest cost values by group
I have the following Django model: class Costs(models.Model): """Represents a cost for a vendor / locale combo.""" valid_from_date = models.DateField() vendor_id = models.ForeignKey('Vendor') locale_id = models.ForeignKey('Locale') cost = models.FloatField() In order to preserve historic data, when the cost changes for a vendor / locale combo, we just add a new entry into the table (rather than overwrite the old one) with a new valid_from_date. It's fairly easy to get all of the data from the table with Costs.objects.all(). It's also easy to get an individual vendor / locale's current value with Costs.objects.filter(vendor_id=1, locale_id=10).latest(). What I'm interested in getting is all of the latest cost values for each vendor / locale combo. So essentially running the latest() function over each combination and getting a list / queryset as a result. For example, given the following set of data: Id: 100, Date: 2017-1-1, Vendor: 1, Locale: 10, Cost: $1 Id: 200, Date: 2017-2-1, Vendor: 1, Locale: 10, Cost: $2 Id: 300, Date: 2017-1-1, Vendor: 2, Locale: 10, Cost: $3 Id: 400, Date: 2017-2-1, Vendor: 2, Locale: 10, Cost: $4 Id: 500, Date: 2017-1-1, Vendor: 2, Locale: 20, Cost: $5 I would want the following data back: Id: 200, Date: 2017-2-1, Vendor: 1, … -
Knockout.js save to Django
Currently I am working on a survey application that uses django and knockout.js. I would like it to save the survey results to django but do not know how to pass the data to my views.py. Below is an example survey. Survey.Survey.cssType = "bootstrap"; var surveyJSON = {pages:[{name:"page1",questions:[{type:"checkbox",choices:["apples","oranges","grapes"],name:"1",title:"What fruit do you like?"}]}]} function sendDataToServer(survey) { //send Ajax request to your web server. alert("The results are:" + JSON.stringify(s.data)); } var survey = new Survey.Model(surveyJSON, "surveyContainer"); survey.onComplete.add(sendDataToServer); -
get data from django models with peewee
I have already Django models and data in my mysql database, i want to get this data with peewee but it does nothing. my script.py: import peewee as pw myDB = pw.MySQLDatabase("somedb", host="localhost", port=3306, user="someuser", passwd="somepass") a = myDB.connect() items = Item.get() my django item model: class Item(BaseModel): name = models.CharField(max_length=255) user = models.OneToOneField(User) def __unicode__(self): return self.name -
selection of different DB in save( ) django
I am badly stuck in a pity issue. I am making a django app to upload forms. I know i am not doing it in standard way but still it works. My issue is related to multiple databases. i have defined 3 databases in setting.py as follow: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'root', 'PASSWORD': 'testing', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', }, 'Firewall': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Firewall_Policies', 'USER': 'root', 'PASSWORD': 'testing', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', }, 'CES': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'CES_Policies', 'USER': 'root', 'PASSWORD': 'testing', 'HOST': '127.0.0.1', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } The model of the required class looks like this: class ID_Table(models.Model): FQDN = models.CharField(max_length=128, db_column="FQDN") CES_Using = models.CharField(max_length=256, db_column="CES_Using") MSISDN=models.CharField(max_length=16, db_column="MSISDN") IPv4 = models.CharField(max_length=16, db_column="IPv4") Unique_ID = models.CharField(max_length=64, db_column="Unique_ID") Subscription = models.CharField(max_length=128, db_column="Subscription") class Meta: db_table='ID_Table' And forms.py file is as: class ID_TableForm(forms.ModelForm): class Meta: model = ID_Table fields = ['FQDN', 'CES_Using', 'MSISDN', 'IPv4', 'Unique_ID', 'Subscription'] And the views.py file is something like this: def add_table_page(request, table_specified): request.session.set_expiry(2000) if request.session.get('user_auth') == … -
Django forms: how to use a query to show right options
I have the following model: class Question(models.Model): name = RichTextField ( verbose_name = 'Question' ) QUESTION_TYPE = ( ('Multi', 'Multiple Choice (one correct answer)'), ('Check', 'Multiple Answers') ) question_type = models.CharField( default = "Multi", max_length = 7, verbose_name = "Question Type", choices = QUESTION_TYPE) category = models.ForeignKey( Category, help_text = 'Category for this Question', null = True ) author = models.ForeignKey( User, ) quiz = models.ForeignKey ( Quiz, ) def __unicode__(self): return u'%s' % (self.name) I am trying to use a Django form with it so I have this form: class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['id','question_type','category','name','author','quiz',] widgets = {'id': forms.HiddenInput(), 'author': forms.HiddenInput(), 'quiz': forms.HiddenInput(), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'question_type' :forms.Select(attrs={'class': 'form-control'}), 'category' :forms.Select(attrs={'class': 'form-control'}), } It works fine except the Category model is associated to a specific Quiz and I only want Categories for the Quiz to which the Question is linked. class Category(models.Model): name = models.CharField ( max_length = 30, verbose_name = "Question Categories", ) quiz = models.ForeignKey ( Quiz, verbose_name = 'Quiz', ) def __unicode__(self): return u'%s' % (self.name) I am trying to work out how to limit the Category models presented to the user through the form but I cannot work out how. Help … -
Using docker-compose to collaborate on existing git repo Django project
I'm just getting started with Docker, and I want to use it to containerize a Django project which ~7 collaborators are working on, and I want some of us to have the option of using Docker to speed up the on-boarding process of setting up a local development environment. The app we are working on is a Django app, using Postgres/PostGIS and some other dependencies. So far, I've followed this tutorial which goes through creating a new Django project and using docker-compose to have it run in a container. My question has to do with the workflow of using docker-compose with many other people to collaborate on an existing Django project. Should those of us using Docker follow a similar pattern as shown in the tutorial, but instead of creating a new project, simply clone the repository and proceed as the tutorial does? Sorry if this question doesn't make sense. I'm just trying to get a sense if my use-case is a fit for docker/docker-compose, and if what I'm proposing is plausible. -
Sentry User Feedback form submitting reports to localhost rather than Sentry server
I am using the User Feedback form for the Sentry crash reporter on a 500 error page in a Django app. As per the docs, I use this snippet in the template: <!-- Sentry JS SDK 2.1.+ required --> <script src="https://cdn.ravenjs.com/2.3.0/raven.min.js"></script> {% if request.sentry.id %} <script> Raven.showReportDialog({ eventId: '{{ request.sentry.id }}', dsn: '<my_public_dsn>' }); </script> {% endif %} The GET request gets the crash submission form from https://sentry.<my-domain>/api/embed/error-page/?eventId=<eventId>&dsn=<my_public_dsn>. However, it POSTS the form to localhost: http://localhost:8000/api/embed/error-page/?eventId=<eventId>&dsn=<my_public_dsn>. Resulting in nothing being sent to the Sentry server and this error message in the 404 response: The requested URL /api/embed/error-page/ was not found on this server. In the script Sentry gives me for the reporting form, there is an endpoint variable that is being set to /api/embed/error-page/?eventId=<eventId>&dsn=<my_public_dsn>. This is the endpoint used in the POST. As I call this from localhost, this is where it looks for the endpoint. How do I get the crash report submission to be POSTed to the Sentry server that served the form in the first place?