Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: django.test TestCase self.assertTemplateUsed
Working on Hello Web App. Please help with TestCase: test_edit_thing. Here's the error details: The error in case of '/things/django-book/edit/': # AssertionError: No templates used to render the response response = self.client.get('/things/django-book/edit/') self.assertTemplateUsed(response, 'things/edit_thing.html') The error in case of '/things/django-book/': # AssertionError: Template 'things/edit_thing.html' was not a template used to render the response. Actual template(s) used: things/thing_detail.html, base.html response = self.client.get('/things/django-book/') self.assertTemplateUsed(response, 'things/edit_thing.html') Code Snippet: from django.contrib.auth.models import AnonymousUser, User from django.test import TestCase, RequestFactory from collection.models import Thing from .views import * class SimpleTest(TestCase): def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = User.objects.create_user(username='Foo', password='barbaz') self.thing = Thing.objects.create(name="Django Book", description="Learn how to build your first Django web app.", slug="django-book", user=self.user) def test_index(self): request = self.factory.get('/index/') response = index(request) print(response.status_code) self.assertEqual(response.status_code, 200) response = self.client.get('/') self.assertTemplateUsed(response, 'base.html') def test_thing_detail(self): django_book = Thing.objects.get(name="Django Book") request = self.factory.get('/things/django-book/') response = thing_detail(request, django_book.slug) print(response.status_code) self.assertEqual(response.status_code, 200) response = self.client.get('/things/django-book/') self.assertTemplateUsed(response, 'things/thing_detail.html') def test_edit_thing(self): django_book = Thing.objects.get(name="Django Book") request = self.factory.get('/things/django-book/edit/') request.user = django_book.user response = edit_thing(request, django_book.slug) print(response.status_code) self.assertEqual(response.status_code, 200) # AssertionError: No templates used to render the response #response = self.client.get('/things/django-book/edit/') # AssertionError: Template 'things/edit_thing.html' was not a template used to render the response. Actual … -
Create a query with Django
Hi everyone I and try to do a query with the params pass by URL in my case the uRL is like http://127.0.0.1:8000/api/cpuProjects/cpp/es http://127.0.0.1:8000/api/cpuProjects/cpp,ad/es My code to create the query is like this def findElem(request, **kwargs): projects_name = str(kwargs['project_name']).split(',') status = str(kwargs['status']) list_project = tuple(projects_name) print(list_project) query = "SELECT * FROM proj_cpus WHERE project in '%s'" % projects_name print(query) result = run_query(query) the first return this query SELECT * FROM proj_cpus WHERE project in '['cpp']' the second one has to by a query like this SELECT * FROM proj_cpus WHERE project in '['cpp', 'ad']' In this case when I execute the query return that I have a error in the syntax, yes I know the [] is no correct So I convert my params in a tuple so now the query is like that and the error is SELECT * FROM proj_cpus WHERE project in ('cpp') SELECT * FROM proj_cpus WHERE project in ('cpp', 'ad') not all arguments converted during string formatting What is the best way to create the query? Thanks in advance -
Timedelta between two fields
I'm looking for objects where the timedelta between two fields is greater than a certain number of days. Baiscally I have a date when a letter is sent, and a date when an approval is received. When no approval is received in let's say 30 days, then these objects should be included in the queryset. I can do something like the below, where the delta is something static. However I don't need datetime.date.today() as a start but need to compare against the other object. delta = datetime.date.today() - datetime.timedelta(30) return qs.filter(letter_sent__isnull=False)\ .filter(approval_from__isnull=True)\ .filter(letter_sent__gte=delta) Any pointer how to do this? -
Django Python-Social-Auth can't get some facebook data fields
I am learning how to use python-social-auth. I can retrieve name, first_name, gender, but no more than it, and I don't understande why. pipeline.py from .models import Profile from django.contrib.auth.models import User def save_user(backend, user, response, details, is_new=False, *args, **kwargs): if backend.name == 'facebook': print (response.get('name')) print (response.get('gender')) print (response.get('email')) print (response.get('about')) print (response.get('first_name')) print (response.get('birthday')) print (response.get('hometown')) print (response.get('locale')) settings.py SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'account.pipeline.save_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', ) The output: Lorenzo Simonassi male None None Lorenzo None None en_US So, why I am getting None? Tks -
Custom 404 django template
I'm trying to customize the 404 error pages in my application. After searching many possible solutions, I created an 404.html template, added a method which should handle HTTP Error 404 and edited my urls.py. But I guess I'm doing something really wrong. My log presents an invalid syntax error and I cannot solve it. My views.py: # HTTP Error 400 def page_not_found(request): response = render_to_response('404.html',context_instance=RequestContext(request)) response.status_code = 404 return response My urls.py is like: urlpatterns = [ handler404 = 'views.handler404' url(r'^$', views.home),] And the syntax error: Traceback (most recent call last): File "/.../myenv/lib/python3.4/site-packages/django/core/urlresolvers.py", line 393, in urlconf_module return self._urlconf_module AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module' ... File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/dcaled/work/portal-interface/portal/urls.py", line 12 handler404 = 'views.handler404' ^ SyntaxError: invalid syntax Does anyone have an idea of what's going on? Thanks. -
Faster way to populate a table in Django
I use for loop in Django to populate a table, like this. {% block table_1 %} {% for label in results %} <tr> <td class="col_1">{{ label.0 }}</td> <td class="col_2"">{{ label.1 }}</td> </tr> {% endfor %} {% endblock %} Here "results" is a list, it works just fine if the list is small (len(list) <= 150). However, most of the time I have large lists, usually contain ten to a hundred thousand items. It significantly slowing down the response. For a list with 200,000 items, it took about two minutes to open the web page. Is there any faster way to do this? -
Current options for Django permissions CBV/DRF
What are the currently available options for permissions in Django that work for both class-based-views and Django-REST-Framework? I don't want object-level permissions but rather something like rules, django-rules, or dry-rest-permissions. However, the first two appear to be specific to normal views while the second appears to be specific to DRF. I want both. What are my options if I don't want to duplicate my permission rules. -
How can I import a chartjs chart into a django pdf using django_xhtml2pdf
I'm trying to save a chartjs and export it as a PDF, any ideas on how to do this? Thanks, -
Can't load CSS to my django local website
I am running through django tutorial on book "Try Django". Everything was ok until CSS chapter. I have created basic site and now I want to change some colors but I am unable to do it. Django 1.10. I have created directory in my app 'static' and inside is file 'style.css' with some basic instruction to change color of h1 text. Inside settings.py I have: 'django.contrib.staticfiles' and my app installed, Debug is True, STATIC_URL = '/static/' html of site: http://pastebin.com/PBhZieRe Unfortunately h1 text is still black. I tried to read through documentation on https://docs.djangoproject.com/en/1.10/howto/static-files/ but everything looks ok there. When I simply type url 127.0.0.1:8000/static/style.css in my command line I get 304 code. Need some advice on that. Regards. -
Django model with unique_together and without auto incremented id primary key
So I have a Django model that stores 5 days worth of data in it because the amount of data is so large we must delete all data older than 5 days. The model currently has the auto incremented id field that Django creates automatically. The problem here is that pretty soon it won't be able to generate primary keys large enough. Ideally, I'd have a composite primary key, but Django doesn't support this yet. So I was looking at unique_together and wondering if it was possible to just use that as a pesudo pk and remove the auto incrementing id because its not really used for anything in the application. Another option is this module: django-compositekey but I'm not to sure how well its supported? In either case the I would need to combine 4 columns to make a unique record: class MassObservations(models.Model): time = models.DateTimeField() star = models.ForeignKey('Stars') property = models.ForeignKey('Properties') observatories = (('1', 'London'), ('2', 'China'), ('3', 'United States')) station = models.CharField(max_length=2, choices=observatories) mass = models.FloatField() class Meta: unique_together = ('time', 'star', 'property', 'station') Any other ideas on how to treat data/Django table like this? -
Error using django-user-sessions to close a session in Firefox from Chrome
I have a Django's middleware controlling when a user try logging in and exists another user logged with the same. My code checks if exist one more user logged and shows a template asking if the user want logout or finish the others sessions. If the user choses finish the other session, he is redirected to system. The request.path is useful to accept the requests only login and session/delete views. def process_request(self, request): try: object_list = request.user.session_set.filter(expire_date__gt=timezone.now()) except: object_list = None if object_list and len(object_list) > 1: if request.path != '/users/session/delete' and request.path != '/login/': return logout(request) return None The error happens when from Chrome I try finish one session running on Firefox. It redirects to logout instead logging in the system. When I test the feature in localhost, it performs normally. Looking for the error I found that the 'referer' in request header is different when I use localhost and web from Chrome. What can I do to fix this? -
Change value depends of other field value Createview
I need to assign a value to a field, if a checkbox is "on". I can't call form.is_valid() because this field is unique and it raises a exception before assigment in form_valid() class SocioNuevo(SuccessMessageMixin, CreateView): model = Socio template_name = "socio_nuevo.html" form_class = SocioForm success_message = "success" def get_success_url(self): return reverse_lazy('socio-miembro-nuevo', args=(self.object.id,)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) num_auto = request.POST.get('num_auto') if num_auto == "on": print('kaga' + request.POST.get('numero')) ultimo_socio = Socio.objects.last() numero = ultimo_socio.numero[1:5] numero = int(numero) + 1 numero = 'N' + str(numero) print(numero) kwargs['numero'] = numero return super(SocioNuevo, self).post(request, *args, **kwargs) I have tried too form.instance.numero besides kwargs['numero'] but the value not change before form.is_valid(). How can I do this? is request.POST.get('num_auto') the best way to access a field value declared in forms outside the model fields? Thx -
Django with mod_wsgi: error importing sqlite3
I made a very simple project with django using python 3.4, django 1.10.2, and virtualenv all on FreeBSD. I cannot get mod_wsgi to work for the life of me, and I have done almost nothing beyond building the project and running manage.py migrate. It seems to be having a problem importing sqlite3 but in the virtualenv I can run python and import sqlite3 and _sqlite3. I get the following: mod_wsgi (pid=15765): Target WSGI script '/server/apache/partner/partner/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=15765): Exception occurred processing WSGI script '/server/apache/partner/partner/wsgi.py'. Traceback (most recent call last): File "/server/apache/partner/partner/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/server/apache/partner-env/lib/python3.4/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/server/apache/partner-env/lib/python3.4/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/server/apache/partner-env/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/server/apache/partner-env/lib/python3.4/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/server/apache/partner-env/lib/python3.4/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/server/apache/partner-env/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/server/apache/partner-env/lib/python3.4/site-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/server/apache/partner-env/lib/python3.4/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/server/apache/partner-env/lib/python3.4/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/server/apache/partner-env/lib/python3.4/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/server/apache/partner-env/lib/python3.4/site-packages/django/db/utils.py", line 211, in … -
How to make a string visible on a webpage using Django form fields
I have a django page I've created and managed to pass values to it. I am trying to make a text box which would contain some string. this string can be edited and saved by the user if needed. views.py form = EditProjectForm(project_name = project_name,store_id=store_id, `enter code here`start_date=start_date,end_date=end_date,data = request.POST or None) context = {'someList': someList ,'form':form} return render(request, 'editview.html', context) forms.py class EditProjectForm(forms.Form): def __init__(self, *args, **kwargs): self.project_name = kwargs.pop('project_name') super(EditProjectForm, self).__init__(*args, **kwargs) self.fields['project_name'] = forms.CharField(self.project_name) I tried using forms.CharField(widget=forms.TextInput(attrs={'placeholder': self.project_name })) But that does not show up as editable text. I would like self.project_name to be visible on my page in a text box and be editable. this is what I would want the output to look like -
Django app can't find jquery
I am working on a template that is served up from one of my Django projects apps. The template extends from a base template that is bringing in all the scripts and stylesheets I need from a static directory in my main app. when I go to another template, my 'home' template, served up by a view function in my main app, everything works the way it should. JQuery is up and running with no errors, and every static reference is.....referencing. In another app however, my Services app, I'm getting an error that says it can't find JQuery, and the path it shows its trying to go down to get JQuery has services at the beginning. GET http://localhost:8003/services/static/node_modules/jquery/dist/jquery.min.js I added a STATICFILES_DIRS list configuration to my settings file to say that if Django can't find a static folder in that app, to also look in my main app for a static folder. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "HalloweenProject/static") ] Is there some key ingredient I'm missing, or is there some ordering/syntax issue here ? -
dynamically make a form readonly without changing properties
In my view I am passing a form to the template in the following way return render(request, 'editCase.html', {'form': CaseDetails(),} ) and in the template i am displaying the form as such <form role="form" action= ... method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Submit</button> </form> My question is how can i make a form non-editable ? Is there anything i can do in the view to make the entire form read only ? I know ic an go through each individual attribute and mark it as read only i wanted to know if there was a better way ? -
Run Celery task at user selected time
I have a Django app and once a day the system should send an email at a specific time. At the moment I'm using Celery + Redis to send the email at a specific time of the day. I want to allow the user the set the time of day that the background task must run that will send the email. What is the best way to achieve this? I can't find any examples where the user sets this time. Alternatively I will allow the users to select the hour when the email must be sent. Either 9:00, 10:00 etc. I will then set the task to run every hour and check if any user has selected that hour. This doesn't seem like the cleanest approach. Any other suggestions? My app is running on Heroku, not sure if that makes a difference -
Can't extend templates correctly - missing elements from parent template
I'm trying to create two tables which I want to be inside the Django admin. I know what template I have to extend but I can't figure out why there missing some elements. For example Logout, Welcome text etc. I want to have normal Django admin header there. This is a regular django admin header - right side (with theme so there is greeen): And this is the header of extended template: I'm attaching my template and admin base.html: {% extends "admin/base.html" %} {% load static %} {% load i18n %} {% load render_table from django_tables2 %} {% block title %} Admin Pairing {% endblock %} {% block extrahead ..... endblock %} {% block branding %}{% trans "Pairing Rides" %}{% endblock %} {% block content %} <h2>{% trans "Candidate pair reservations" %}</h2> <br> {% render_table table %} <hr> <h2>{% trans "Existing pair reservations" %}</h2> {% render_table table_existing %} <div class="overlay"> <div id="loading-img"></div> </div> {% endblock %} And this is the template I extend from: {% load i18n admin_static %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{% … -
how to make django manage a table that wasnt in the migration but in the database?
Ok, where i work we are using a database that we would like to continue using but instead connect it to a different front end. Django 1.8 we did a inspectdb and we did a makemigration based on that infomation and migrated but still wont work. the other tables work fine but the other tables didnt exist before the migration (and wont taken from another database ) and the table we are looking at had information we wanted to keep for testing the error we get is column plans_to_lodge.id does not exist LINE 1: SELECT "plans_to_lodge"."id", "plans_to_lodge"."sm_sequence"... -
Capturing WindowsError in template
I'm coding on a Windows machine but I'm running my production site on Linux. When trying to reach a page on my development machine using a database copied from the production system, I get errors while trying to list files if these files don't exist locally. This is as expected, since I just copied the DB and not the files. I don't want/need the files, but I don't want following error either: WindowsError at /126/documents/ [Error 3] The system cannot find the path specified: u'C:\mysite\media\documents\2016\07\26\myfile.docx' Instead of throwing the error, I'd prefer to handle this in my template, something like: {% if doc.data %}{{ doc.data.size | filesizeformat }}{% else %}File not found{% endif %} However that doesn't work. doc.data does exist, since the DB knows a value for this file location. But the file isn't available on the disk. Any way to catch this properly, preferably in the template? My model: class Document(models.Model): data = models.FileField(upload_to="documents/%Y/%m/%d") -
django rest auth email validation
Can someone explain how to set up email verification for django rest auth ? My settings.py contains: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False And I've added this line in my urls.py: url(r'^accounts/', include('allauth.urls')), But when I register with this endpoint: rest-auth/registration/, the email is not sent, but the user is created. What is the good configuration to send email confirmation? Do I have to have a SMTP server? -
Transform a base 64 encoded string into a downloadable pdf using django rest framework
I have a django/python3 application that requests the Limesurvey API and gets a base 64 encoded string as result. I'd like to return this result as a downloadable pdf file. Here's my current implementation that's simply display the base 64 string into a blank page... data = limesurvey.export_responses_by_token(survey_id, token) response = HttpResponse(data, content_type='application/pdf') return StreamingHttpResponse(response) Any help would be very appreciated! -
django left outer join with where clause subexpression
I'm currently trying to find a way to do something with Django's (v1.10) ORM that I feel should be possible but I'm struggling to understand how to apply the documented methods to solve my problem, so here's the sql that I hacked together to return the data that I'd like from the dbshell with an sqlite3 database: select voting_bill.*,voting_votes.vote from voting_bill left outer join voting_votes on voting_bill.id=voting_votes.bill_id where voting_votes.voter_id = ( select id from auth_user where username="django" ); Here's the 'models.py' for my voting app: from django.db import models from django.contrib.auth.models import User class Bill(models.Model): name = models.CharField(max_length=255) description = models.TextField() result = models.BooleanField() status = models.BooleanField(default=False) def __str__(self): return self.name class Votes(models.Model): vote = models.NullBooleanField() bill = models.ForeignKey(Bill, related_name='bill', on_delete=models.CASCADE,) voter = models.ForeignKey(User, on_delete=models.CASCADE,) def __str__(self): return '{0} {1}'.format(self.bill, self.voter) I can see that my sql works as I expect with the vote tacked onto the end, or a null if the user hasn't voted yet. I was working to have the queryset in this format so that I can iterate over it in the template to produce a table and if the result is null I can instead provide a link which takes the user to another view. … -
Django Many to Many Field
Whenever I create a new PreDefinedSet it grabs all the equipment that I've added in my database. Question is how do I make it blank and is it possible to edit what's inside a many to many field? My goal is to make a class where in it is a list of equipment which can be predefined by the users. Here are my models: class Equipment(models.Model): name = models.CharField(max_length = 50) class PreDefinedSet(models.Model): name = models.CharField(max_length = 100) Equipments = models.ManyToManyField(Equipment) -
Cannot parse my geojson (Seems it is always a string?)
I am trying to get objects from a database and return it to my webpage in json format. It seems to be working yet on the javascript side it feels like it is still a string even after a JSON.parse views.py: def globe(request): if request.method == 'POST': form = EntityGlobeForm(request.POST) if form.is_valid(): #you are going to have to make a panel and paginate footprints #object_list = ChangeDetectCSV.objects.filter(processing_level='RAW') #AND DATE sensor = form.cleaned_data.get('layer') #it is really sensor #if sensor is not object_list = CesiumEntity.objects.filter(sensor = sensor) jdata= serialize('geojson', object_list, geometry_field='mpoly', fields=('name','file_name', 'id',)) #get the selection check box that was clicked to know what entities to get #grab entities #object_list = ChangeDetectCSV.objects.filter(processing_level='RAW') #AND DATE #wrap it up with a listing of which ones work, and html and all and pass it back to the view. # do something with your results return HttpResponse(json.dumps({'data': jdata})) else: form = EntityGlobeForm return render_to_response('swsite/sw_nga_globe.html', {'form':form }, context_instance=RequestContext(request)) Then my html form: $('form').submit(function(e){ $.post('/swsite/globe/', $(this).serialize(), function(data){ //this var json = JSON.parse(data) ... ..etc.. The problem is, json.data[0] returns a string character (So the feature data must be in a diff array). If I do a console.log(json.data); Then this is my output: { "type": "FeatureCollection", "crs": { "type": …