Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I tell if a Django QuerySet has been evaluated?
I'm creating a Django queryset by hand and want to just use the Django ORM to read the resulting querset.query SQL itself without hitting my DB. I know Django quersets are lazy and I see all the ops that trigger a queryset being evaluated: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#when-querysets-are-evaluated But... what if I just want to verify my code is purely building the queryset guts but ISN'T evaluating and hitting my DB yet inadvertently? Are there any attributes on the queryset object I can use to verify it hasn't been evaluated without actually evaluating it? -
TruncDay not working in Django+MySQL5.5
Lets create a small Django app with this model: class Thing(models.Model): timestamp = models.DateTimeField(auto_now_add=True) Now lets try to get a truncated version of this date: Thing.objects.create() print Thing.objects.annotate( truncstamp=TruncDay('timestamp') ).values('truncstamp') If we just run the queryset in Django, we get an error which might explain something: ValueError: Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed? But I have pytz installed, and I've loaded the time zones in my database. I mean, this query works: SELECT CONVERT_TZ(NOW(), 'SYSTEM', 'UTC'); Lets see what query it's trying to run: print Thing.objects.annotate( truncstamp=TruncDay('timestamp') ).values('truncstamp').query This yields the query: SELECT CAST(DATE_FORMAT(CONVERT_TZ(`stuff_thing`.`timestamp`, 'UTC', UTC), '%Y-%m-%d 00:00:00') AS DATETIME) AS `truncstamp` FROM `stuff_thing` If I try to run this query in MySQL it doesn't work. ERROR 1054 (42S22): Unknown column 'UTC' in 'field list' Here's the minimum subset of the query that still gives the same same error: SELECT CONVERT_TZ(timestamp, 'UTC', UTC) from stuff_thing; What are we doing here? Converting from UTC to UTC? Why is the second UTC not quoted? Is Django emitting invalid SQL? Even if you do quote the second 'UTC', all you get from the conversion is NULL. Why is it even trying to convert … -
Django - Filter objects older than X days
I need to filter objects older than X number of days. I realize this question exists here: django filter older than day(s)? However, I not trying to do exactly that, since the number of days, in my case lives inside the model: class Post(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) createdAt = models.DateTimeField(default=datetime.now, blank=True) plan = models.ForeignKey(Plan) # This model has the number of days This is the query I have so far: Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days)) Note the plan.days part of the query. How can I reference plan.days for this query? Is it possible? -
java (play) or python (django) for dashboard design
Our company planning to design CRM (customer relationship management) web application which contains rich frond-end like charts, little animations etc. We are in confusion to decide which framework to use either play or django and which framework works well with AngularJS/ember/chartJS/ReactJS etc. Detail comparisons with performance, scalability, complexity and time will be helpful (if possible). Thank You! -
Allow connecting to Django server from client and other intermediate server
We have this setup: Central Django server, CSRF and login enabled. Except for the login no action may be performed without logging in previously. An Angular2 client which connects for almost every call to the central server. The login on the central server is executed from here. CSRF token is available and authentication works. Another small server which takes files. It is also Django but not CSRF enabled. The client sends files to this server which the central server may never possess or even see. The file upload (using form-data and POST) works fine. However, after a file upload has been completed, we would like this small server to call the central server notifying it of the successful upload. The problem is the last step. The central server refuses the call, saying we need to be logged in. Can we in any way make the central server believe that the request came from the user who logged in with the Angular2 client? How do we have to set up the CSRF token? We are sending the user's CSRF token he got in the client to the small server. We are using the python-requests library, Python 3 and Django 1.10. This … -
Front end open source django package views that can increment and decrement simple sales items to form a cash reconciliation
Am in need of django package that simply outputs class objects defined in one's models and are bootstrapped just like "django_admin_bootstrapped" to build a view daily cash reconciliation for my django app and how to add features like add and subtract in my views.... Thank you stack community... -
Django cache_page()
How to use cache on CBV? I added this to my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:8000', } } My urls.py: url(r'^(?P<resolution>[0-9]+x[0-9]+)/$', cache_page(60 * 60)(ImageView.as_view())) And this is my views.py: class ImageView(ListView): model = DummyImage template_name = 'dummy_images/images.html' def get_context_data(self, **kwargs): """Split resolution string by 'x' character.""" width = self.kwargs['resolution'].split('x')[0] height = self.kwargs['resolution'].split('x')[1] dummy_images = DummyImage.objects.all() dummy_images_counter = DummyImage.objects.all().count() random_image = get_object_or_404(DummyImage, pk=dummy_images[random.randrange(0, dummy_images_counter)].id) context = {'width': width, 'height': height, 'img': random_image, } return context I want to save random_image in cache using memcache and display it in one of my templates.How do I do that? I spent hours reading documentation and answers on stack but I couldn't find anything. -
'AttributeError' While Trying to Pass Instance Arguements in 'post_save'
I have searched everywhere for a solution but the suggested methods are either outdated or simply don't seem to work. It is strange that I could not find a clear answer for this in Django documentation as this seems to be a very common case. I have extended the Django "User" model with my own, named "Userprofile", using a one-to-one relationship. I wish to store some additional data that is related to the User in this model. I have created a "post_save" signal handler to create a Userprofile instance and insert the additional data used during account creation. I have found out that I should be able o use the "instance" variable sent alongside the signal, but when I try to access it, I just get an error that says Django Version: 1.10 Exception Type: AttributeError Exception Value: 'User' object has no attribute '_dateofbirth' I have verified that I can access the form data and the database is working fine as even though I get the error, an entry is created in the application's "auth_user" table. My code is as follows; I am sure the problem is somewhere there but I just can't locate it: models.py: class Userprofile(models.Model): user = … -
no module named utils error
Error code snippet I have installed django and python 2.7 in mac. I have also installed utils but still I am getting the error: from django.template.utils import InvalidTemplateEngineError ImportError: No module named utils This is after installing compressor module. How can I resolve it? -
Download files directly from S3 from Django site
Is it possible to serve a download link directly from S3? I have large zip files I do not want to transfer to my site instance and would prefer to serve out of S3. Is there a way to basically make a button initiate a download directly from S3? I do not care about hiding the S3 url from the user. -
formating html Djago-cms
I create a app, where I can put html code like this <h2>where we are?</h2> <h4>Main Offices</h4> My problem is when I show in my view I see the text with the html tags, I try this {{ item|striptags }} but this remove the html tag from the page, even when I inspect the element it's look like string "where we are? Main Offices" What is the way in django-cms to don't see the html tag in the view, but when I inspect the element the tags is there! -
Django: 'Could not parse' error when creating an HTML list of names of objects from a database
I'm trying to create a website for students and professors which includes a database of courses. Each course is a model Kurs which includes among other fields the following ones, which are the professor running the course and the name of the course: prowadzacy = models.ForeignKey(User) nazwa = models.CharField(max_length=200) In the shell, I can easily find all courses ran by a given professor: >>> Kurs.objects.filter(prowadzacy__username='stefantestowy') <QuerySet [<Kurs: Estetyka 7>]> So in the above I learn that the professor with the username 'stefantestowy' runs one course, 'Estetyka 7'. After a professor logs in (I'm using the built-in Django login mechanism) he or she is redirected to usersite.html, which should display information about the professor, including the list of names of the courses he or she is running. But if I want to crudely use the syntax which works in the shell to produce a HTML list, I encounter a 'cannot parse' error. Namely, my usersite.html contains the following: Your login is {{request.user.username}} </br> Your name is {{request.user.first_name}} {{request.user.last_name}} </br> (...) Here is a list of your courses: </br> <ul> {% for kurs in Kurs.objects.filter(prowadzacy__username=request.user.username) %} <li>{{ kurs.nazwa }}</li> {% endfor %} </ul> which leads to the following error: Could not parse … -
Django 403 CSRF Verification Failed
I'm writing an enrollment website for my school, and using Django for the framework. For the registration, I require a username, password, and registration token. Those have yet to be validated, all I'm attempting to do right now is go from the registration input page (which uses a POST request) to a "You have successfully registered" page. Somewhere along the line, the csrf token is apparently refusing to be validated. My view: def register(request): return render(request, 'enroller/successfulEnroll.html') My page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="container"> <label><b>New Username</b></label> <input type="text" placeholder="Username" name="uname" required> <br> <label><b>Password</b></label> <input type="password" placeholder="Password" name="psw" required> <br> <label><b>Registration Password</b></label> <input type="text" placeholder="Registration Key" name="reg" required> <br> <input type="submit" value="Register" /> </div> </form> </body> </html> When I attempt to go from the registration page to the success page, it gives me an error 403 (CSRF Verification failed. Request aborted). However, when I attempt to go to the url mysite.com/register/, it returns the page I requested with no error. Is there any way to fix this? I've been looking at RequestContext, but I'm not entirely sure where it would be used. -
Do I Need to Migrate to Link my Database to Django
I'm working on a project that I inherited, and I want to add a table to my database that is very similar to one that already exists. Basically, we have a table to log users for our website, and I want to create a second table to specifically log users that our site fails to do a task for. Since I didn't write the site myself, and am pretty new to both SQL and Django, I'm a little paranoid about running a migration (we have a lot of really sensitive data that I'm paranoid about wiping). Instead of having a django migration create the table itself, can I create the second table in MySQL, and the corresponding model in Django, and then have this model "recognize" the SQL table? without explicitly using a migration? -
How to display data depending on country in Django
So I have a Django site that works perfectly and displays everything I want it to in the US. It automatically displays the data from the US data model. What I want to be able to do is basically have an exact clone of my site, maybe under like mysite.com/canada for example, that displays the data from canada. One approach was for me to just add in all the data into the database and add a field that says which country it's from, but I'd rather for each countries data to be in a completely different model. With pure HTML/CSS this would be easy, I would just copy the entire site directory into a sub directory and that would be it for the country. Was wondering if there is something similiar I can do with Django. -
Angular Cordova FileTransfer and Django Rest Framework
I'm trying to upload an object using Cordova-File-Transfer and Django Rest Framework. This is the angular code: $scope.sendData = function(){ var server = Config.serverUrl() + '/product_image_upload/'; var filename = $scope.imagenes[0].name; var path = $scope.imagenes[0].path; window.resolveLocalFileSystemURL(path+filename, function(entry){ var options = { fileKey: 'file', filename: filename, chunkedMode: false, mimeType: 'multipart/form-data', params: { 'filename': filename }, headers: { 'Authorization': $rootScope.token, 'Content-Disposition': 'attachment', 'filename': filename } }; $cordovaFileTransfer.upload(encodeURI(server), entry.toURL(), options) .then(function(resultsUpload){ console.log(resultsUpload); $scope.imagenes = []; $scope.barCode = null; $scope.item = {}; }, function(errorUpload){ console.log(errorUpload); }, function(progressUpload){ $scope.progress = progressUpload; }) }); The Django Rest Framework code is this one: class ProductImageUpload(APIView): renderer_classes = (JSONRenderer,) parser_classes = (FileUploadParser,) def post(self, request): print("REQUEST.DATA: %s" % request.data) print("request.__dict__ : %s" % request.__dict__) image = request.data.get("file", None) request.data is emtpy, don't know why. I have tried it with the MultiPartParser didn't work either. -
Custom middleware class raises error
I want to create a very simple Middleware which just prints 'OK' on every request. The problem is that it raises error: Traceback (most recent call last): File "c:\python27\Lib\wsgiref\handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in __call__ return self.application(environ, start_response) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__ self.load_middleware() File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\core\handlers\base.py", line 52, in load_middleware mw_instance = mw_class() TypeError: __init__() takes exactly 2 arguments (1 given) The middleware class is in project/project/middleware.py middleware.py class UserHasProfileMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) print 'OK' return response SETTINGS.PY MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'SolutionsForLanguages.middleware.UserHasProfileMiddleware' ) Do you know where is the problem? -
Importing path to settings Django (django-rest-auth)
I am stuck with very trivial thing in Django, and that is I don't know how to define path to REGISTER_SERIALIZER in main settings file. I am using http://django-rest-auth.readthedocs.io/en/latest/configuration.html. I added all the apps, and it works without custom serializer. I just need to know how to add valid path this (you can check link for library example). This is what I tried: REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER' : os.path.join(BASE_DIR, "rest\\rest_user_profile\\serializers.RegisterSerializer") } the path is correct and still I get ImportError: No module named 'C:\\...\\rest\\rest_user_profile\\serializers' -
object has no attribute get while overriding the POST method
class CreatePosts(CreateView): model = posts fields = ['title','comments'] def post(self, request, *args, **kwargs): current_inspectionfile = Inspectionfile.objects.get(pk = self.kwargs['pk']) new_post = posts.objects.create(inspectionfile=current_inspectionfile, title =request.POST.get("title"), comments =request.POST.get("comments")) return new_post Models class posts(models.Model): inspectionfile = models.ForeignKey(Inspectionfile, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=120) comments = models.TextField() flag = models.BooleanField(default=False) def get_absolute_url(self): return reverse('posts_form', kwargs={'pk': self.pk}) def __str__(self): return self.title form is a simple template: <form class = "form_horizontal" action = "" method = "post"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> my url is: url(r'^(?P<pk>[0-9]+)/$',views.CreatePosts.as_view(),name=='posts_form') The error I am getting is "posts" object has no attribute get. I have tried seeing other blogs but nothing seems to work. I have overridden the post method in CreatePosts class to work in a certain way. Is this why I am getting this error or is it because of some URL mismatch. Once the user hits submit I want them to come back to the same form hence the URL. -
ELK: using Celery as an easy alternative for Logstash
I'm developing a web application with Django+Celery, and I wish to add a simple stack that let me track events and get statistics. My first thought was Elasticsearch+Kibana, but I don't want to over complicate my deployment (I'm already using AWS Elasticsearch). So I was wonder why I need something like Logstash when I can send my events directly to Elasticsearch (in background with Celery). If I, for instance, have to setup Redis or RabbitMQ to send messages to Logstash so it can sent to Elasticsearch, I could do the same with Celery, which I have already running. My plan would be to call a Celery task from Django, with an array of events that would be sent to Elasticsearch. I'm using AWS SQS to connect with Celery. I understand that with Logstash I can merge different sources, but this is not my problem right now. In fact, I'm already using AWS CloudWatch to centralize logs, which could do the same work as Logstash, but it's easier to send JSON events to Elasticsearch directly. Surely I'm missing something, because I haven't found anyone using Celery like that. But I would like to know the reason. My web it's very small … -
How do you perform a django lookup between different applications using the same database?
I have the following class (reduced down for brevity): from other.app.models import Enclosure class Server(models.Model): enclosure = models.ForeignKey(Enclosure, null=True, blank=True, db_index=True, related_name='server_enclosure') def get_enclosure(self): get_enclosure = self.enclosure.server_enclosure.get(rack=10) models.ForeignKey(Enclosure <-- Enclosure is a class in separate app. Question I have is on the query. I suspect this is not that proper way to to do this since pylint-django complains. Is there a better way within django to perform the get()? I was looking at the django docs, and it looks like the information for lookups that span relationships are tailored towards models within the same application. I can't seem to find any good reference pattern for lookups the span different applications using the same database. -
add/remove fields in django forms
So I have a form where user can post "Parents" details also fields for Children from a different model. What I need is that to allow users to add "Children" fields as many children as they have . Also for the children fields not to be required in case they do not have children. But, if one of the children fields is filled the others are required. models.py : class Parent(models.Model): title = models.CharField(max_length=250) address = models.CharField(max_length=250) class Kid(models.Model): family = models.ForeignKey(Parent) title = models.CharField(max_length=250) age = models.CharField(max_length=250) views.py def add_family(request): if request.method == 'POST': parent_form = ParentForm(request.POST) kid_form = KidForm(request.POST) if parent_form.is_valid() and kid_form.is_valid(): parent = parent_form.save(commit=False) parent.save() kid = kid_form.save(commit=False) kid.family = parent kid.save() return redirect('index') else: parent_form = ParentForm() kid_form = KidForm() template = 'add_family.html' context = {'parent_form': parent_form, 'kid_form': kid_form} return render(request, template, context) template: <form method="post"> {% csrf_token %} {{ parent_form.title }} {{ parent_form.address }} {{ kid_form.title }} {{ kid_form.age }} <button type="submit">Send</button> </form> so if the "kid_form.title" is filled. then the age is required. any help? -
Python- how to query database by class
I have a Python project (I'm quite new to Python), and on one of the webpages, there is a drop-down box which should display a list of all of the projects whose 'status' fields are set to 'live'. It seems that a couple of particular objects are not being displayed in this drop-down box, so I want to manually query the database to check what their 'status' fields are set to. How do I manually query the database for these particular projects by their 'project name'/ 'project code', both of which I know are unique? I've tried getting a list of all of the projects in the shell, so that I can query that list by project_name for the particular projects that I want using the commands: from projects.models import Project prjcts = [] prjcts = Project.objects.all() This gets all of the Project objects and assigns them to the list prjcts. I now want to query that list for a particular project, and have tried doing so like this: 6Stoke = prjcts.get(project_code = 6SPR) My intention was that the project with the project_code whose value was 6SPR would be assigned to the variable 6Stoke, so that I could then find … -
Application stops when Graylog server not running.
In my Django application I'm using Graypy which connect to graylog server via udp. If the server is shut my application also stops working. Is there a way I can extend graypy not to stop application. In case connection not made with graylog server. -
django static folder is not served in apache2
I have inherited a django application (1.7) and I am supposed to install it on Apache2. Everything runs fine when I do runserver from command prompt but as deploy to apache2/mod_wsgi. I am pretty sure the STATICFILES_DIRS has been set correctly. The settings.py is like below: """ Django settings for sampleapp project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tf07wvjy+#g&&#s$spi34_c-jno^8_cb0bw=*dx2ni2+w6x-(h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] ALLOWED_HOSTS = ['192.168.1.36', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'south', 'CordeliaHanelBackend', 'tastypie', 'StudioHanel', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'CordeliaHanelBackend.urls' PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) # TEMPLATE_DIRS = ( # '/var/www/CordeliaHanelBackend-master/StudioHanel/templates/StudioHanel', # ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/var/www/CordeliaHanelBackend-master/StudioHanel/templates/StudioHanel','CordeliaHanelBackend/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', …