Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check for a value if it exists in another application - django
I have two applications in my django project, where I need to check and do some operations depending on whether a value exists in another application. I'm not sure how django does this. Any inputs or any links to django docs I can refer? Thanks. Note: I do not want to get the value and use in my application. I just wanted if the value exists in another application. -
Select from PostgreSQL table without using Django ORM
I have a Django project that is hosted in Heroku. I created a table using the directly in the database without using the Django ORM. How can I do a select of this table?? -
How do I tell django-admin which settings module to use?
When I run django-admin with --settings switch, it fails: (env) $ django-admin help --settings=myapp.settings Traceback (most recent call last): File "/srv/http/myapp/env/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/srv/http/myapp/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/srv/http/myapp/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/srv/http/myapp/env/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/srv/http/myapp/env/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/srv/http/myapp/env/lib/python3.5/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'myapp' (env) $ ls myapp/settings.py myapp/settings.py But manage.py works just fine. To make it clear, I'd like to have additional settings.py for development environment. -
Django - Selecting a subset of database entries via checkbox form
I have a database with 100 entries, model structured as: # models.py class AssayPlate(models.Model): filename = models.CharField(max_length=1000) assay_plate = models.CharField(max_length=10) file_date = models.CharField(max_length=25) chromatic = models.CharField(max_length=4) plate_format = models.IntegerField('plate_format') def get_absolute_url(self): return reverse('rttrace:detail', kwargs={'pk': self.pk}) def __str__(self): return self.assay_plate + ' --- ' + self.file_date + ' --- ' + self.chromatic I would like to allow the user to select (via checkboxes) the entries they would like, and display the filename of each selection on the next page. # views.py class IndexView(generic.ListView): template_name = 'rttrace/index.html' AssayPlate.objects.all().delete() for file in filelist: assayplate_model_fill(file, 1536) context_object_name = 'all_assayplates' def get_queryset(self): return AssayPlate.objects.all() def trace(request): selected_plates_ids = request.GET.getlist('plates') context = { 'selected_plates': selected_plates } return render(request, 'rttrace/detail.html', context) And the html is as follows: # index.html <form method="GET" action="{% url 'rttrace:trace' %}"> {% csrf_token %} {% for plate in all_assayplates %} <input type="checkbox" id="plate{{ forloop.counter }}" name="plates" value="{{ plate.filename }}"> <label for="plate{{ forloop.counter }}"> {{ plate.assay_plate }} - {{ plate.file_date }} - {{ plate.chromatic }} </label><br> {% endfor %} <input type="submit" value="Generate Trace Template"> </form> # trace.html {% for plate in selected_plates %} {{ plate.filename }} <br> {% endfor %} Here, I am just printing the filename. For bonus points - a question of … -
Django-Rest-Framework browsable API not showing 'editable=False' fields within the POST box
I would like to be able to instantiate my 'Job' entities via the browsable API (of django-rest-framework), however my employer field has the field 'editable=False'. Therefore the employer entry box does not appear. This is what I see when editable=False (code further below): (Image) POST form without employer entry box This is what I see when I remove editable=False (code further below): (Image) POST form with employer entry box How can I get employer box to show whilst not allowing the employer field not to be changed after it is first set? (So that it will look like the second image) models.py from django.db import models from users.models import Proof_User class Job(models.Model): title = models.CharField(max_length=254, blank=False, null=False) description = models.TextField(blank=True) employer = models.ForeignKey(Proof_User, editable=False, related_name='jobs', blank=False, null=False) serializers.py class Job_Serializer(serializers.ModelSerializer): class Meta: model = Job fields = ('id', 'title', 'description', 'employer',) views.py class Job_Viewset(viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = Job_Serializer -
index.fcgi renders as text on CENTOS 6.8 - django website
I have a dedicated server with WHM, and I need to migrate a Python website to a user inside that server. I am not familiar with python so I started looking for an index.php or index.html file but could not find any. After investigation, I tried to execute the file manage.py, it was giving several errors and found that django was not installed, so after completing the install, the manage py file shows now some text with python commands and does not give any errors, you can visit it at http://mgtransportes.com.co/cgi-bin/manage.py I have been reading that in order to show the website, I need to create a file called index.cfgi, and I did, but when opening the URL from the browser I get plain text, you can visit the naked domain (I cannot add more links due to my current reputation) I am not sure how to enable FastCGI from WHM, and I do not even know if this is going to work, I have followed different tutorials, and looks like python is correctly installed, I have a test file on /cgi-bin/test.py and I prints a message as intended. I am not sure how to execute the python script and … -
How do I access a list in side a dictionary, inside a 'defaultdict(<class 'list'>) inside another dictionary, in a django template?' [duplicate]
This question already has an answer here: My defaultdict(list) won't show up on template but does in my view [duplicate] 1 answer Here is the expanded context being passed from my view. {'context': defaultdict(<class 'list'>, {1: [<Course: Title: 2x3 Study Time, Location: Some room>, <Course: Title: 2x3 Science Time, Location: Some room>, <Course: Title: 2x3 Math Time, Location: Some room>], 2: [<Course: Title: 2x3 Knitting, Location: Some room>, <Course: Title: 2x3 Computers, Location: Some room>, <Course: Title: 2x3 Having Fun, Location: Some room>]}), Here is my most recent (failed) attempt in a template. {% for k0 , v0 in context.items %} {{ k0 }}{{ v0}} {% endfor %} Note: Noting is being displayed. For more context. Here is the current model (note some fields are char/text fields while testing) class Course(models.Model): title = models.CharField(max_length=200) limit = models.IntegerField(default=10) description = models.TextField(max_length=800) location = models.CharField(max_length=200, default="") teachers = models.TextField(max_length=800, default="") grades = models.ManyToManyField("Grade", related_name="grade_range") days = models.ManyToManyField("Day", related_name='day_range') class_time = models.ManyToManyField("startEndTime", related_name="time_range") Here is my view. def select_classes(request): if request.method == 'POST': form = GradeForm(request.POST) if form.is_valid(): classesBySelectedGrade = Course.objects.filter(grades__grade__contains=form['grade'].value()).order_by( 'class_time__startTime').all() optionCount = classesBySelectedGrade.count() c = defaultdict(list) for i in classesBySelectedGrade.all(): c[hash(i.class_time.all()[0].id)].append(i) return render(request, 'select-classes.html', {'context': c, 'size': optionCount}) The idea behind … -
Is DEBUG == False supposed to mean that the app is running in production environment?
At least, that's what I see occasionally on the internet. But what do I put in settings.py then? Okay, I can put local settings to, say, settings_local.py and import it from settings.py. But if some settings depend on environment, than I've got to put them after import statement. There more I think about it, the more I don't like it. And you? -
Error while reading image using cv2.imread() in Django views.py
I am trying to apply image processing on an image which i'm loading through cv2.imread() in Django's views.py file, but i'm getting an AttributeError everytime. The image file exists in the directory, following is the heirarchy views.py through which i'm trying to read temp321.jpg : def process_image(request): url = "static/images/temp321.jpg" a = cv2.imread(url) r, c = a.shape Error which i'm getting: What am i doing wrong? -
Target WSGI script '/home/ubuntu/webapps/webapps/wsgi.py' cannot be loaded as Python module
I am in python 2.7, django 1.10, apache2 to have django project deployed on aws ec2 ubuntu. In /etc/apache2/apache2.conf I have this: WSGIScriptAlias / /home/ubuntu/webapps/webapps/wsgi.py WSGIPythonPath /home/ubuntu/webapps Require all granted AllowOverride None Require all granted Options Indexes FollowSymLinks AllowOverride None Require all granted In webapps/webapps/wsgi.py, I have this: import os, sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapps.settings") application = get_wsgi_application() ~ When I restart apache2 and it always got 500 error, I check on the error.log it always shows: Wed Nov 09 21:35:32.261257 2016] [wsgi:error] [pid 2888:tid 139941118269184] [client 67.171.70.190:62684] mod_wsgi (pid=2888): Target WSGI script '/home/ubuntu/webapps/webapps/wsgi.py' cannot be loaded as Python module. [Wed Nov 09 21:35:32.262444 2016] [wsgi:error] [pid 2888:tid 139941118269184] [client 67.171.70.190:62684] mod_wsgi (pid=2888): Exception occurred processing WSGI script '/home/ubuntu/webapps/webapps/wsgi.py'. [Wed Nov 09 21:35:32.262481 2016] [wsgi:error] [pid 2888:tid 139941118269184] [client 67.171.70.190:62684] Traceback (most recent call last): [Wed Nov 09 21:35:32.262508 2016] [wsgi:error] [pid 2888:tid 139941118269184] [client 67.171.70.190:62684] File "/home/ubuntu/webapps/webapps/wsgi.py", line 12, in [Wed Nov 09 21:35:32.262579 2016] [wsgi:error] [pid 2888:tid 139941118269184] [client 67.171.70.190:62684] from django.core.wsgi import get_wsgi_application [Wed Nov 09 21:35:32.262594 2016] [wsgi:error] [pid 2888:tid 139941118269184] [client 67.171.70.190:62684] ImportError: No module named django.core.wsgi I think I follow the django document and don't know why. Could someone help me? -
Django lock rows for atomic insertions
We are using Django 1.3. Our models are: class Info(models.Model): class Meta: ordering = ('-ts','snp_number',) ts = models.DateTimeField(auto_now_add = True) description = models.TextField() release = models.CharField(max_length=50) stream = models.CharField(max_length=100) class Snap(models.Model): class Meta: ordering = ('-snp',) unique_together = ('snp','app_name') snp = models.ForeignKey(SnapInfo) app_name = models.CharField(max_length=255) parent_app_name = models.CharField(max_length=255) class Env(models.Model): class Meta: ordering = ('-snp',) snp = models.ForeignKey(Snap) env = models.CharField(max_length=50) class Connection(models.Model): class Meta: ordering = ('-snp',) snp = models.ForeignKey(Snap) app_name = models.CharField(max_length=255) For a given Info we can have multiple Snaps. For a given Snap we can have multiple Connection and Env. The Write Somewhere in our app, we have the creation of the snaps at @transaction.commit_on_success def create_snap_controller (topo_id=None, release=None, type=PREP, is_live=False): try: snp_info = Info.get_or_create_snap(release_name, type) except Exception as e: log.error("%s - Error creating snap Info for the release %s and type %s " %(str(e), release_name, type)) ... return create_snap(snp_info, app_name, parent_name) def create_snap(info, app_name, parent_name): ... snp = Snap.objects.create(snp=info, app_name=app_name, parent_app_name=parent_name) for conn in connections: conn = Connection.objects.create(snp=snp, app_name=conn) for env in envs: create_env(snp, env) ... return snp def create_env(snp, env): .... e = Env.objects.create(snp=snp, env=env) The Read There is also an API which reads these latest Snap and given app_name and returns JSON of … -
Django: if url not end with slash, POST works like GET
urls.py url(r'^v1/files/$', MyFileView.as_view(), name='api-upload'), url(r'^v1/files/$', MyFileView.as_view(), name='api-view-all'), views.py class MyFileView(APIView): def post(): pass def get(): pass My question is: why POST api/v1/files works like GET api/v1/files/? Thanks -
Playing next and previous song in django based music player
I am making a music player in django. I have added common features like play, pause etc. I wish to add prev() and next() functions in it which will play the next song/previous song from current song. Since the songs are stored in django database and I have to write these functions in javascript, I am not getting any idea how to link them. The songs are passed form a django view to a template. On clicking a song, the songs starts playing in the player. I would also like play the next song when the current song ends. views.py: from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from models import Song def home(request): song = Song.objects.all() context = {"song":song[0]} return render(request,'music/base.html',context) def listallsongs(request): songs = Song.objects.all() context = {"songs":songs} return render(request,'music/allsongs.html',context) base.html: {% load staticfiles %} <html> <head> <link rel="stylesheet" href="{% static 'home.css' %}" type="text/css"> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="{% static 'home.js' %}"></script> </head> <body> <div id = "musicplayer"> <div id = "details"> <p id = "title">{{ song.song_title }}</p> </div> <div id = "buttons"> <progress id="seekbar" value="0" max="1"></progress> <div id = "menu"> <audio src="{{ song.file.url }}" id="player"></audio> <button id = "prev" onclick = "prev()">PREV</button> <button … -
django admin group by
i have a Django model of payments this payments has a date,a value, then I need show in the django admin a query of total sales group by for date I make a function to return a dict with dates a total sales payments.objects.extra(select={'day': 'date( date )'}).values('day').annotate(available=Sum('value')) but I need show this group by from django admin, but When I put this fuction in the django admin not show this query group by for date -
loop in json after using JSON.Parser
I'm Using Rest framework to get JSON data and parse them. now I don't know how to access the second argument of json data, for parse the json I've seen this link. code in views: @api_view(['POST']) @parser_classes((JSONParser,)) def product_list(request): """ List all products which name of them is in the json data """ if request.method == 'POST': print(request.data) MarketProduct=[] for item in request.data: print(item) try: product=Market.objects.get(name=item) MarketProduct.append(product) except Market.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = MarketSerializer(MarketProduct, many=True) return Response(serializer.data) code in urls: urlpatterns = [ url(r'^listproducts/$', views.product_list), ] here in this line: for item in request.data: the item only has the first argument of each json. the json which I've sent is : {'hello': '1', 'bye': '2'} in printing items , only "hello" and "bye" prints.but i want to access "1" and "2" too. It's important for me to use Django framework. and I can't get the appropriate way to use json.load(raw) in this situation -
Django form with dynamic (user-selected) field quantity
My goal is to have a form containing an arbitrary number of records, each containing 3 values. The user should be able to add as many of these records as they need within a single form. For example, see the wireframe in this question. I'd need it to be backed by something that I can parse back into the DOM if the user wants to edit the data, so a Postgres JSONField may be a good fit. I know how this could be achieved from scratch, but does Django support this out-of-the-box? Or is there any existing library which would solve this faster? -
Installing Django in a Virtualenv means that i have to re-install it everytime I make another project?
Sorry if this is an obvios or dump question but the thing is that i've been having problems with the installation of Djandgo, and the virtualenvs. I'm a windows 10 user and I've following a series of tutorials of Django in wich they create a virtualenv an inside of it, using pip, they proceed with the installation of the framework. The problem is that, I drop the old project or virtualenv wich had Django installed and started a new one, a new virtualenv (creating a new folder and typing virtualenv .), and reinstalled django on it but now, when i go throught the cmd to the directory J:\project2\Scripts\django-admin.py I receive and error: Traceback (most recent call last): File "J:\project2\Scripts\django-admin.py", line 2, in from django.core import management ImportError: No module named django.core is it because I re-installed again Django in another new virtualenv? Thanks to all :) -
HEAD method not allowed after upgrading to django-rest-framework 3.5.3
We are upgrading django-rest-framework from 3.1.3 to 3.5.3. After the upgrade all of our ModelViewSet and viewsets.GenericViewSet views that utilize DefaultRouter to generate the urls no longer allow HEAD method calls. I've searched through the release notes and docs and haven't been able to find any setting or change that caused HEAD to stop being allowed. I'm able to resolve this issue by subclassing the DefaultRouter and altering the route defaults, but I don't think this is the best or correct solution. From reading within django-rest-framework issues and documentation, it appears that django-rest-framework should handle HEAD and OPTIONS methods automatically. @detail_route, @list_route, and views derived from ApiView which allow the GET method are automatically gaining the HEAD and OPTION methods. Why has the HEAD method disappeared after this upgrade and what is the correct method of ensuring HEAD methods are allowed on our routes? -
Missing leading slash on images uploaded with Django Filebrowser
I'm having an issue with Django-Filebrowser when I try to upload an image. I'm using the following versions: Django 1.8.7, Filebrowser 3.6.4 and Python 2.7. When I try to upload an image, everything works as expected, and the uploaded files are placed in the right folder without any problem; but the resultant file url doesn't have any leading slash necessary to serve properly the file. For example, if I try to upload "test.jpg", the final image url will be "uploads/test.jpg" and "_versions/test_xxx.jpg" that actually creates issues even in the Filebrowser panel, since the resulting request will be issued to http://localhost:8000/admin/filebrowser/browse/uploads/test.jpg and http://localhost:8000/admin/filebrowser/browse/_versions/test.jpg rather than http://localhost:8000/uploads/test.jpg and http://localhost:8000/_versions/test.jpg that the server would serve properly. (Note that the Filebrowser panel url is http://localhost:8000/admin/filebrowser/) Here's my settings: urls.py: urlpatterns = [ url(r'^admin/filebrowser/', include(site.urls)), url(r'^admin/', include(admin.site.urls)), url(r'^', include('pages.urls')), url(r'^blog/', include('articles.urls')), url(r'^tinymce/', include('tinymce.urls')), url(r'^grappelli/', include('grappelli.urls')), ] settings.py FILEBROWSER_DIRECTORY = 'uploads/' FILEBROWSER_VERSIONS_BASEDIR = '_versions/' Add a leading slash to the FILEBROWSER_DIRECTORY would trigger a SouspiciusFileOperation error since '/uploads/' is located outside the project folder. Thanks in advance. -
django: how to include inline formset for a foreign key in a model form
For example, I have the following models: class Project(models.Model): description = models.CharField(max_length = 200, null=True) login_date = models.DateField(null=True) login_by = models.CharField(max_length = 200, null=True) notes= models.CharField(max_length = 200, null=True) class Sample(models.Model): sample = models.ForeignKey(Project, on_delete = models.CASCADE, null=True) serial_number = models.CharField(max_length = 200, null=True) location = models.CharField(max_length = 200) I am wondering how could I make a model form of Project that not only have field of its own, but also a inline formset of Sample, where multiple samples could be added/deleted within the model form, just like what we have in admin site. -
NoReverseMatch at /blog/create/
I am getting this error NoReverseMatch at /blog/create/, can anyone help me? Thank you. views.py @login_required(login_url='account_login') def create_post(request): if request.method == 'POST': post_form = CreatePostForm(request.POST) if post_form.is_valid(): new_post = post_form.save(commit=False) new_post.author = request.user new_post.slug = slugify(new_post.title) new_post.save() messages.success(request, 'Post creates successfully') # redirect to new created item detail view return redirect(new_post.get_absolute_url()) else: post_form = CreatePostForm() return render(request, 'blog/post/detail.html', {'post_form': post_form}) def post_detail(request, id, slug): post = get_object_or_404(Post, id=id, slug=slug) return render(request, 'blog/post/detail.html', {'section': 'blogs', 'post': post}) models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager published = PublishedManager() # Our custom manager tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blogs:post_detail', args=[self.id, self.slug]) urls.py for the app: urlpatterns = [ # post views url(r'^$', views.post_list, name='post_list'), url(r'^create/$', views.create_post, name='post_detail'), url(r'^detail/(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.post_detail, name='detail'), ] main urls.py urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blogs', app_name='blog')), ] when i try to create a new post i get that error. I want to display the post thats created. Here … -
Django ajax-selects package is not working. What I am missing?
I am trying to use Django ajax-selects package I have my form.py : from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField from ajax_select import make_ajax_field class LeaseTenantForm(forms.ModelForm): class Meta: model = LeaseTenant exclude = [] tenant = make_ajax_field(LeaseTenant,'tenant','tenant',help_text="Search for label by name") #tenant = AutoCompleteSelectField('tenant', required=False, help_text=None) I have my lookup.py: from ajax_select import register, LookupChannel from client.models import Tenant @register('tenant') class TenantLookup(LookupChannel): model = Tenant def get_query(self, q, request): return self.model.objects.filter(name=q) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.name I have my tenant model.py: class Tenant(CommonInfo): version = IntegerVersionField( ) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=30) language = models.CharField(max_length=1, default='E', choices=LANGUAGE_CHOICES) external_address = models.CharField(max_length=90,null=True, blank=True) external_zip_code = models.CharField(max_length=50,null=True, blank=True) external_city = models.CharField(max_length=60,null=True, blank=True) external_state_province = models.CharField(max_length=30,null=True, blank=True) external_country = models.CharField(max_length=30,null=True, blank=True) status = models.CharField(max_length=1, default='N', choices=TENANT_STATUS_CHOICES,null=True, blank=True) def __unicode__(self): return u'%s %i %s %s %s %s %s %s' % ("#", self.id,"first_name", self.first_name, "last_name", self.last_name, "phone", self.phone ) But in my form I am not getting no autocomplete and no field create. What have I missed? -
Django: 'no such table' after extending the User model using OneToOneField
(Django 1.10.) I'm trying to follow this advice on extending the user model using OneToOneField. In my app 'polls' (yes, I'm extending the app made in the 'official' tutorial) I want to store two additional pieces of information about each user, namely, a string of characters and a number. In my models.py I now have the following: from django.contrib.auth.models import User class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stopien = models.CharField(max_length=100) pensum = models.IntegerField() and in admin.py the following: from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from polls.models import Employee class EmployeeInline(admin.StackedInline): model = Employee can_delete = False verbose_name_plural = 'employee' class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) When adding a user using the admin panel my two new fields display correctly. However, when I click 'save', or if I don't add any user and just click on the name of my sole admin user in the admin panel, I get the following error: OperationalError at /admin/auth/user/1/change/ no such table: polls_employee I see some questions and answers related to similar problems, but they seem to be relevant for older version of Django. Could anyone give me a tip as to what I should do? Ideally I'd … -
Django - How can I get a child type object from a parent class object using MTI?
I have a function, get_priority(), which sorts through all objects in a parent class (Chunk) to get the highest 'priority' object. Now I want to get the related subclass object to the superclass object. The Django docs on Multi-Table Inheritance show that I can do this by using the lowercase name of the subclass. For example, if the subclass was Concept I could do the following: chunk = get_priority(Chunk.objects.all()) chunk.concept However, the subclass could be Concept, Code, Formula or Problem. Is the only way to approach this to use try/except for each subclass, e.g.: chunk = get_priority(Chunk.objects.all()) try chunk.concept: object = chunk.concept except Exception: pass try chunk.code: object = chunk.code except Exception: pass # etc. -
Django Clickjacking Protection resp.get('X-Frame-Options') NoneType
Problem: User must not view a logon page if already authenticated with our single sign on provider. Solution: An iframe and javascript display a loading gif until after the iframe has returned a response from the single sign on provider. If the SSO provider response is that the user is currently logged in, Django authenticates the user server side, and javascript redirects the user into the web app. If the SSO provider response is that the user is NOT logged in, javascript replaces the loading gif with the logon form. Using Django==1.9.9, Python 2: Our get call is decorated with @xframe_options_sameorigin, but recently starting returning this error sometimes: 2016-09-25 16:38:27,598 | django.request | ERROR | Internal Server Error: /accounts/open-id-finish/ Traceback (most recent call last): File "/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/virtualenv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/opt/virtualenv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/opt/virtualenv/local/lib/python2.7/site-packages/django/views/decorators/clickjacking.py", line 40, in wrapped_view if resp.get('X-Frame-Options') is None: AttributeError: 'NoneType' object has no attribute 'get' Where is this error coming from? Was there a change in @xframe_options_sameorigin in Django 1.9? How is it …