Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'Query' object has no attribute 'aggregate_select'
I am writing a small script in Django. It is based on the Command class for execution by cron. I am using pyodbc with MS-SQL. class Command(BaseCommand): help = 'Sends email notifications' def handle(self, *args, **options): all_open_port = MyEmailModel.objects.using('emaildb').filter(u_sentinstant__gte=datetime.date.today()) for p in all_open_port: self.stdout.write(p.u_sentinstant) self.stdout.write(self.style.SUCCESS('Successfully finished.')) I alwas get this error, when the QuerySet is evaluated: AttributeError: 'Query' object has no attribute 'aggregate_select' I am unable to solve this as the code is identical to the docs... -
solving django 1.10 integrity error
i created two models Category and Song. i linked song to category using foriegn key and then i linked song to user using foreignkey. i then created created a form to add song to the database , but anytime i use the form i get this error "Integrity Error NOT NULL constraint failed: home_song.user_id (home is the name of the app)" please how do i solve this error. my models: class Category(models.Model): category_name = models.CharField(max_length= 100) class Song(models.Model): category = models.ForeignKey(Category, on_delete= models.CASCADE) user = models.ForeignKey(User) song_name = models.CharField(max_length = 100) -
Django message recipient url
so i have django-messages installed on my website: https://github.com/arneb/django-messages and it states in the docs "Messages can be composed and there is an easy, url-based approach to preloading the compose-form with the recipient-user, which makes it extremly easy to put "send xyz a message" links on a profile-page." and I've found the url being , ^messages/ ^compose/(?P<recipient>[\w.@+-]+)/$ [name='messages_compose_to'] however the docs give no information on how to implement this, i would like to be able to add send user a message on the profile page of each user however being so new to django i dont really unserdtand how to implement this. Could someone please guide me in the right direction? i would really appreciate any help. Thank you, and sorry for being such a noob. Callum -
Dynamically create buttons or send data to buttons
I am dynamically trying to pass data that I get from my for loop to the buttons. I am using django to get the data in the for loop, html to make the button and jquery to pass the data. I am not sure if this is the best description though. My code is: {% for dogs in Dogs.Other %} <form id="primaryDogForm" action="{% url 'personal:account:email_dog_confirm' %}" method="post"> {% csrf_token %} <input type="hidden" id="dogId" name="dogId" value="{{ dogs }}"> <input type="button" value="Make this your primary dog" id="makePrimaryButton" class="btn btn-primary" data-toggle="modal" data-target="#makePrimary" /> </form> {% endfor %} Basically, people can add a list of dogs to their account and select a dog to be their primary dog. I want a modal to be called when I click on the button. And that modal should display the name of the dog that is potentially being made the primary dog. The modal code is as follows: <div class="modal fade" id="makePrimary" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Make Primary</h4> </div> <div class="modal-body"> <p> You are about to make <span id="newDog" name="newDog"></span> your primary dog. </p> <hr> <a href="#" id="makePrimarySubmit" class="btn btn-primary">Submit</a> </div> </div> … -
Django + Dropzone - I can't display files
I'm creating Django application with gallery. That gallery have albums and photos. Photos have foreign key to album. In template I'm sending files and album id (only one person can add something to gallery, so I don't have to worry about that as a security hole). I'm sending these files with dropzone's javascript. Then in view I use such code to save photos: if 'addphotos' in request.POST: if ('Album' in request.POST): ualbum = Album.objects.get(id=request.POST['Album']) print(ualbum.title)#just checking, this part works files = [request.FILES.get('dzfile[%d]' % i) for i in range(0, len(request.FILES))] for ufile in files: p = Photo.objects.create(album=ualbum, file=ufile) And something is not working there with files. Photo object is created but file is not attached to it. In ./manage.py shell I did something like this: >>> from main.models import Photo >>> from main.models import Album >>> album = Album.objects.get(id=8) >>> print (album.title) teraz zadziała >>> photos = Photo.objects.filter(album=album) >>> print(photos) <QuerySet [<Photo: Photo object>, <Photo: Photo object>, <Photo: Photo object>]> >>> for photo in photos: ... print(photo.album.title) ... teraz zadziała teraz zadziała teraz zadziała >>> for photo in photos: ... print(photo.file.url) ... Traceback (most recent call last): File "<console>", line 2, in <module> File "/home/zeko/Pulpit/grh/stronka/s/lib64/python3.4/site-packages/django/db/models/fields/files.py", line 70, in url self._require_file() File … -
access args in render function in django
I'm using Django and can't access the argument (args) which I pass with my render method. I get the error: TemplateSyntaxError at /app/. Could not parse the remainder: '['messages']' from 'args['messages']' Views: def index(request): messages = ["This is message1", "This is message2"] args = {'messages': messages} return render(request, 'app/index.html', args) Index html file: {% for message in args['messages'] %} <div class="live_message"> <p>{{ message }}</p> </div> {% endfor %} What is going wrong and how do I fix it? -
Djangocms users don't have permission to add or edit plugins
I have a website, currently running with Django==1.8.6 and Django-CMS 3.0.x (running through upgrades at the moment). My users can not edit any of the frontend plugins. At the moment I am sure that this is not only true for my custom made plugins, but for ones that come with Django-CMS as well. As a test I have made a new User with all rights and staff status (no superuser). But also this user can't edit or add plugins. For my search I have found this: https://github.com/divio/djangocms-text-ckeditor/issues/78 I also tested the solution given there as I am using ckeditor, but I don't have an entry for text, so this: sqlite3> select * from django_content_type where app_label = 'text'; id | name | app_label | model ----+------+-----------+------- 23 | text | text | text For results to sqlite3> select * from django_content_type where app_label = 'text'; sqlite3> I tried to figure out how to debug permission errors. I have also looked through auth_permission, but everything seems to be alright. Is there anyway to debug the permission process in order to find whats preventing my users from using the frontend editing? -
Django 1.11 - Password reset
I have an issue with a password modification form. I don't want to use the password reset function from Django. def view_password(request): if request.user.is_authenticated(): if request.method == 'POST': form = ChangePasswordForm(request.POST) if form.is_valid(): new_password = form.cleaned_data['new_password'] confirm_password = form.cleaned_data['confirm_password'] if new_password == confirm_password: strengh = new_password[0].isalpha() if all(c.isalpha() == strengh for c in new_password): messages.add_message(request, messages.INFO, 'Le mot de passe doit contenir au moins 8 charactères lettres et chiffres.') else: update = User.objects.get(id=request.user.id) update.set_password('new_password') update.save() messages.add_message(request, messages.INFO, 'Votre mot de passe a bien été changé.') else: messages.add_message(request, messages.INFO, 'La confirmation du mot de passe est incorrect.') else: messages.add_message(request, messages.INFO, 'Une erreur est survenue pendant la modification.') else: form = ChangePasswordForm() return render(request, 'password.html', locals()) else: from start.views import view_logon messages.add_message(request, messages.INFO, 'Vous devez être connecté pour accéder à cette page.') return redirect(view_logon) The form works well and the modification of the password is done. However, after looked at the database, it seems that the new password is not well hashed. Indeed when I try to login with the new password or the old password, it doesn't work. Thanks for your help. -
Javascript Alert On Successful Form Submission
I am currently using Django 1.9 and Braintree payments JS v3. What I want to be able to do is when the user submits the form successfully, have a Javascript alert() pop up. But the pop-up message will be contingent on what the back end Python returns... So like this: Submit the form Run the backend stuff Pop up the alert with a message dependent on what is returned by the Python backend When the alert is closed, refresh or redirect var client_token = "{{ request.session.braintree_client_token }}" var form = document.querySelector('#checkout-form'); var submit = document.querySelector('input[type="submit"]'); braintree.client.create({ authorization: client_token }, function (clientErr, clientInstance) { if (clientErr) { // for error loading client authorization if(alert('There was a form verification issue, reloading page on close.')){} else window.location.reload(); return; } braintree.hostedFields.create({ client: clientInstance, styles: { 'input': { 'font-size': '14px' }, 'input.invalid': { 'color': 'red' }, 'input.valid': { 'color': 'green' } }, fields: { number: { selector: '#card-number', placeholder: 'Credit Card Number' }, cvv: { selector: '#cvv', placeholder: '123' }, expirationDate: { selector: '#expiration-date', placeholder: '10/2019' }, postalCode: { selector: '#postal-code', placeholder: '10014' } } }, function (hostedFieldsErr, hostedFieldsInstance) { if (hostedFieldsErr) { // for errors creating form if(alert('There was a form creation issue, reloading … -
Python Package Malware Ztz
When I try to do pip install requirements.txt of a basic requirements package for django, the following malware runs: Collecting requirements.txt Using cached requirements_txt-1.1.1-py2.py3-none-any.whl Collecting ztz (from requirements.txt) Using cached ztz-0.1.1.tar.gz Installing collected packages: ztz, requirements.txt Running setup.py install for ztz ... error Complete output from command /Users/[user redacted]/inventory-barcode/inventoryenv/bin/python3 -u -c "import setuptools, tokenize;__file__='/private/var/folders/q9/124ns0sn68d1gkhlps1t60s80000gn/T/pip-build-nrl9xijr/ztz/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/q9/124ns0sn68d1gkhlps1t60s80000gn/T/pip-zthn0_6m-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/[user redacted]/inventory-barcode/inventoryenv/include/site/python3.6/ztz: running install [+] It looks like you try to install ztz without checking it. [-] is that alright? [*] Please visit http://evilpackage.fatezero.org/ [/] Aborting installation. ---------------------------------------- The package is supposedly intended to show people the dangers of installing typo'd packages, but it's obnoxious and unwelcome, and supposedly puts the user info online for public shaming. How can I get rid of it and prevent it from hijacking pip? -
python app deployment on heroku application error
I'm trying to deploy my python project to Heroku, I followed the tutorial on Heroku but still get an application error! (ISproject) Hessas-MBP-2:ISproject hessaaljeri$ git push heroku master Counting objects: 9, done. Delta compression using up to 4 threads. Compressing objects: 100% (9/9), done. Writing objects: 100% (9/9), 985 bytes | 0 bytes/s, done. Total 9 (delta 7), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/b in/steps/python: line 7: [: too many arguments remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: 180 static files copied to '/tmp/build_eb1f0e2e350e841c604cef9887a7c8c2/static'. remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 74.8M remote: -----> Launching... remote: Released v6 remote: https://charitycba.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy.... done. To https://git.heroku.com/charitycba.git 2890bc6..116d04a master -> master (ISproject) Hessas-MBP-2:ISproject hessaaljeri$ heroku run ./manage.py migrate Running ./manage.py migrate on ⬢ charitycba... up, run.7297 (Free) Operations to perform: Synchronize unmigrated apps: crispy_forms, messages, datetimewidget, staticfiles, geoposition Apply all migrations: auth, sessions, admin, registration, contenttypes, app, sites Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: No migrations … -
Python - logged exception is just '__exit__'
I am getting an internal server error for one of my view functions in Django that takes an image file and saves it to one of my models. The view function works in development, but is giving me an internal server error in production. I tried to wrap the part of the code that is failing in a try/except block, but the exception that it logs just says '__exit__' I'm not really sure what this means, or what kind of exception it is. I tried looking up what that exception would mean, but couldn't find anything. Does it have something to do with opening the file, and having issues closing it ? The exact part of the view function that breaks is where it says ... if name == 'one': trade_in.photo_one = file View def edit_photos(request): trade_in = account_trade_in(request) if not trade_in: return HttpResponse(json.dumps({'error': 'Something went wrong, unable to edit photos'}), content_type='application/json') if request.method == 'POST': try: file = request.FILES['file'] name = request.POST['photo'] if name == 'one': trade_in.photo_one = file elif name == 'two': trade_in.photo_two = file elif name == 'three': trade_in.photo_three = file elif name == 'four': trade_in.photo_four = file elif name == 'five': trade_in.photo_five = file elif name … -
Can I use a base64 encoded byte string as Django's secret key?
Is it acceptable to generate my SECRET_KEY in Django base64.base64encode(os.urandom(32)) or would using binascii.hexlify(os.urandom(32)) be a better option? If neither of these, what would you suggest? I'm trying to avoid Django's get_random_string since I don't think that is as secure. This is for a production environment. I could also increase the integer passed to os.urandom but I'm not sure what value is not overkill. -
Django messages automatically add username to recipient box
So i currently have django-messages on my website: https://github.com/arneb/django-messages and i have user profiles with an image, bio etc. I was wondering if there was a way to implement a button that would allow user when they are on another users profile to click a button and be able to send that person a message directly. So currently i could add a button that takes them to compose a message page, however they then need to manually add the persons username into Recipient*, as you can see in the image below. Ideally the persons username from the profile they where on would automatically be put into the recipient box. i would really appreciate any ideas, as i currently have no idea how to even start working on this. Thanks -
Django App Config in application located inside folder
I have a pretty large django 1.8 (as of June 2, 2017 still in LTS) project where, in order to keep things clean, I've broken some of the modules into a separate folder. For example, here's the file structure of my project open_project/accounts/__init__.py open_project/accounts/models.py open_project/accounts/views.py open_project/accounts/apps.py open_project/accounts/signals.py project/wsgi.py project/settings.py manage.py I want to hook my signal receivers (all stored in signals.py) to the broader application, so I have this bit of code in open_project/accounts/apps.py class AccountsConfig(AppConfig): """App configuration for the Accounts application""" name = 'accounts' verbose_name = 'Accounts' def ready(self): """Functionality to execute with the app is ready""" from open_project.accounts.signals import * And this code in open_project/accounts/__init__.py default_app_config = 'open_project.accounts.apps.AccountsConfig' When I run this code I get this traceback Unhandled exception in thread started by <function wrapper at 0x104c9ef50> Traceback (most recent call last): File "/Projects/Envs/project/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/Projects/Envs/project/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/Projects/Envs/project/lib/python2.7/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/Projects/Envs/project/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/Projects/Envs/project/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Projects/Envs/project/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Projects/Envs/project/lib/python2.7/site-packages/django/apps/config.py", line 138, in create app_module = import_module(app_name) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named … -
Django's management_form not getting post data
I'm having a trouble with django's formsets, the data from POST was being stored when I had just one formset but after I added a second one I am getting just the last input of each formset. Here are the forms: class OperationsForm( forms.Form ): operation = forms.CharField( required = True, max_length = 20, widget = forms.TextInput( attrs = { 'placeholder':'Operation Name' } ), ) class DataTypesForm( forms.Form ): field = forms.CharField( required = True, max_length = 20, widget = forms.TextInput( attrs = { 'placeholder':'Field Name' } ), ) type = forms.CharField( required = True, max_length = 20, widget = forms.TextInput( attrs = { 'placeholder':'Field Type' } ), ) Here is the views.py: def index( request ): OperationsFormSet = formset_factory( OperationsForm ) DataTypesFormSet = formset_factory( DataTypesForm ) if request.method == 'POST': operations_formset = OperationsFormSet( request.POST, prefix='operations' ) data_formset = DataTypesFormSet( request.POST, prefix='datas' ) if operations_formset.is_valid() and data_formset.is_valid(): operations_list = [] for operation_form in operations_formset: operation = operation_form.cleaned_data.get( 'operation' if operation: print( operation ) operations_list.append( operation ) operations = ' '.join(operations_list) operations = "\"" + operations + "\"" data_list = [] for data in data_formset: dataName = data.cleaned_data.get( 'field' ) dataType = data.cleaned_data.get( 'type' ) if dataType and dataName: dataToAdd = … -
How can I require a google recaptcha in django with angular?
This is my form. When you have filled in all fields, recaptcha is required as well -
In Django Admin page how do I retain few details when i delete an object?
from django.contrib import admin from .models import Offic,Slary admin.site.register(Offic) admin.site.register(Slary) -
Facebook login in localhost not working
I'm developing a Django app. My configuration is as follows: App Domain: localhost Site URL: http: //localhost:8000/ Valid Oauth Redirect URIs: http: //localhost:8000/ , http ://localhost/ But when i click on the login button i get this error: Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains. I tried checking similar questions but i haven't been able to make it work. -
Django/DRF: Why am I getting a Model error for a non model serializer?
I have a simple API endpoint. It takes two post parameters that match no model in my system: user_id and code My serializer: class ConfirmationCodeSerializer(serializers.Serializer): user_id = serializers.CharField(max_length=36) code = serializers.CharField(max_length=7) def validate(self, attrs): try: user = User.objects.get(pk=attrs['user_id']) except (ValidationError, User.DoesNotExist): raise serializers.ValidationError("invalid user_id") try: confirmation_code = SignupConfirmationCode.objects.get( user_id=attrs['user_id']) except (ValidationError, SignupConfirmationCode.DoesNotExist): raise serializers.ValidationError("confirmation record not found") if confirmation_code.code != attrs['code']: raise serializers.ValidationError("incorrect user_id and/or code") if user.is_active: raise serializers.ValidationError("user already confirmed") return attrs def create(self, validated_data): print(validated_data) user = User.objects.get(pk=validated_data['user_id']) user.is_active = True user.save() confirmation_code = SignupConfirmationCode.objects.get( user_id=user.id) confirmation_code.delete() return user my view: class confirmation_code(APIView): """ send confirmation code to validate and activate a new user account """ permission_classes = ([AllowAny]) def post(selfself, request, format=None): serializer = ConfirmationCodeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when it runs- it does it's job, the confirmation code is deleted, and the user record is updated, but I'm getting this error: AttributeError: Got AttributeError when attempting to get a value for field `user_id` on serializer `ConfirmationCodeSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'user_id'. My question is, why is the … -
MD5 of a file in JS and in Python/Django
I need to check the md5 of an image in django and in javascript. However I don't obtain the same results. The django code give me the same md5 as md5sum on a terminal. Django code : file0 = request.FILES.get('file') buffer0 = file0.read() print hashlib.md5(buffer0).hexdigest() //9f982242d24ab97a7254edd7e28e3921 I tried two javascript md5 library, which give me the same results ( https://github.com/blueimp/JavaScript-MD5 and https://github.com/sytelus/CryptoJS ). I have tried different methods (readAsArrayBuffer, readAsBinaryString, ...) and none of them give me the same md5 as python and md5sum. Javascript : var reader = new FileReaderSync(); var datas = reader.readAsArrayBuffer(file); console.log(md5(datas)); //060e4e9e30bcb9ae675a80328a87a687 var string0 = reader.readAsBinaryString(file); console.log(md5(string0)); //2e4cac0a23ddf95683c6538d64b26e21 console.log(CryptoJS.MD5(string0).toString(CryptoJS.enc.Hex)); //2e4cac0a23ddf95683c6538d64b26e21 var string1 = reader.readAsText(file,'ascii'); console.log(md5(string1)); //329c4271b8eda786213b2468e378b251 console.log(CryptoJS.MD5(string1).toString(CryptoJS.enc.Hex));//329c4271b8eda786213b2468e378b251 var view = new Uint8Array(datas); var str = "" for (var i=0, strLen=view.length; i < strLen; i++) { str+= String.fromCharCode(view[i]); } console.log(md5(str)); //2e4cac0a23ddf95683c6538d64b26e21 console.log(CryptoJS.MD5(string1).toString(CryptoJS.enc.Hex)); I think the problem come from how I read the file in JS. -
Django: filter by a property defined on a model, in a DRY way?
I'm working in Django 1.10. I have a model like this: class MyEvent(models.Model): class = models.ForeignKey(Class) starts = models.DateTimeField() url = models.URLField(blank=True, null=True) def in_past(self): return self.starts.date() < datetime.date.today() def is_interesting(self): return self.url or not self.in_past() In a couple of different places in my app, I want to show only events that are "interesting" as defined above, i.e. have a URL or aren't in the past. I want to display headers in the template if any such events exist. I don't seem to be able to do this in my views: events = MyEvent.objects.filter(is_interesting=False) in the view. In the template, I can filter individual events by this property, but I can't tell if there are any such events: {% if events.is_interesting.any %}Interesting events{% endif %} always returns false. Is there any way I can get a list of "interesting" events in my views or templates, in a DRY way? -
Create foreignkey object instances on parent create - Django
models.py class Req(models.Model): name = models.CharField(max_length=200) # fileup is a csv of 6 digit barcodes fileup = models.FileField(upload_to='uploads/') class ReqBarcodes(models.Model): barcode = models.CharField(max_length=6) req = models.ForeignKey(Req, on_delete=models.CASCADE) When the user uploads their csv, I would like to create ReqBarcodes instances for all barcodes contained in that csv file, analagous to on_delete CASCADE, but something like on_create CASCADE. My guess would be that I need to define a custom init method inside the Req model class. If so, can I perform csv validation inside that as well? Will either class instance be created if the validation fails? I would prefer not to have the classes created, and I will redirect the user to try again. I am also using a generic create view at this point. Can I modify this view, or is it necessary to write a completely custom view? views.py class RequestCreate(CreateView): model = Request fields = ['name', 'upload'] success_url = reverse_lazy('requests:index') -
TypeError at /index/:Expected binary or unicode string, got <Image: 43474673_7bb4465a86.jpg>
I want to use retrained model to classify image by using Django. In my Django project: model.py: from django.db import models class Image(models.Model): photo = models.ImageField(null=True, blank=True) def __str__(self): return self.photo.name setttings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'imageupload') urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from imageupload import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index, name='index'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render from .form import UploadImageForm from .models import Image import os, sys import tensorflow as tf def index(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): picture = Image(photo=request.FILES['image']) picture.save() #if os.path.isfile(picture.photo.url): os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' image_path = picture # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("retrained_labels.txt")] # Unpersists graph from file with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') with tf.Session() as sess: # Feed the image_data as input to the graph and get first prediction softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) # Sort to show labels of first prediction in order of confidence top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] a … -
Django elif template tag rendering with constant
I'm trying to compare a dictionary value with a constant and I'm noticing these are being treated differently, based on whether I use an if/elif statement and if I just compare the value directly with the value stored in the constant. Below is an example showing the relevant portions of the context dictionary and the template (only option 2 and 3 work). Am I missing something here as to why option 1 doesn't work? view: STATUS1 = 1 STATUS2 = 2 STATUS3 = 3 context = { 'obj1': {'status': STATUS3, 'otherattrs': 'other stuff'}, 'STATUS1': STATUS1, 'STATUS2': STATUS2, 'STATUS3': STATUS3 } option 1 template: {% if obj1.status == STATUS1 %} button 1 {% elif obj1.status == STATUS2 %} button 2 {% elif obj1.status == STATUS3 %} button 3 {% endif %} option 2 template: {% if obj1.status == STATUS1 %} button 1 {% endif %} {% if obj1.status == STATUS2 %} button 2 {% endif %} {% if obj1.status == STATUS3 %} button 3 {% endif %} option 3 template: {% if obj1.status == 1 %} button 1 {% elif obj1.status == 2 %} button 2 {% elif obj1.status == 3 %} button 3 {% endif %}