Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to unit-test a decorator which uses environment variable?
I created a decorator to allow functions be be run in specific environments only: def accepted_environments(*envs): """ The decorated function can be executed only in specified envs """ def my_decorator(func_to_be_decorated): def wrapper(): if settings.ENV_NAME not in envs: raise EnvironmentException return func_to_be_decorated() return wrapper return my_decorator # Usage example @accepted_environments('local', 'prod') def hello(): print("hello") That seems to work, but I'd like to unit test it. The problem is: my tests are potentialy run in every environment (local, staging, prod). Plus, I think it's not safe my tests are able to change environment variables. Should I "mock" this behaviour? How would you do? Thanks! -
Django - how to safe form without validation?
I need to separate form saving feature from form confirming. I want to give user possibility to save form without validating its content firstly, but when form is finished, users should click confirm button which implies data validation and saves it to database. When I try to save it with commit=False parameter it raises error: The Table could not be created because the data didn't validate. -
postform.is_valid() False&True with widget attrs
I get confused when the following is_valid() False with resum widget notes: data-mini=true is a jquery mobile attribute. resume = models.FileField("resume(doc/pdf)", upload_to=upload_path) class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = [ 'name', 'mobile', 'resume' ] widgets = { 'name': TextInput(attrs={'data-mini': u"true"}), 'mobile': TextInput(attrs={'data-mini': u"true"}), 'resume': TextInput(attrs={'data-mini': 'true', 'type': 'file'}), } def post(self, request, pk, *args, **kwargs): question = get_object_or_404(Question, id=int(pk)) postform = ChoiceForm(request.POST, request.FILES) if postform.is_valid(): choice = postform.save(commit = False) choice.question = question choice.save() return HttpResponseRedirect(reverse("resume:submitok")) else: return render(request, self.template_name, { 'form': postform, 'question': question, }, But the following is_valid() True with resum widget class ChoiceForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ChoiceForm, self).__init__(*args, **kwargs) self.fields['resume'].widget.attrs['data-mini'] = "true" Anyone could help me explain the reason which caused form is_valid() result? Thanks! -
Add ModelForm Fields as Attribute to Object
I have a ModelForm for my Risk set up as: class RiskForm(forms.ModelForm): class Meta: model = Risk fields = '__all__' def __init__(self, *args, **kwargs): progid = kwargs.pop('progid') super(RiskForm, self).__init__(*args,**kwargs) dict_of_fields = {} all_char = Program.objects.get(id=progid).char_set.all() for char in all_char: c = [] for cat in char.cat_set.all(): c.append( (cat.label, cat.label) ) dict_of_fields[char.label] = c self.fields[char.label] = forms.ChoiceField(c) Where the Risk Object is defined as: class Risk(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE) label = models.CharField(max_length=200, default='') def __str__(self): return self.label However, I want to store the extra fields that I have created into my database under my Risk object. As I have it now, it only stores the two attributes 'program' and 'label'. However, I also want to store the answers to the characteristics into my database for later usage. For more information about how I've set things up: Django Form Based on Variable Attributes And a print screen of my ModelForm: https://gyazo.com/89c9833613dbcc7e8d27cc23a3abaf72 Is it possible to store all 6 answers under my Risk Object in my database? If so, how do I do that? -
CORS Header Error when using Authorization Header
So this is my current code When I delete the Authorization from the headers the request will be successful, and i get the response. But when I use the Authorization header, it will give me this error. The server is using Python Django and using this libary for CORS Handling -
ImportError at / cannot import name patterns with different Django Version
I am running to a weird error. I have only a single installed django version 1.7.11 and when I tested my website to see it is working I ended up having the error: ImportError at / cannot import name patterns. I am using 1.7.11 and patterns is supported of that version of Django but here is the weird thing, when I checked the django version on the site where it complained with the error it says: Django Version: 1.10 Python Version: 2.7.6 However, when I enter the python shell: Python 2.7.6 (default, Jun 22 2015, 17:58:13) >>> import django; django.VERSION (1, 7, 11, 'final', 0) and I only have a one version of Django installed. Why is this happening? I am using https://www.pythonanywhere.com to run the django app. Thanks a lot for the help in advance -
How to setup django migrations to be always the last one applied
I have django application and migration file 002_auto.py, which uses Django RunPython to alter database. I have no idea how much migrations files would be created in future, but I want the file 002_auto.py to be applied as the last part of migration process. How to set that migrations to be executed as the last one while performing django migrations without need to perform any manual steps each time I want to execute migrate command (or altering dependencies variable each time i've added new migrations)? p.s. I've looked into django migrations documentation and other articles without success. -
Apache client server authentication
I a using Apache Web server with a Django website, client-server certificate authentication. Apache configuration: <VirtualHost *:443> SSLEngine On SSLCertificateFile /etc/apache2/ssl/server.crt SSLCertificateKeyFile /etc/apache2/ssl/server.key SSLCACertificateFile /etc/apache2/ssl/ca.cer ServerAdmin webmaster@localhost <Directory /> SSLVerifyClient Require SSLVerifyDepth 10 SSLRenegBufferSize 10485760 SSLUserName SSL_CLIENT_S_DN_CN SSLOptions +StdEnvVars +ExportCertData Options FollowSymLinks AllowOverride None Require all granted </Directory> AliasMatch ^/([^/]*\.css) /home/user/projects/app/app/static/css/$1 Alias /static/ /home/user/projects/app/app/static/ <Directory /home/user/projects/app/app/static> Require all granted </Directory> Alias /static/admin "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/" <Directory "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/"> Require all granted Options FollowSymLinks AllowOverride None </Directory> WSGIDaemonProcess app_wsgiprocesses=1 threads=15 display-name=%{GROUP} WSGIScriptAlias / /home/user/projects/app/app/wsgi.py <Location /> WSGIProcessGroup app_wsgi </Location> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel debug </VirtualHost> I get the following error in apache error.log [Tue Oct 25 16:22:04.009502 2016] [ssl:info] [pid 52928:tid 139907737540352] [client 192.168.2.25:5136] AH01964: Connection to child 14 established (server appserver:443) [Tue Oct 25 16:22:04.017818 2016] [ssl:debug] [pid 52928:tid 139907737540352] ssl_engine_kernel.c(1844): [client 192.168.2.25:5136] AH02041: Protocol: TLSv1.2, Cipher: ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits) [Tue Oct 25 16:22:04.018664 2016] [ssl:debug] [pid 52928:tid 139907737540352] ssl_engine_kernel.c(222): [client 192.168.2.25:5136] AH02034: Initial (No.1) HTTPS request received for child 14 (server appserver:443) [Tue Oct 25 16:22:04.018914 2016] [ssl:debug] [pid 52928:tid 139907737540352] ssl_engine_kernel.c(570): [client 192.168.2.25:5136] AH02255: Changed client verification type will force renegotiation [Tue Oct 25 16:22:04.018941 2016] [ssl:info] [pid 52928:tid 139907737540352] [client 192.168.2.25:5136] AH02221: Requesting connection re-negotiation [Tue Oct 25 16:22:04.018960 2016] [ssl:debug] … -
Django ForeignKey field required despite blank=True and null=True
I am using Django REST Framework and I have a MyNodel with a related MyOtherModel in a many-to-one relationship: models.ForeignKey(MyModel, related_name="my_other_models", blank=True, null=True) Although blank=True, null=True, when I try to post a MyModel JSON without a my_other_models field I get a "this field is required" error. -
Getting Server response (400): Invalid classifier "Framework :: Django :: 1.10" from Pypi
I´m packaging a Django app, I ran: $ python setup.py sdist bdist_wheel After that I ran: $ python setup.py register -r pypitest I get the following error: ... writing manifest file 'acp_calendar.egg-info/SOURCES.txt' running check Registering acp-calendar to https://testpypi.python.org/pypi Server response (400): Invalid classifier "Framework :: Django :: 1.10" This are my classifiers on my setup.py classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.8', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Intended Audience :: Developers', ], -
django request.POST.getlist[my_list', None] returns [] for non-existant keys
I'm using Django 1.10.2. In a view, the below return [] print(request.POST.getlist('collected_already', None)) print(request.POST.getlist('collected_already[]', None)) print(request.POST.getlist('non_existent', None)) print(request.POST.getlist('non_existent[]', None)) I would expect None to be returned for the non_existent keys. I'd appreciate pointers. With best wishes, Andy. -
Django model __init__ not working with select_related?
in one project I've noticed redundant SQL queries in a view. It was caused by the following code: views.py from .models import Product def view_test(request): products = Product.objects.select_related('product_picture').all() products = list(products) return HttpResponse('OK') models.py from __future__ import unicode_literals from django.utils.translation import ugettext as _ from django.db import models class ProductImage(models.Model): name = models.CharField(max_length=200) class Product(models.Model): name = models.CharField(max_length=200) product_picture = models.ForeignKey('ProductImage', blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('Product image')) def __init__(self, *args, **kwargs): super(Product, self).__init__(*args, **kwargs) if self.product_picture is not None and self.product_picture.name != '': pass The problem is following: select_related in a view should take all data from ProductImage object, in particular its name in one query. However, the code in init (let's not dwell upon is it good code or not) is making another query to take ProductImage object name. I would like to understand what is happening here. Why there are two queries instead of one. -
Can't access model method into celery task
I have some issue with my Celery tasks. In my method I want to synchronize in background the soundcloud music library of the user @task(name="synchronize_library") def synchronize_library(user_id): from api.models import User logger.info("Enter in function") user = User.objects.get(pk=user_id) attr = getattr(user, "has_soundcloud_account") logger.info(callable(attr)) if user.has_soundcloud_account(): logger.info("User has account") # Do some stuff else: logger.info("User has not account") # Do some stuff When I call this method in a synchronous context like : synchronize_library(1) Everything works fine so there is no error in this method, but if I call : synchronize_library.delay(1) That's what I can see in the celery logger : [2016-10-25 10:02:44,078: INFO/MainProcess] Received task: synchronize_library[3e8e8a67-c896-4d3e-96fe-0959abed749d] [2016-10-25 10:02:44,081: INFO/Worker-1] synchronize_library[3e8e8a67-c896-4d3e-96fe-0959abed749d]: Enter in function [2016-10-25 10:02:44,744: INFO/Worker-1] synchronize_library[3e8e8a67-c896-4d3e-96fe-0959abed749d]: True So I have an object with a method "has_soundcloud_account" but the process seems to stop when I decide to call this function. After few tests this behavior appears everytime I try to call a method of my model. Is someone has an idea of what's going on ? -
django zinnia: customize the templates after extending the entry model
iam new to django, I followed the documentation of zinnia for extending the entry model with a gallery model, after many hours this works now, NOW my questions is how to display the gallery with the images in my template, how this will work? my app: zinnia_gallery models.py (in zinnia_gallery) from __future__ import unicode_literals # The model from django.db import models from django.utils.translation import ugettext_lazy as _ from zinnia.models.entry import Entry class EntryImage(models.Model): """Image Model""" entry = models.ForeignKey(Entry, verbose_name=_('entry')) image = models.ImageField(_('image'), upload_to='uploads/gallery') title = models.CharField(_('title'), max_length=250) description = models.TextField(_('description'), blank=True) def __unicode__(self): return self.title admin.py from django.contrib import admin from zinnia.admin import EntryAdmin from zinnia.models.entry import Entry from zinnia_gallery.models import EntryImage class EntryImageInline(admin.TabularInline): model = EntryImage class EntryAdminImage(EntryAdmin): inlines = (EntryImageInline,) admin.site.unregister(Entry) admin.site.register(Entry, EntryAdminImage) THANKS A LOT GUYS -
Django staff login to all urls
I want to define some specific urls starts with /staff/* to access only by staff. So only staffs can access the urls starts with /staff/* How can I define that in Django ? -
providing dynamic client ID and client secret for mobile users using django oath2 toolkit
I am working on android project. All my users install apps and provide phonenumbers to get client ID and client secret as part of registration process. And get access token to further use whole resources. I am using django restframework I have searched a lot in SO and google to find how to do it for mobile users. Django Oath2 toolkit provides documentation in which it shows minimal setup with templateview to manually provide details to get credentials for logged in user in browser. But I need to generate credentials dynamically for mobile users. I want to generate in views.py dynamically when user provide their phonenumber. How to do that? Any small example or hint? -
Cabot - 502 bad gateway error
Mine nginx.conf file worker_processes 1; error_log stderr notice; events { worker_connections 1024; } http { types_hash_max_size 2048; upstream cabot_app { server cabot:5000 max_fails=3 fail_timeout=3s; } server { listen 8088; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://cabot_app; } location /static/ { include /etc/nginx/mime.types; default_type application/octet-stream; root /code/; } } } and docker-compose yaml file redis: image: redis restart: always db: image: postgres restart: always ports: - "5432:5432" restart: always environment: POSTGRES_PASSWORD: test POSTGRES_USER: test POSTGRES_DB: tests cabot: build: . restart: always links: - redis:celerybroker - db - redis env_file: cabot_env ports: - "5000:5000" nginx: image: nginx ports: - "9999:8088" links: - cabot volumes_from: - cabot volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - ./cabot/static/:/code/static:ro Temporarily I am getting 502 bad gateway. its goes off when I reload the page. Nginx logs files gives: /code/static/CACHE/css/base.36481a0991d5.css" failed (2: No such file or directory) -
Django Rest Framework OneToOneField related BooleanFilter
I'm using django with rest-framework. Now I have models with OneToOne relations: class ModelA(models.Model): pass class ModelB(models.Model): a = models.OneToOneField( A, related_name='b') And I have a ViewSet applied on A: class ModelAViewSet(viewsets.ModelViewSet): queryset = ModelA.objects.all() serializer_class = ModelASerializer Then, I want to add a BooleanFilter on ModelAViewSet to filter whether the ModelA object has a relating ModelB object. And I tried the below: class ModelAViewSet(viewsets.ModelViewSet): class Filter(FilterSet): has_b = filters.BooleanFilter('b') queryset = ModelA.objects.all() serializer_class = ModelASerializer filter_fields = ['has_b'] So, if it works, we got: ?has_b=1: returning all records without filtering; ?has_b=2: returning records which have relating ModelA object; ?has_b=3: returning records which NO NOT have relating ModelA object; It almost worked, except the case 3 above. So what's the correct way to do this? -
Saving dynamic formset with more than one form
I've built dynamic forms using django formsets and javascript, but unfortunately on submitting the form only the first form is submitted. I'd like all dynamically added forms to be submitted also. Any help would be appreciated. Views: def routestepinfo(request): class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False RouteStepFormSet = formset_factory(RouteStepForm, formset=RequiredFormSet, extra=1, can_order=False, can_delete=True) if request.method == 'POST': formset = RouteStepFormSet(request.POST) if formset.is_valid(): for form in formset.forms: form.save() print 'apple' return redirect("/buildpage/") else: formset = RouteStepFormSet() return render(request, "buildpage/routestepinfo.html", {'formset' :formset}) HTML <form id= "myForm" method = 'POST' action="{% url 'buildpage:routestepinfo' %}" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} <div id="form_set"> {% for form in formset %} <table class='no_error'> <tbody>. {{form.as_table}} </tbody> </table> {% endfor %} </div> <p><input type = "button" value = "Add another step" id = "add_more" ></p> <div id="empty_form" style="display:none"> <table class='no_error'> {{ formset.empty_form.as_table }} </table> </div> <div id="forms"></div> <p>&nbsp;</p> <p>&nbsp;</p> <input type = "submit" name = "Submit Steps"> </form> JS Clone: <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> -
upload and resize image in django without using modelForm
I have to resize an image and upload it to server using django, currently i am using fileSystem storage for uploading file, but and my code is def create_new_event(request, steps=None): if request.method == 'POST': stepFirstForm = CreateEventStepFirstForm(request.POST, request.FILES) if stepFirstForm.is_valid(): if request.FILES['artist_image']: randomArtistImage = ''.join(random.choice('0123456789ABCDEFabcdefghijklmn') for i in range(8)); myfile = request.FILES['artist_image'] fs = FileSystemStorage() fileName, fileExtension = os.path.splitext(myfile.name) artistImageName = randomArtistImage+'-'+str(request.user.id)+str(fileExtension) filename = fs.save('event_artists_images/'+artistImageName, myfile) uploaded_artist_image_url = fs.url(filename) Using this code i can move image to event_artists_images folder, but i want to also resize this image upto 300*300 pixels. How can i do this. If i can use PIL Image class then on server how can i upload and resize file. -
TemplateDoesNotExist: mainpage.html in Django calendar
I'm new to Django. I want to display a calendar with monthly view. The local host server runs fine but, I am getting an error that TemplateDoesNotExist at mainpage.html. I have cloned the project from https://github.com/morenopc/django-calendar-app repository. I think the error is in this line in mainpage line 38 {'form': AddEventForm, 'editform': editform, 'calendars': calendars, 'calendar': calendar, 'selection': selection}, context) Kindly guide me through this. Any answers and suggestions are welcomed. -
Can foreign keys be used in get() Django
I have been trying to retrieve a record with get(). I'm getting matching query does not exist error. Below is my code. for id in range(selected_revIds): update_instance = SiverifyProblemStatement.objects.get(site_revision_id=id) problem_stmt = update_instance.revision_problem_statements.update(main_concern=concern, risk_estimate=estimate_code, rev_title=title, problem_statement=description) site_revision_id is a foreign key in the table SiverifyProblemStatement. I suspect this is the reason for the error. Any solutions to clear this? Thanks. -
Django: access the model meta class value
I have some model classes defined: class ModelA(models.Model): class Meta: abstract = True class ModelB(ModelA): class Meta: abstract = False So, now I have a class object, I want to check if it is abstract, is there any way to do this? For example, I want something like: >>> ModelA.abstract True >>> ModelB.abstract False -
Python/Django - Expected a string or bytes-like object
I've looked around, and I've seen a couple of solutions that I thought would work for my own code, but seemed to do nothing. I am trying to pull data from a JSON file and add the information to arrays. The arrays will then be used to input data into several objects that I add to the database (I know, this is terribly inefficient, but the way I wrote the original script, I didn't have to add objects to a database. I am planning on changing that). Object contains a date time associated with it. I used Python's strptime function to convert the strings into datetime objects. In my models.py, I have a DateTimeField for the datetime. When I try and migrate, however, I get the following error: TypeError: expected string or bytes-like object Here is the entire traceback: Applying interactive_table.0016_auto_20161024_2259...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/andrewho/anaconda/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, … -
List of all items from queryset with BeautifulSoup
I have Django project with field, with contents (from QuerySet): <p><b>Name and LastName</b><br /> Work Title<br /><span class="text-spacer"></span> </p> <p><b>Name and LastName 1</b><br /> Work Title1 <br /><span class="text-spacer"></span> </p> <p><b>Name and LastName 2</b><br /> Work Title 2<br /><span class="text-spacer"></span> </p> But I want to have text in this format, with (-): Name and LastName - Work Title Name and LastName 2 - Work Title 2 Name and LastName 3 - Work Title 3 Here is my code, but I get only first item, but I want to have array with items: text_list = self.texts.filter(code='ON') for i in text_list: soup = BeautifulSoup(i.text_en, "html.parser") aa = soup.p.get_text(separator=" - ", strip=True) return [aa]