Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Serialize ManyToMany and ForeignKey Relationship Using Django REST framework
I have a model (model.py) that return the below results (result1) in the django shell, based on the query below (query1), and it works fine. My objective is to return the same queryset using Django Rest API, but I don't know how to manipulate my serialize to classes to to make this happen. I'm stuck on being able to return the respective user, in this case rhunter, for each task. Based on my view class below (view1.py) and my current serialized class below (serialize.py), I've been able to return the following below reults so far (result2), but I'm stuck. Any help would be greatly appreciated model.py class Task(models.Model): task_name = models.CharField(max_length=200) def __str__(self): return self.task_name @python_2_unicode_compatible # only if you need to support Python 2 class Space(models.Model): space_name = models.CharField(max_length=200) task = models.ManyToManyField(Task) def __str__(self): return str(self.space_name) @python_2_unicode_compatible # only if you need to support Python 2 class Room(models.Model): building = models.ForeignKey(Building, on_delete = models.CASCADE) room_name = models.CharField(max_length=200) rmfloor_name = models.ForeignKey(Floor, on_delete = models.CASCADE) sqfootage = models.IntegerField() spacetype = models.ForeignKey(Space, on_delete = models.CASCADE) barcode_name = models.CharField(max_length=100) def __str__(self): return self.room_name @python_2_unicode_compatible # only if you need to support Python 2 class Schedule(models.Model): building = models.ForeignKey(Building, on_delete = models.CASCADE) schedule_name = β¦ -
Django: unbound method is_authenticated() must be called with AbstractBaseUser instance
This issue is rather strange. Here's a stack trace: Environment: Request Method: GET Request URL: http://localhost/en/dashboard Django Version: 1.9.6 Python Version: 2.7.12 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django_mongoengine', 'django_mongoengine.mongo_auth', 'django_mongoengine.mongo_admin.sites', 'django_mongoengine.mongo_admin', 'django_adyen', 'spiral_api', 'rest_framework', 'rest_framework_mongoengine', 'spiral_admin', 'rest_framework_docs') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'spiral_api.middlewares.BehalfUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'spiral_api.middlewares.AuthHeaderMiddleware') Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 235. response = middleware_method(request, response) File "/code/django_app/spiral_api/middlewares.py" in process_response 11. def process_response(self, request, response): File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in inner 204. self._setup() File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in _setup 351. self._wrapped = self._setupfunc() File "/code/django_app/spiral_api/middlewares.py" in get_user 18. user = get_user_middleware(request) Exception Type: TypeError at /en/dashboard Exception Value: unbound method is_authenticated() must be called with AbstractBaseUser instance as first argument (got nothing instead) Here's a middleware: from functools import partial from django.contrib.auth.middleware import get_user as get_user_middleware from django.contrib.auth.models import AbstractBaseUser from django.utils.functional import SimpleLazyObject from spiral_api.models import SpiralUserProfile class AuthHeaderMiddleware(object): def process_response(self, request, response): response['is_login'] = int(request.user.is_active) if hasattr(request, 'user') else 0 return response class BehalfUserMiddleware(object): def get_user(self, request): user = get_user_middleware(request) if user.is_authenticated(): profile = SpiralUserProfile.objects.get(user=user) return profile.behalf or user else: return user def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before β¦ -
Django session always closes after browser close
once I set this in settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True I can't change to set it back and make sessions always open. I tried to set this to False , but no effect. -
Store the user who submitted the form into the same table?
I'm looking for the most advisable method for storing the name of the user responsible for the form submission so that I can easily organize the forms they have submitted by their username sort of like an "account setting" for each user. I've searched but the solution is very fragmented and all posts about this refer to older versions as well as the best solution changing in every Django version. It probably doesn't help that I'm still learning the basics of Django. Here is my views.py: def add(request): title = 'Add Reddit Account' # ADD FORM form = AddRedditForm(request.POST or None) instance = form.save(commit=False) instance.user = request.user instance.save() if request.method == "POST": print(request.POST) context = { "form": form, "title": title, "user": instance.user } return render(request, "addreddit/add.html", context) and my models.py: from django.db import models class Account(models.Model): user_name = models.CharField(max_length=20) password = models.CharField(max_length=18) secret = models.CharField(max_length=100) tag = models.CharField(max_length=20, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) user = models.ForeignKey('auth.User', null=True) def __str__(self): #Python 3.3 is __str__ return str(self.user) return self.user_name return self.password return self.secret return self.tag return self.timestamp Lastly, forms.py in the event that it's relevant: from django import forms from .models import Account class AddRedditForm(forms.ModelForm): class Meta: model = Account fields = β¦ -
How to change a html page from flask to Django
I am working on an app that requires changing a flask template to that of Django.How to change the url_for('function') in the html page -
How do you upload a file from a form in a Django test through Client.post()?
I'm designing a Django test in which I upload an .xml file. If the file is correct (validated by the schema) it's data it's added to project's database. Part of the code for the view: if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): result = parse_xml_question(request.FILES['docfile'], topic_id) I have the following class for the form: class UploadFileForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='.xml file' ) The html where the form is used: <form action="{% url 'add_question_w_subject_topic' subject.id topic.id %}" enctype="multipart/form-data" method="post"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload" /></p> </form> And the test that fails: def test_question_file_wrong_format(self): c = Client() script_dir = os.path.dirname(__file__) rel_path = "xml_files/wrong_format.xml" abs_file_path = os.path.join(script_dir, rel_path) response = c.post('/add/question/'+ str(self.subj1.id) +'/' + str(self.topc1.id) + '/', {'docfile': open(abs_file_path, 'rb')}) self.assertEquals(response.status_code, 200) Notice this line: response = c.post('/add/question/'+ str(self.subj1.id) +'/' + str(self.topc1.id) + '/', {'docfile': open(abs_file_path, 'rb')}) I have tried several ways. In all of them, it returns a status code 302, while I was expecting 200, I've read this, and I can't understand it enough to adapt that solution to my code. If you need more information, just tell me. Sorry β¦ -
Django: Filling out a ManytoMany relationship for every new form in a formset
I'm using these 3 models (simplified): class Model1(models.Model): field1 = models.CharField(max_length=25) class Model2(models.Model): field1 = models.CharField(max_length=25) class Model3(models.Model): model1 = models.ForeignKey(Model1) model2 = models.ForeingKey(Model2) I have a form for Model1 and a formset for Model2s that work but the problem is that for every Model2 in the formset I want there to also be a Model3 that connects Model2 to Model1. How do I add Model3 so it gets filled out for each Model2 in the formset? I tried finding a solution using inlineformsets or modelformsets but I still don't really understand them. I don't even know if that's the right direction to go in. I'm looking for anything that will point me in the right direction. -
How to run Django tests using Twisted Trial?
I recently discovered Twisted Trial but I can't find a way to run Django tests with it. If I try to run trial djangoapp/tests.py I get an error because it is not making all the setup steps that manage.py test does. Anyone uses Trial to run Django tests? -
django: how to make a choice field choosing from entry of a m2m field?
Sorry if the title doesn't make lots of sense. Let's say we have a model set up like this: class Sample(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Project(models.Model): description = models.CharField(max_length = 200, null=True) sample = models.ManyToManyField(Sample) class SampleLogoutRecord(models.Model): project = models.ForeignKey(Project, on_delete = models.CASCADE, null=True) sample_choice = models.CharField(max_length = 200, null=True, choices = SAMPLE_CHOCIES) logout_date = models.DateField(null=True) logout_by = models.CharField(max_length = 200, null=True) So basically with have the main model Project which holds a m2m field sample that relates to several samples. And then SampleLogoutRecord is a foreign key to project that is a record of a specific piece of sample belonging to this project is logged out. My problem is, how do I set sample_choice up so that this choice field use those samples belongs to this project as choice options? For example, if Project A has sample 1, 2 and 3. I would like sample_choice to be a choice field with options: 1, 2 and 3. From official document it seems that choices of a choice field could be a callable that returns a 2-tuple list. This sounds like what I should do but I got stuck on how actually implements this. TIA -
Changes to Excel file not showing up in pandas ExcelFile() import
I am using the code below to import data from and Excel file to a Django-based website. The file reads just fine but when I make changes to the file and save them and then reload my website, the data is not refreshed. But, if I save the modified Excel file that I'm trying to load under a different name and load that file instead, the website updates as it's supposed to. I would like for changes I make to show up without having to rename the file. How can I tell pandas to do this? from pandas import * xlsx = ExcelFile('Testbook3.xlsx') df = xlsx.parse(xlsx.sheet_names[0]) df_dict = df.to_dict() -
django list of values
What is the best way to store a field that can take a subset of choices of another class? I have a class with a field that is a list of choices: class Type( models.Model): type = models.CharField(max_length=4, choices=TYPE_CHOICES, default='CONS') and another class with a foreign key to Type that should store a subset of the choices: class AnotherType( models.Model ): model_parameter = models.ForeignKey(Type, on_delete=models.CASCADE) subset = models.XXX( arbitrary subset of Type.type.TYPE_CHOICES ) Any help is appreciated! -
Django close sessions if users moves another site or after browser close
How can I close sessions in Django if a user moves from my site to another or if he close the browser. -
How do i implement both built-in django auth and third party social-auth in my application?
I using django from last 4-5 months and recently started learning django-rest-framework and I'm confused about proper authentication system, Actually I am trying to build an application mostly using REST API because my client can be both browser and Android, so I need an authentication system in which user can sign up using both django built-in auth(django.contrib.auth.model.User) as well as third-party social authentication(Google, Facebook, etc..). Now, I'm confused about how do I create my database, because when ever i'll create a table/model lets say a 'Book', then this model would need a foreign key to the user model and here user can be both 'django.contrib.auth.model.User' and a user signed-up using third party auth, So how I will refer to User in foreign key Field of my models? And I have also decided to customize django's buit-in auth because i want user to login using their email not username. class Book(models.Model): title = models.CharField(...) author = models.ForeignKey(?) ? Here, how do i refer to both 'django.contrib...User' and users signed-up using thrid-party auth. -
Using JavaScript to render forms dynamically in Django
So I am new to Django and a complete novice at JavaScript. I am trying to create a view which renders multiple forms dynamically using JavaScript. Below are two forms that I have created. class CreateTestForm(forms.ModelForm): class Meta: model = Test fields = ['name', 'test_group', 'description', 'query_text', 'failure_condition', 'status'] def getKey(self): return "create_test_form" class VC1Form(CreateTestForm): expected_relation = forms.ChoiceField(choices = [('<','<'), ('>','>'), ('=','='), ('<=','<='), ('>=','>='), ('!=','!=')], required = True, label = 'Expected Relation: ') num_rows = forms.IntegerField() def getKey(self): return "vc1_form" In addition, I have the following view def create_test(request): context = { 'all_validation_classes': ValidationClass.objects.all() } for form in [CreateTestForm, VC1Form]: if request.method == 'POST': f=form(request.POST) if (f.is_valid()): return HttpResponseRedirect('/test_created/') else: return HttpResponseRedirect('/test_not_created/') else: f = form() context[f.getKey()] = f return render(request, 'create_test.html', context) And template: <form action="/tests/create/" method="post"> {% csrf_token %} {{create_test_form.as_ul}} <br><br> <select id="validation_classes_id" name="all_validation_classes" onchange="showForm()"> <option value="%">Choose the validation class</option> {% for val_class in all_validation_classes %} <option value="{{ val_class.id }}">{{ val_class.id}} {{val_class.name }}</option> {% endfor %} </select> <br><br> <script> function showForm(){ var x = document.getElementById("validation_class_id").value; } </script> <input type="submit" value="Submit" /> I am trying to get to a point, where, when the user selects something from the dropdown (validation_classes_id), the view will render the form corresponding to that β¦ -
How to search a file and find the closest one?
I should find the file path of the manage.py no matter where I am in the Django project directory. Of course, the manage.py should be correct one. And I have do not use any external module. Example possible positions: βββ workspace β βββ project 1/ [HERE] β β βββ env/ β β βββ src/ [HERE] β β β βββ core/ [HERE] β β β βββ app/ [HERE] β β β β βββ migrations/ [HERE] β β β β βββ templatetags/ [HERE] β β β β βββ admin.py β β β β βββ views.py β β β β βββ models.py β β β βββ templates/ [HERE] β β β β βββ app/ [HERE] β β β βββ manage.py β βββ project 2/ β β βββ env/ β β βββ src/ β β β βββ core/ β β β βββ app β β β βββ manage.py The script should run from the outside of the virtual environment. I do not have access the Django module. What is the fastest way? ps: Actually, I can use VimScript instead of Python too. I want to do this to write a vim plugin. -
I am developing a p2p file transfer system in python using sockets but I dont know how to listen as well as do query at same time
I am creating p2p file transfer system but am unable to understand how to listen as well as perform query at the same time -
Reconstruct a Django Fieldname in Django Template
I do not know if this is possible and if I need to redesign my approach. I have a table which I am creating as follows: DAYS = ( ('Monday'), ('Tuesday'), ('Wednesday'), ('Tursday'), ('Friday'), ('Saturday'), ('Sunday'), ) WORK_HOURS = range(8,22) HOUR_BREAKS = ['00','30'] def time_slots(*args): class TimeSlot(models.Model): class Meta: abstract = True for slot in args[0]: models.BooleanField( default=False ).contribute_to_class(TimeSlot, slot) return TimeSlot slots = ['%s %s:%s' % (d, h, m) for d in DAYS for h in WORK_HOURS for m in HOUR_BREAKS] class NormalWorkingHours(time_slots(slots)): user = models.OneToOneField(User, on_delete=models.CASCADE) def __unicode__(self): return u'%s' % ('Normal Working Hours: ' + self.user.first_name + ' ' + self.user.last_name) This gives me column names of 'Monday 8:00', 'Monday 8:30' ... 'Sunday 21:30' which is great. I have a form declared as follows: class NormalWorkingHoursForm(forms.ModelForm): class Meta: model = NormalWorkingHours exclude = ['user'] This will create a long list of checkboxes which isn't particularly useful. I've, therefore, tried to put the form into a table as follows: <form method="post" action="{% url 'work-week' %}">{% csrf_token %} <table class="table table-condensed"> <thead><td></td> {% for d in days %} <td>{{d}}</td> {% endfor %} </thead> {% for h in hours %} {% for m in slots %} <tr> <td>{{h}}:{{m}}</td> {% for β¦ -
Serving font awesome files from S3
I have a Django app hosted on Heroku and I want to serve my static assets from S3. I'm having trouble getting the font awesome files loading correct. I've read a number of posts on setting the the CORS poilcy such as this question. I've tried every one of those answers and I keep getting this error: Font from origin 'https://s3-eu-west-1.amazonaws.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://myapp.herokuapp.com' is therefore not allowed access. The font awesome file contains the following. @font-face { font-family: 'FontAwesome'; src: url('../fonts/fontawesome-webfont.eot?v=4.2.0'); src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg'); font-weight: normal; font-style: normal; } I suspect the way it loads the font files might be causing the issue, but have no idea how to solve it? Or what else could be causing this to fail? Note I'm not using Cloadfront, just plain S3. -
Django: setting the foreignkey in a model form
I have models for an event and an attendee class Event(models.Model): name = models.CharField(...) class Attendee(models.Model): event = models.ForeignKey(Event) first_name = models.CharField(...) last_name = models.CharField(...) I want to create a view for people to signup as attendees, but I want to define what event they are signing up for in the view. The attendee should not be able to choose the event. They can only enter their name. I've created a model form: class AttendeeForm(forms.ModelForm): class Meta: model = Attendee fields = ['first_name', 'last_name'] And I created a view: class Signup(FormView): form_class = AttendeeForm template_name = 'event/signup.html' success_url = reverse('event_signup_success') def event(self): """ For example, let's say I have the event here. What do I do with it? """ return Event.objects.get(pk=1) Trying to submit this form currently results in a error, since the Attendee does not have an event defined. I'm not sure how I should be setting the event in the view. I do not want to add the event to the form as a hidden field and then set it in the view using get_initial because then the user could possibly change it by modifying the POST data. What is the best way to set the event in β¦ -
Odd!! django OneToOneField can't save foreign key value
User """The user model is the default model of django""" Model class UserProfile(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) # !!!!!!!!!---here OneToOne Field--!!!!!!!!!! user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) description = RichTextField(max_length=140, default='') avatar = models.CharField(max_length=50, default=_random_avatar, null=True) home_url = models.URLField(blank=True, null=True) github_url = models.URLField(blank=True, null=True) linkedin_url = models.URLField(blank=True, null=True) stackoverflow_flair = RichTextField(blank=True, null=True) is_user = models.BooleanField(default=False) is_public = models.BooleanField(default=False) Form class ProfileForm(ModelForm): class Meta: model = UserProfile fields = '__all__' View @login_required def index(request): """ Notice, the profile.html is composited by 2 sections, user and profile So, setter and getter all are 2 group, too """ info = None if request.user.is_authenticated: user = request.user if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): # link to user form.user = user form.save() # <------here, can't save the user_id, why? else: form = ProfileForm() # here, queryset allways is null <------- profile = UserProfile.objects.filter(user_id=user.id) return render(request, 'account/profile.html', {'user': user, 'profile': profile, 'form': form} ) else: return redirect( reverse('account_login') ) I try to fill the profile information in form view,then saving, but I can get a new record in table profile, but the user_id is null. I don't know why. -
Django CKEditor uploaded images url ends with get request (AWS S3 bucket parameters)
I serve all my STATIC & MEDIA with Amazon S3, for my Django app and it works great... But I have some troubles with the uploaded images with CKEditor. It generates some GET requests at the end of my generated tag (you have to scroll a little to see the interesting part). <img src="https://wailing-trees.s3.amazonaws.com:443/media/uploads/2016/10/18/avatar-clip.jpg?Signature=qwPDtjmDG5hsaxOEAp5OhEYrqrk%3D&amp;Expires=1476816373&amp;AWSAccessKeyId=AKIAI2MJLYGYK72HZIEQ"style="height:900px; width:904px"> And that request is expired so the image can't displays. That adress returns : <Error> <Code>AccessDenied</Code> <Message>Request has expired</Message> <Expires>2016-10-18T18:46:13Z</Expires> <ServerTime>2016-10-28T16:03:27Z</ServerTime> <RequestId>D9C4809CF1DE0AF3</RequestId> <HostId> 9f6KFwhlBSjDZZo3XxovY8eqLC7bPkiCFi7ygPrPGSpsCurvFjRoU15XtnJYZNd1gvMYEj6qpBE= </HostId> </Error> I have also that in my settings.py : CKEDITOR_UPLOAD_PATH = 'uploads' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': [ ["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["HorizontalRule",], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink",], ['Undo', 'Redo'], ["Source"], ["Maximize"]], 'extraAllowedContent': 'iframe[*]', }, } AWS_HEADERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = 'wailing-trees' AWS_ACCESS_KEY_ID = 'AKIAI2MJLYGYK72HZIEQ' S3_REGION_NAME = 'eu-west-1' AWS_SECRET_ACCESS_KEY = 'XXXXXXXX' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME # MEDIA_ROOT = os.path.join(BASE_DIR, 'wt/media/') STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' import custom_storage STATICFILES_STORAGE = 'custom_storage.StaticStorage' DEFAULT_FILE_STORAGE = 'custom_storage.MediaStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storage.MediaStorage' AWS_QUERYSTRING_AUTH = β¦ -
Is there a easy way to filter mulitfield in django's admin site?
The Model: class Person(Model): (...) fathers = models.ManyToManyField('Person', related_name="fathers_children", blank=True) mothers = models.ManyToManyField('Person', related_name="fathers_children", blank=True) sex = models.CharField(null=True, blank=True, max_length=1) admin.py: class PersonAdmin(admin.ModelAdmin): form = PersonAdminForm model = Person fields = ('last_name', 'birth_date','fathers','mothers') ordering = ['last_name','birth_date'] admin.site.register(Person, PersonAdmin) (maybe I cut to much, but I think it is self descriptive) Please don't think why person can have more than one father/mother - it is intentional. And now when I enter to e.g /admin/person/836, got the form with two MultipleChoiceFields containing full list of persons. I want to reduce both - fathers should contains males, mothers - females. But how to do it? -
Python web serve JSON feeds from my Postgres DB
I'm a python/postgres developer and have populated quite a few Postgres databases with statistics for my own and companies data analytics projects. I now would like to have a web layer where I can create some JSON feeds which I will use https://www.geckoboard.com to listen to and provide a webfront end analytics for my company dashboards. I'm very comfortable with the querying and creating dictionaries from my DBs so should I use a web framework like web2py/Django to serve the JSON or is this overkill? I also might want to merge data from multiple databases an export into one JSON feed on the fly after the feed URL is called. Can anyone point me in the right direction for a simple helloworld app/server example which I should follow. I've checked out: http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer but I kinda see this as overkill but maybe I'm wrong! Thanks in advance -
How to display content dinamically in django view?
I'm currently using Zbar to read barcodes in an application that is written in python. Also I'm running a web app with Django to work with my barcode reader. When I read a barcode I check it on a sqlite3 database (default Django database) if exist. If it exist I need to display it on a table in one of my Django views automatically. As far as I've got is this: Zbar Reader #!/usr/bin/python from sys import argv import zbar import sqlmanager # create a Processor proc = zbar.Processor() # configure the Processor proc.parse_config('enable') # Create Database comparator comparator = sqlmanager.DatabaseComparator("db.sqlite3") # initialize the Processor device = '/dev/video1' if len(argv) > 1: device = argv[1] proc.init(device) # setup a callback def my_handler(proc, image, closure): # extract results for symbol in image.symbols: # do something useful with results compare(symbol.data) # Here I should sent it to Django view: # pseudocoding... if comparator.barcodeExist(): render(DjangoView, comparator.getDBresults()) def compare(symbol): comparator.connectDatabase() comparator.checkBarcode(symbol) comparator.printResults() comparator.disconnectDatabase() proc.set_data_handler(my_handler) # enable the preview window proc.visible = True # initiate scanning proc.active = True try: # keep scanning until user provides key/mouse input proc.user_wait() except zbar.WindowClosed, e: pass Database comparator import sqlite3 # Class to compare barcode readed to the β¦ -
'str' object has no attribute 'get'
I am trying to set a field's choices in a modelform by overiding the init but i get this error 'str' object has no attribute 'get' forms.py class carOwnerForm(forms.ModelForm): first_name = forms.charfield() last_name = forms.charfield() def __init__(self, a,b,c): super(carOwnerForm,self).__init(a,b,c) self.field["ownership_Type"].choice = [a,b,c] class Meta: model = CarOwner fields = ['ownership_type','CarModel'] view def CarOwnerSearch(request): if request.user.is_authenticated(): form = carOwnerForm('B','None','C') return render (request,'carmanager/CarOwnerSearch.html', {'form': form}) error in the html Request Method: GET Request URL: http://127.0.0.1:8000/parcelmanager/CrownLandsSearch/ Django Version: 1.8 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'get' Exception Location: C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 223 Traceback: File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Sites\laisy\carmanager\views.py" in CrownLandsSearch 811. return render (request,'carmanager/CrownLandsSearch.html', {'form': form}) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\shortcuts.py" in render 67. template_name, context, request=request, using=using) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\loader.py" in render_to_string 99. return template.render(context, request) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\backends\django.py" in render 74. return self.template.render(context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render 209. return self._render(context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in _render 201. return self.nodelist.render(context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render 903. bit = self.render_node(node, context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\loader_tags.py" in render 135. return compiled_parent._render(context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in _render 201. return self.nodelist.render(context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\base.py" in render 903. bit = self.render_node(node, context) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File β¦