Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'set' object has no attribute '__getitem__' in Django?
(venv) srk@srk-Lenovo-G580:~/mysite$ python manage.py runserver Unhandled exception in thread started by Traceback (most recent call last): File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/rest_framework/decorators.py", line 15, in from rest_framework.views import APIView File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 98, in class APIView(View): File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 101, in APIView renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES File "/home/srk/.virtualenvs/venv/local/lib/python2.7/site-packages/rest_framework/settings.py", line 213, in getattr val = self.user_settings[attr] TypeError: 'set' object has no attribute 'getitem' -
Transfer data from view to url
I'm working on my django app, and I have problem with pass year to url. I use CVB as view. Below is my solution, but isn't working. Here is my view: class EventsListView(ListView): template_name = 'events/production_list.html' model = Events def get_context_data(self, **kwargs): context = super(EventsListView, self).get_context_data(**kwargs) year_season = Events.objects.filter(is_active=True).last() context['year'] = year_season return context Here is my url: url(r'^/events/(?P<year>)$', EventsListView.as_view()), -
Proper way of using form input to redirect to a url in Django
I managed to get the value from an HTML form to a URL pattern but it wasn't an elegant way of solving the problem. So I'm asking what is the better way to do that, since I'm faced with the same problem again. Here's a simplified version of what I had: My HTML form: <form method='post' action={% url 'pressed_button' %}> <button name="choice" value="Correct-Button"> Click Me </button> <button name="choice" value="Wrong-Button"> Dont Click Me </button> </form> Here's my urls.py: url(r'^PressedButton/$', views.PressedButtonView.as_view(), name='pressed_button'), url(r'^PressedButton/(?P<choice>\w+)$', views.PressedButtonView.as_view(), name='pressed_button_with_user_choice'), and the view class PressedButtonView: class PressedButtonView(View): def get(self, request, choice): return render(request, 'weirdapp/buttonclicked.html', {'button': choice}) def post(self, request): choice = request.POST['choice'] return redirect(reverse('pressed_button_with_user_choice', kwargs={'choice': choice})) Now, I thought if I could just send the value of the pressed button in the "action" attribute of the form <form method='post' action={% url 'pressed_button_with_user_choice' 'pressedButtonValue' %}> it will be a lot nicer code. Also, if I could get an answer to my secondary-but-related question, what does the reverse method in return redirect(reverse()) do? Why not just redirect to a URL pattern name? Thanks. -
Writing files using django forms and multiprocessing
I am uploading a large number of files to server side using python multiprocessing technique and django forms.Here is the code def pooltest(request): try: file_list=request.FILES.getlist('docfile') print 'cpu_count() = %d\n' % cpu_count() total_no_files = len(request.FILES.getlist('docfile')) chunk_size = total_no_files//cpu_count() print chunk_size t1 = time.time() p = Pool() p.map(upload_function, file_list,chunksize=chunk_size) p.close() p.join() But when i trying to upload large number of files following error occuring expected string or Unicode object, NoneType found Please help to fix this?Is this pool configurations are correct?How do i change this so that i can upload large number of files with minimum time. -
How to pass html <span> tags between table rows?
I'm trying to add expandable blocks into the table so when user clicks on a row, he will see expanded block of data. Like here: Expandable rows The problem is that I'm generating the table using Django-tables2 and I don't know and didn't find any appropriate way to do this. There are multiple ways how to do that. I would like to avoid creating hidden rows. Instead of that, I like the idea with <span> tags between rows. I tried to inject html into the last column like this: action = tables.columns.TemplateColumn("""ACTION</td><span style="display: none;" id="record_{{ record.id }}"> <strong class="bold">Description:</strong> <br> <pre>This is row with id=0, containing other content</pre> </span>""") But this creates <span> tags under the table. class ProductsTable(tables.Table): has = tables.columns.TemplateColumn("""HAS""") action = tables.columns.TemplateColumn("""ACTION</td><span style="display: none;" id="record_{{ record.id }}"> <strong class="bold">Description:</strong> <br> <pre>This is row with id=0, containing other content</pre> </span>""") class Meta: model = Product fields = ('code', 'name', 'brand', 'category', 'has', 'action') attrs = {'class': 'table table-hover'} row_attrs = { "onclick":lambda record: "$('#record_{}').fadeIn('slow');".format(record.id) } I would like to avoid adding span tags using JQuery and AJAX it's the last option. Do you have any ideas? EDIT: My new idea is to override table.html. The problem is that … -
django: how to reverse for an object that is only available on another SITE_ID
I have two sites in my django project. How can I, when running my first site, reverse for an object/url that is only available on my second site? I would need this, when building links to items (blog articles, whatever) that are available on the second site only. I'm using reverse('item_detail', args=(self.id) in the get_absolute_url() method from a model that is displayed on the second site. This looks like quite a normal use case to me, but I'm just stuck at the moment? I'm using django-cms, with app hooks, if this is somehow important. -
Advantage of Django ORM V/S Performing raw SQl quries
I have been working with django since two years but still finding the advantage of using django ORM rather than writing raw sql query. Is there any memory efficiency advantage ? Is there any configuration advantage ? Is there any data migrations advantage ? What are the situations I should use Django orm ? Why should anyone use Django orm over raw sql query? -
Can I open a modal with URL parameters in Django to edit a form?
thank you in advance. I am creating a Django template that allows users to add / edit families information. I would like the ability to add my edit forms to a modal but am having issues passing the parameters of the URL. url: url(r'^family/(?P<pk>\d+)-(?P<nav_key>[A-Za-z]{4})-(?P<nav_id>\d+)-(?P<sub_key>[A-Za-z]{4})-(?P<sub_id>\d+)/$', family_view, name='family_detail_sub_key_id'), HTML <a href>: <!-- This is where I need assistance with opening the modal --> Again, thank you -
Django settings LOGOUT_REDIRECT_URL doesn't work
I'm using Django 1.8.7 with the following apps installed: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'myapp', 'storages', 'rest_framework', 'django_tables2',] I use the built-in django.contrib.auth.urls to create my pages for login, password change, etc. I set my LOGOUT_REDIRECT_URL in the settings.py to '/home', exactly like I did with LOGIN_REDIRECT_URL. Logging out a user via the page works fine, but I stil remain at the logout page afterwards. This is not a problem when logging in, the login redirect works like it should. a part of my urls.py: url(r'^accounts/', include('django.contrib.auth.urls'), {'template_name': 'registration/login.html'}), my settings.py: LOGIN_REDIRECT_URL = '/home' LOGOUT_REDIRECT_URL = '/home' Thanks in advance for any help or ideas! -
User cannot upload to Media directory on Pythonanywhere
I'd like to submit a form where there is a filefield, in developpement mode I can submit it successfully but when it comes to pythonanywhere I'm redirected to my custom fail page which means the form didn't get through. The form is saved when there are no attachments, it works on debug true & false on developpement (username.pythonanywhere.com) but not on product (www.domain.com) Here is how I configured pythonanywhere files : settings.py : BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py : urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class AskTicket(models.Model): document = models.FileField(upload_to='attachments') ... And here is how I setup the static files manager : Why users cannot download files ? Did I miss something ? -
Django update the value of a variable in template
i have assigned value to a template using with tag.I am assigning a numeric value to a variable.I want to increment the value of that variable when ever an if condition in a for loop is true. I have tried the in built add filter and tried custom filter but the value is not updating , during each iteration of the loop it returns back to default value.Any suggestions to fix it? -
Getting a 'This field is required` error when updating a model instance
I have an edit view for when a user wants to edit a Post: def edit(request, id): post = get_object_or_404(Post, id=id) edit_form = PostForm(request.POST or None, instance=post) if edit_form.is_valid(): instance = edit_form.save(commit=False) instance.save(update_fields=['content']) return HttpResponseRedirect('/') else: print(edit_form.errors) edit_form = PostForm(instance=post) context = { 'edit_form': edit_form, 'form_post': post } return render(request, 'edit.html', context) When a user edits a Post, I only want them to be able to edit 1 field (content), so i've only rendered that form field in my template (pre-populated with the previous post.content. The other fields are just fields of the object (not a form/can't be edited). ... <form method="post" action="" enctype="multipart/form-data">{% csrf_token %} <h1>{{ form_post.title }}</h1> <p>{{ edit_form.content}}</p> <p>{{ form_post.category }}</p> </form> ... and here is my Post model: class Post(models.Model): ... title = models.TextField(max_length=76) content = models.TextField(null=False, default='') category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') When the edit form is submitted, form_errors returns this: <ul class="errorlist"> <li>title<ul class="errorlist"><li>This field is required.</li></ul></li> <li>category<ul class="errorlist"><li>This field is required.</li></ul</li> </ul> Why is this happening? Doesn't: instance = edit_form.save(commit=False) instance.save(update_fields=['content']) keep the fields from the orignal Post and just change the content field? -
Python Django MongodB mongoengine
How to connect a mongodB to django 1.8 or above??? DATABASES = { 'default' : { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'my_database' } } it doesn't work.. -
How to sort a list of list of objects by an object's attribute in python
I have a list of list of object: [ [obj1, obj2, obj3], [obj4, obj5, obj6], ... ] object is an instance (returned from a django's queryset) that has a date. Now I want to order the outter list depending on the newest date of each object's list (since each list can have one ore more object, I want to get the newest date as a representation of the whole collection). -
Angular 2 and ng2-file-upload (backend Django rest)
I am re writing an application into Angular and have to upload a file. The network shows me status: 200 but there is no response and my back end is not receiving any file. I used example ng2-file-upload I have a situation with request: Chrome: chrome console: Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin is therefore not allowed access. enter image description here Firefox: firefox is not consol error enter image description here My cod: import { Component, OnInit } from '@angular/core'; import { FileUploader } from 'ng2-file-upload'; const URL = 'http://127.0.0.1:8000/api/v1/upload/'; @Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent implements OnInit { public uploader: FileUploader; constructor() { this.initUpload() } ngOnInit() { } initUpload() { this.uploader = new FileUploader({ url: URL, headers: [ {name: 'Access-Control-Allow-Credentials', value: 'true'}, {name:'Access-Control-Allow-Origin', value: '*'} ] }); } } -------------------------------------------- import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { FileUploadModule } from 'ng2-file-upload'; import { AppComponent } from './app.component'; import { UploadComponent } from './upload/upload.component'; … -
python call to boto3.client.create_data_source_from_s3
I'm trying to use AWS Machine Learning batch processes from a python project. I'm using boto3. I am getting this failure message in the response. There was an error trying to parse the schema: \'Can not deserialize instance of boolean out of START_ARRAY token\n at [Source: java.io.StringReader@60618eb4; line: 1, column: 2] (through reference chain: com.amazon.eml.dp.recordset.SchemaPojo["dataFileContainsHeader"])\ The .csv file I am using works. I know this because it worked through the console process. Here is my code; it is a function within a django model which holds the url to the file to be processed (input_file): def create_data_source_from_s3(self): attributes = [] attribute = { "fieldName": "Var1", "fieldType": "CATEGORICAL" } attributes.append(attribute) attribute = { "fieldName": "Var2", "fieldType": "CATEGORICAL" } attributes.append(attribute) attribute = { "fieldName": "Var3", "fieldType": "NUMERIC" } attributes.append(attribute) attribute = { "fieldName": "Var4", "fieldType": "CATEGORICAL" } attributes.append(attribute) attribute = { "fieldName": "Var5", "fieldType": "CATEGORICAL" } attributes.append(attribute) attribute = { "fieldName": "Var6", "fieldType": "CATEGORICAL" } attributes.append(attribute) dataSchema = {} dataSchema['version'] = '1.0' dataSchema['dataFormat'] = 'CSV' dataSchema['attributes'] = attributes dataSchema["targetFieldName"] = "Var6" dataSchema["dataFileContainsHeader"] = True, json_data = json.dumps(dataSchema) client = boto3.client('machinelearning', region_name=settings.region, aws_access_key_id=settings.aws_access_key_id, aws_secret_access_key=settings.aws_secret_access_key) #create a datasource return client.create_data_source_from_s3( DataSourceId=self.input_file.name, DataSourceName=self.input_file.name, DataSpec={ 'DataLocationS3': 's3://' + settings.AWS_S3_BUCKET_NAME + '/' + self.input_file.name, 'DataSchema': json_data, }, … -
Show response from ajax error function in django template
A part of the django view which is executed is as follows: def traxio_advice(request): ....... ....... elif calculation['statusCode'] == 400: response = JsonResponse({'message': 'The calculation is not available! Please try another mileage.'}, status=500) return response And in django template I have ajax call as follows : $.ajax({ type: 'POST', url: '{% url 'traxio_advice' %}', data: { firstname: $('input[name=firstname]').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { ...... }, error: function (data) { var message = $.parseJSON(data.responseText).message; $('#calculation-error').removeClass('hidden').html(message) }, beforeSend: function () { $('#result-content').html('<div class="loader"></div>'); } }) The problem is in the error function. I get what I want, thus, the data is correct. message = "The calculation is not available! Please try another mileage." But the message isn't showing in the div with the id calculation-error. Instead I see the loader from the beforeSend function on the screen and in the console I get POST http://127.0.0.1:8000/master/traxio_advice/ 500 (Internal Server Error) What am I missing? -
django user with email as pk - hack possible?
I read a lot about the topic, but didn't find anything that sounded as satisfactory as an idea of mine, and also don't see why it would raise problems. So if you can give it a look... I want to change user authentication in mid-project, i.e. avoid using a custom user model, since this requires to be done before the first migration. Can I just modify the email field to editable=False in the django.contrib.user.models and add a modified save(), so the email is updated from the username? Or the other way round? Pro And another distict general question: Would I do such things in the venv, or can I copy the whole auth-folder as a local app? -
Makemigrations causes TypeError: LoadLibrary() argument 1 must be string, not unicode
Im trying to run python manage.py makemigrations but this causes the following error (env) C:\Users\MattH\Coding\django\yokupark\yokupark>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\db\models\base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\db\models\base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\MattH\Coding\django\yokupark\env\lib\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 "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\db\utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\db\utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 5, in <module> from .features import DatabaseFeatures File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\gis\db\backends\postgis\features.py", line 1, in <module> from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\gis\db\backends\base\features.py", line 4, in <module> from django.contrib.gis.db.models import aggregates File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\gis\db\models\__init__.py", line 2, in <module> from django.contrib.gis.db.models.aggregates import * # NOQA File "C:\Users\MattH\Coding\django\yokupark\env\lib\site-packages\django\contrib\gis\db\models\aggregates.py", line 1, … -
How filter latest m2m objects with a QuerySet in Django
I have the following model: class Customer(object): licenses = models.ManyToManyField(License, related_name="licenses") class License(object): maintenances = models.ManyToManyField(Maintenance, related_name="maintenances") class Maintenance(object): start_date = DateTimeField(null=True) expiration_date = DateTimeField(null=True) Once a license maintenance is renewed, a new Maintenance object is created. This way I can track back to all Maintenance a particular License has had. Now I want to generate a report to show me all Customers which License are about to expire - based on their Maintenance expiry date. And I want only the latest Maintenance object a License has, because it is the latest sold. I don't want the others. I know I could achieve this with a QuerySet and a for loop, but that would be a bit costy to the server, given a have a lot of entries. Is there a way to do this filtering through a QuerySet? Customer.objects.filter(licenses__maintenances__expiry_date__last__lte=now().date()) I know I can use __last in some ocasions, but that doesn't quite work if I have to specify something after that. -
Media files not showing on Debug False
I've just deployed a site with pythonanywhere, when I set to DEBUG mode to False, my media images dissapear, the path of my media folder is not found. I was asking myself what causes this issue and how I can resolve it ? Here is how I configured my settings : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
how to define triggers in django?
I have a model Idea I want to trigger the date it's validated. how to tell django to automatically write validation date each time Field state is updated to validated value ? -
Update the user information only when it needed with python-social-auth
In my django web application I use python-social-auth. My settings.py file has 'social.pipeline.social_auth.associate_by_email', so user can login with different social networks without account duplication. Also in settings.py I use 'social.pipeline.user.user_details', so every time when user login with new social network information about user like first_name, last_name updates. Question: If it possible to update user details(first_name, last_name) using data from provider only if these fields are empty and dont update if these fields have information? -
Beautify django form html
The form.as_ul shortcut works completely fine but the html isn't formatted. The only solution I found was to include a middleware which beautifies the complete html but I only want to do that for the form part. Is there a other way than write my own form template? -
Show ajax error message in django template
The django view is as follows : def traxio_advice(request): if request.method == 'POST': connector = Adapter(Connector) selection = Selection(request).to_dict() calculation = connector.calculations(request.user, selection, request.POST) if 'statusCode' in calculation: # Calculation success if calculation['statusCode'] == 200: customer = '' if 'customer' in calculation: customer = calculation['customer'] price = price_incl_vat(calculation['calculation'].purchase_price) context = {"calculation_data": calculation['calculation'], 'customer': customer, 'price': price} return render(request, 'master/result-calculation.html', context) # Calculation limit reached ######### I go here, I het statusCode=403 ############ elif calculation['statusCode'] == 403: response = HttpResponse('Your have reached your limit. Please contact us.', status=403) response.status_code = 403 return response else: response = HttpResponse('Something went wrong. Please contact us.', status=400) response.status_code = 400 return response else: response = HttpResponse('Something went wrong. Please contact us.', status=400) response.status_code = 400 return response else: response = HttpResponse('Something went wrong. Please contact us.', status=400) response.status_code = 400 return response The ajax call in the django template is as follows : $.ajax({ type: 'POST', url: '{% url 'traxio_advice' %}', data: { mileage: mileage, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { $('#save-user-form').addClass("hidden"); calculationAvailable(mileage); $('#result-content').html(data); }, error: function (data) { console.log(data.responseText); debugger; $('#calculation-error').removeClass('hidden').html(data.responseText) } }) The problem is in my error function. If I get calculation['statusCode'] == 403 in the view then I …