Community

Django community: Django Q&A RSS

This page, updated regularly, aggregates Django Q&A from the Django community.

Connecting Django to an sensor using sockets?

Posted on April 24, 2014 at 10:46 PM by Stack Overflow RSS

I have a sensor that is connected to a GSM/GPRS module. The data is to be stored and displayed online with django. I want to also be able to send commands to the device. I'm unclear on how to connect the two parts of this project. As I understand it, sockets are not directly supported in django. I've taken a look a few libraries and other projects that use sockets in django, but I found them confusing and I am unsure as how to set up my project to use them (I'm new to django). My question: Is there an easier or better way of doing this without using sockets in django? For instance,a separate python socketserver...would that be able somehow relay the sensor data / commands back and forth? Thanks for your time.

Read this post in context »

Django/python: Model relationships for API related data

Posted on April 24, 2014 at 10:18 PM by Stack Overflow RSS

I am building a wrapper around an API, and as such I want to hold information that the API itself holds (I want any updated api information to be held on my server as well). This being the case, I need to build models that anticipate the data I will be receiving. So I started building these models. Let us assume they look like this: class ModelForAPI(models.model): #model fields here Now this data is going to steadily be collected and updated accordingly when it is needed to. Let's then assume that in addition to the models ive built to hold the api data, I have more data that is related but that is relevant on my server only. The question becomes: how is the best way to "extend" this data? I feel that there a few possible options, either I extend the api model like such: class Model(models.Model): api_information = ForeignKey(ModelForAPI) Or I subclass it like such: class Model(ModelForAPI): #model fields here Since I am dealing with API information that is going to be updated frequently with new information, I am not sure which would make my life easier in terms of model architecture. Any pointers would be much appreciated.

Read this post in context »

Django - How to create form fields by iterating through a database query?

Posted on April 24, 2014 at 10:14 PM by Stack Overflow RSS

So I would like to set up a form based on the values I have stored in my database. Let's say I have a model like this: class Questions(models.Model): question = models.CharField(max_length=350) And I would like to create a form in this way: for x in Questions: answer = forms.CharField(label = x.question) And thereby having exactly the number of answer fields in the form as there are questions stored in the database. Any ideas?

Read this post in context »

How to fix this database schema to avoid inconsistency?

Posted on April 24, 2014 at 10:13 PM by Stack Overflow RSS

I'm stuck on an issue of database design. How do I set this up to avoid problems with consistent data down the road? Let's consider three objects: (django model definitions below) TaskType TaskGroup foreignkey to TaskType TrainingTask foreignkey to TaskType foreignkey to TaskGroup The problem (at least I think this is a problem) is that if I have a TrainingTask, then it could potentially have inconsistent values for TaskType (via the direct foreign key and indirectly via the fk to TaskGroup). And some "facts" about these objects: TaskTypes hold meta information about TrainingTasks. TaskGroups are for grouping tasks of the same type. Elsewhere in my application I want to be able to take a TaskGroup and say "give me a random TrainingTask from this TaskGroup". There can be lots of TrainingTasks for a TaskType. All the TrainingTasks in a group should have the same type There can be lots of TaskGroups for a TaskType TrainingTasks with the same TrainingType can be in different TaskGroups Also, I am doing all this in Django, and TrainingTask is a subclass of Task (using Multi Table Inheritance), and thus TrainingTask inherits the fk to TaskType from Task. I would like to keep this structure ...

Read this post in context »

How to make a form that creates a new object and objects related by foreign keys in one request?

Posted on April 24, 2014 at 10:04 PM by Stack Overflow RSS

I have a Recipe model and a Step model, where multiple steps are linked to a recipe via a foreign key. What is the best solution for making a form that creates a new recipe and multiple steps at the same time? After googling around I have only found inline formsets, but they require an instance of the recipe (found by pk) but of course in practice the recipe would not be saved before the form is generated since they (the recipe and its steps) are created in one request. Anyone solved a problem similar to this?

Read this post in context »

Django messaging framework messages not making it passed the redirect()

Posted on April 24, 2014 at 9:43 PM by Stack Overflow RSS

I have some "save" code that sets a success message using the Django messaging framework upon successful creation of a record, then does a redirect back to the main 'application_update' view. I'm having trouble determining why these messages are not making it thru the redirect. The messaging seems to work just fine when doing a "render_to_response", but not when doing a "redirect". function snippet (if POST) in views.py: if ovrd_form.is_valid(): fields = {'application': ovrd_form.cleaned_data['application'], 'course': ovrd_form.cleaned_data['course'], * other field/values * } try: overrides = Overrides(**fields) overrides.save() success_msg = 'Override creation was successful.' create_message(request, success_msg, 'success') except Exception, exception: return HttpResponse('Error: ' + str(exception)) return redirect('application_update', app_id=app_id) create_message() function: from django.contrib import messages def create_message(request, msg, msg_type): """ build a message & sets the correct message.type """ if msg_type == 'error': django.contrib.messages.error(request, msg) elif msg_type == 'warning': django.contrib.messages.warning(request, msg) elif msg_type == 'success': django.contrib.messages.success(request, msg) elif msg_type == 'info': django.contrib.messages.info(request, msg) elif msg_type == 'debug': django.contrib.messages.debug(request, msg) all templates inherit this piece of code: {% if messages %} {% for message in messages %} {% comment %}force -danger if error type for bootstrap css class{% endcomment %} {% if message.tags == 'error' %} <div class="alert alert-danger"> {% else %} <div class="alert ...

Read this post in context »

Django Rest Framework: Non-model service

Posted on April 24, 2014 at 9:34 PM by Stack Overflow RSS

I have been using django-rest-framework for creating services that work with the models. Now I need to create a service that receives some data, evaluates it and sends a notification email. It has been difficult to find such use case in django-rest-framework documentation and I think Function based views(at http://www.django-rest-framework.org/api-guide/views#function-based-views) would be the best approach but not sure if it is. There is very few documentation of it around. Which would be the best way to implement such service?

Read this post in context »

Add CSS class to django-crispy form using hacked inline checkbox for Boolean

Posted on April 24, 2014 at 9:11 PM by Stack Overflow RSS

I'm using crispy-forms to generate an inline-checkbox for a Boolean field using this workaround BooleanField checkbox not render correctly with crispy_forms using bootstrap, which works great except I can't seem to get my css_class to pick up. I've tried every configuration I could think of. Div( Row( Field('role', wrapper_class='col-md-6'), Field('status', wrapper_class='col-md-6'), ), Row( Field('sub_status', wrapper_class='col-md-6'), PrependedText('smarts_monitoring', '', wrapper_class='col-md-6'), #this one doesn't show up ), css_class='attribute_group') )

Read this post in context »

Count and Max after values() method on Django query

Posted on April 24, 2014 at 8:43 PM by Stack Overflow RSS

I have this Django model: class Action(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game) step = models.ForeignKey(Step) from_player = models.ForeignKey(Player) to_player = models.ForeignKey(Player) type = models.ForeignKey(ActionType) timestamp = models.DateTimeField(default=timezone.now) I want to do the following: Filter on game, step and type Find the player/players how has/have obtained the highest number of actions to do so I tried: v = Action.objects.filter(game=1, step=2) v = v.filter(type=3) v = v.values('to_player').order_by().annotate(count=Count('to_player')) v = v.annotate(max=Max('count')).filter(count=F('max')) #try to select the max but last line gives me (because line 3 returns a list of dictionaries): Cannot compute Max('count'): 'count' is an aggregate I know that probably something similar has already been answered but Django values() and aggregate() are a bit tricky to me. Which is the right way to do this?

Read this post in context »

how to access attributes of model fields in templates in django?

Posted on April 24, 2014 at 7:57 PM by Stack Overflow RSS

I have been used the following two urls in my code. In the first case, I access pk of object using underscore. In the second case, I do .pk. For the first one, changing underscore to .pk does not make any difference. but for the second one template throws reverseMatch error? why is it? what is the rule behind field access of objects in templates and views? <a href="{% url 'search_update' pk=search_pk %}">Edit</a> <a href="{% url 'postings_list' pk=post.pk %}" Posting </a>

Read this post in context »

Django, template attribute unique

Posted on April 24, 2014 at 7:39 PM by Stack Overflow RSS

I'm trying to implement a list of events to a js calendar. So the data for the calendar are like this: var studyEvents = { '04-03-2014' : '<span class="event">Event 1</span>', '05-08-2014' : '<span class="event">Event 2</span>', '12-09-2014' : '<span class="event">Event 3</span>' }; In case the are more than one events on the same day, the data are like this: var studyEvents = { '04-03-2014' : '<span class="event">Event 1</span>', '05-08-2014' : '<span class="event">Event 2-1</span><span class="event">Event 2-2</span>', '12-09-2014' : '<span class="event">Event 3</span>' }; So what I'm doing is getting a list with all events ordered by date. I want to check if there are more than one events in on the same day. I'm thinking that I could check(since the list is ordered by date) if the event.date is not unique then there could be a way to put it on the same line. var studyEvents = { {% for event in events %} '{{ event.date|date:"m-d-Y" }}' : '<span class="event">{{ event.title }}</span>'{% if not forloop.last %},{% endif %} {% endfor %} }; I'm a bit lost with this one so any help would be much appreciated!

Read this post in context »

General purpose Python functions in Django views.py

Posted on April 24, 2014 at 7:07 PM by Stack Overflow RSS

I'm writing a simple Django app and I'm having trouble finding a place for general purpose Python functions (not views). Some of the views in views.py are getting chubby and I want to outsource some calculations to a couple of general purpose functions. Should I create some outside module for that, or it is perfectly normal to put them in views.py. What is the general policy about mixing Django-related and generic Python code? I've been thought that generally Django doesn't care, but I can't help cringing when I do that.

Read this post in context »

Django Allauth - 'Association' object has no attribute 'getExpiresIn'

Posted on April 24, 2014 at 6:58 PM by Stack Overflow RSS

I'm trying to set up Google OpenID for my django application using allauth. When I attempt to sign in using google it routes me correctly to google, but once I get sent back to my site I get the following error: 'Association' object has no attribute 'getExpiresIn' The full log follows: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/openid/login/?process=login&openid=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid Django Version: 1.6.2 Python Version: 3.4.0 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.openid', 'allauth.socialaccount.providers.facebook') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "/home/dan/env3b/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dan/env3b/lib/python3.4/site-packages/allauth/socialaccount/providers/openid/views.py" in login 36. auth_request = client.begin(form.cleaned_data['openid']) File "/home/dan/env3b/lib/python3.4/site-packages/openid/consumer/consumer.py" in begin 352. return self.beginWithoutDiscovery(service, anonymous) File "/home/dan/env3b/lib/python3.4/site-packages/openid/consumer/consumer.py" in beginWithoutDiscovery 375. auth_req = self.consumer.begin(service) File "/home/dan/env3b/lib/python3.4/site-packages/openid/consumer/consumer.py" in begin 603. assoc = self._getAssociation(service_endpoint) File "/home/dan/env3b/lib/python3.4/site-packages/openid/consumer/consumer.py" in _getAssociation 1170. assoc = self.store.getAssociation(endpoint.server_url) File "/home/dan/env3b/lib/python3.4/site-packages/allauth/socialaccount/providers/openid/utils.py" in getAssociation 107. if assoc.getExpiresIn() == 0: Exception Type: AttributeError at /accounts/openid/login/ Exception Value: 'Association' object has no attribute 'getExpiresIn' I've followed the documentation carefully and have what I think are the correct settings: LOGIN_URL = '/accounts/login/' SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'publish_stream'], 'METHOD': 'js_sdk' # instead of 'oauth2' }, 'openid': {'SERVERS': [dict(id='yahoo', name='Yahoo', openid_url='http://me.yahoo.com'), dict(id='google', name='Google', openid_url='https://www.google.com/accounts/o8/id')] ...

Read this post in context »

In Django CMS how do I access the Page object from the Form of a CMSPlugin?

Posted on April 24, 2014 at 6:56 PM by Stack Overflow RSS

I have a CMS plugin I wrote for Django CMS 2.4 but it is not working now that I've upgraded to version 3.0. This is no-doubt because 3.0 uses front-end editing by default whereas I had only used it from within the admin screens before. The CMSPluginBase I'm using has a custom Form and the options available in a ChoiceField need to be limited by which Site the Page containing the plugin belongs to. I used to be able to pass the request object into the Form and do this to get the Site: self.request.current_page.site current_page is now a None object (wrapped in a SimpleLazyObject) when the plugin loads in the front-end editing popup. I've tried self.Meta.model.page and various other items in Meta and request to no avail.

Read this post in context »

Django-Storages on s3

Posted on April 24, 2014 at 6:39 PM by Stack Overflow RSS

I have gone through the django-storages for s3 setup and I can submit a form with a file selected without error. However, no files are loaded to my bucket. settings.py: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = '*********' AWS_SECRET_ACCESS_KEY = '**********' AWS_STORAGE_BUCKET_NAME = 'bucketName' STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' When I try to check default_storage: >>> from django.core.files.storage import default_storage >>> print default_storage.connection Getting: ImproperlyConfigured: Requested setting DEFAULT_FILE_STORAGE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Any ideas on what I'm missing? (note - I have installed boto)

Read this post in context »

Using Django With Dynamic Inline Formsets

Posted on April 24, 2014 at 6:39 PM by Stack Overflow RSS

I'm going off the code used here. Problem is I'm getting the error "ManagementForm data is missing or has been tampered with" anytime I try to add new forms to the page. I'm almost positive the problem is here: {{ formset.management_form }} Here's what I'm working with: {% extends "base.html" %} {% block base_content %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="{{ STATIC_URL }}js/jquery.formset.js"></script> <script type="text/javascript"> $(function() { {% for formset in inlines %} $('div#FormSet{{ formset.prefix }}').formset({ prefix: '{{ formset.prefix }}', formCssClass: 'dynamic-formset{{ forloop.counter }}' }); {% endfor %} }) </script> <form id="myForm" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> {% for formset in inlines %} <div id="FormSet{{ formset.prefix }}"> {% for subform in formset.forms %} <table> {{ subform.as_table }} </table> {% endfor %} {{ formset.management_form }} </div> {% endfor %} <input type="submit" value="Save new tool calibration"> </form> {% endblock %} Any and all help is appreciated!

Read this post in context »

Django Query Relations Behaviour

Posted on April 24, 2014 at 6:37 PM by Stack Overflow RSS

Okay is there a way to filter the objects so that you only get records with associated records. Is it a right join maybe? Basically, I only want to select records from A that B has a foreign key for whilst using a WHERE clause on B. Am i making it sound more complicated than it is? I don't need the records from B, just the A; maybe a subquery? I'm relatively new to Django's queries and i've only just done some of the simpler stuff.

Read this post in context »

getting module error in django FW

Posted on April 24, 2014 at 6:36 PM by Stack Overflow RSS

getting following error of opening url 127.0.0.1:8000 which says no module go."jaiho.apps.homepage.urls" but my dir structure has that module present No idea how the flow in django. mkp@mkp-Vostro-2520:~**/Desktop/DJFW/jaiho/jaiho/apps/homepage**$ ls -ltr total 28 -rwxr-xr-x 1 mkp mkp 0 Apr 24 23:18 __init__.py -rwxr-xr-x 1 mkp mkp 57 Apr 24 23:18 models.py -rwxr-xr-x 1 mkp mkp 60 Apr 24 23:18 tests.py -rwxr-xr-x 1 mkp mkp 63 Apr 24 23:18 admin.py -rwxr-xr-x 1 mkp mkp 158 Apr 24 23:30 views.py -rw-r--r-- 1 mkp mkp 147 Apr 24 23:32 __init__.pyc -rw-rw-r-- 1 mkp mkp 335 Apr 24 23:55 urls.pyc -rwxrwxr-x 1 mkp mkp 115 Apr 24 23:56 urls.py mkp@mkp-Vostro-2520:~/Desktop/DJFW/jaiho/jaiho/apps/homepage$ pwd /home/mkp/Desktop/DJFW/jaiho/jaiho/apps/homepage content of urls.py from django.conf.urls import * urlspatterns = patterns('', (r'^$','jaiho.jaiho.apps.homepage.views.index'), ) Error > ImportError at / No module named jaiho.apps.homepage.urls Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.6.2 Exception Type: ImportError Exception Value: No module named jaiho.apps.homepage.urls Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/importlib.py in import_module, line 40 Python Executable: /usr/bin/python Python Version: 2.7.3 Python Path: ['/home/mkp/Desktop/DJFW/jaiho', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] Server time: Thu, 24 Apr 2014 18:29:59 +0000

Read this post in context »

Saving data to database using forms django

Posted on April 24, 2014 at 6:28 PM by Stack Overflow RSS

Model class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() Form from django import forms class ContactForm(forms.Form): name = forms.CharField() address = forms.CharField() city = forms.CharField() state_province = forms.CharField() country = forms.CharField() website = forms.URLField() And view def test(request): if request.method=='POST': form = ContactForm(request.POST) if form.is_valid(): print form.cleaned_data p=Publisher() p.name=form.cleaned_data.get('name') p.address=form.cleaned_data.get('address') p.city=form.cleaned_data.get('city') p.state_province=form.cleaned_data.get('state_province') p.country=form.cleaned_data.get('country') p.website=form.cleaned_data.get('website') p.save() return HttpResponse("Done") else: form = ContactForm() return render(request, 'contact_form.html', {'form': form}) I am saving the data to the database when the submitted form is valid. But what I did is extracting each field from dictionary form.cleaned_data and then assigned it to instance of Publisher object manually for e.g p.name=form.cleaned_data.get('name') My question is that is there is any way to assign the form.cleaned_data dictionary to Publisher object. In short can i do it like , p=Publisher() p=form.cleaned_data p.save()

Read this post in context »

Keep older value of a dom element

Posted on April 24, 2014 at 6:24 PM by Stack Overflow RSS

I have the following html that is rendered by a django. Here is an instance of how it could be html <div class="treatment container"> <div class="row"> <div class="treatment-phrase col-md-4"> <form action="" method="post" class="inline"> <input type="hidden" name="csrfmiddlewaretoken" value="hbdqhZuNYn83WvZg110TCiENekDqWjUD"> <p class="text-info" data-id="2">TR - 35</p> <button class="btn btn-default btn-sm edit-phrase">Edit</button> </form> </div> </div> <div class="row"> <div class="treatment-phrase col-md-4"> <form action="" method="post" class="inline"> <input type="hidden" name="csrfmiddlewaretoken" value="hbdqhZuNYn83WvZg110TCiENekDqWjUD"> <p class="text-info" data-id="3">TR - 34</p> <button class="btn btn-default btn-sm edit-phrase">Edit</button> </form> </div> </div> </div> The css .panel-body { padding:0px; } .panel-body table tr td { padding-left: 15px } .panel-body .table {margin-bottom: 0px; } .panel-group, .settings{ padding-top:2em; } .diagnosis-phrase, .treatment-phrase, .category-item{ padding-bottom: 1em; padding-top: 0.5em; border: 1px solid black; margin-bottom: 0.5em; } .diagnosis-phrase input[type="text"], .treatment-phrase input[type="text"], .category-item input[type="text"]{ margin-bottom:0.5em; } .category-item p{ padding-left: 0.5em; padding-bottom:0.3em; border-radius:0.5em; width:50%; } and js $("#save-phrase").on('click', function (event) { form = $("form#add-phrase") form.submit(); }); $(".edit-phrase").on('click', function(event){ event.preventDefault(); var inputBox; var form = $(this).parent('form'); var p = $(this).siblings('p'); var input = '<input type="text" data-id="'+p.attr('data-id')+'" class="form-control input-sm col-md-4" id="id_phrase" name="phrase" value="'+p.text()+'">'; console.log(input); if($(this).text() === 'Edit'){ p.replaceWith(input); form.append('<button name="delete" class="btn btn-default btn-sm">Delete</button>'); form.append('<input type="submit" name="submit" class="btn btn-default btn-sm" value="Save">'); $(this).text('Cancel'); }else{ console.log(p); inputBox = $(this).siblings('input#id_phrase'); console.log(inputBox); p.text(inputBox.val()); inputBox.replaceWith('<p class="text-info" data-id="'+inputBox.attr('data-id')+'">'+inputBox.val()+'</p>'); $(this).siblings('input[type="submit"]').remove(); $(this).siblings('button').remove(); $(this).text('Edit'); } }); What ...

Read this post in context »

Django Extend Content perserving old Get Results

Posted on April 24, 2014 at 6:21 PM by Stack Overflow RSS

I am proficient with python but quite new to django and html. What is the best method to include additional data while keeping data that was previously queried for displayed on the same page? Some of the sql data involves large datasets being manipulated in python, so I would rather not recalculate everything for a new view, when I am only intending to reuse the old view with 1 extra method/query. Thanks for the help. This is a very stripped down template for exampleurl/experiment1/ to illustrate my problem. {% extends "base.html" %} {% load poll_extras %} {% block content %} {% block info %} #(loaded on default) {% endblock %} {% block chart %} #(loaded with default values) {% endblock %} {% block addinfo1 %} <select class="selectpicker" data-style="btn-info" onchange="if (this.value) window.location.href = this.value" method="get"> <option value="?addinfo1=X">additional data X</option> <option value="?addinfo1=Y">addtional data Y</option> #(etc.) </select> {{if addinfo1}} #(nothing loaded by default) #(display table) {% endblock %} {% block addinfo 2 %} <form class="addinfo search" action="/search/" role="search" method="get"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" name=q> </div> </form> {{if search results }} #(nothing loaded by default) {% endblock %} {% endblock %} I.e. Someone loads experiment 1, selects addinfo=X and then searches in ...

Read this post in context »

'ShortWriteForm' object has no attribute 'request'

Posted on April 24, 2014 at 6:00 PM by Stack Overflow RSS

I have a problem about attributeError in django: from postman.forms import BaseWriteForm from postman.fields import CommaSeparatedUserField class ShortWriteForm(BaseWriteForm): recipients = CommaSeparatedUserField( label=(_("Recipients"), _("Recipient")), help_text='', widget=forms.HiddenInput() ) subject = forms.CharField( initial="Kurze Nachricht", widget=forms.HiddenInput() ) image = forms.ImageField( widget=forms.ClearableFileInput(attrs={'class': 'hidden'}), required=False ) class Meta(BaseWriteForm.Meta): fields = ('recipients', 'subject', 'body', 'image') def save(self, *args, **kwargs): recipient = self.cleaned_data["recipients"][0] is_succesful = ( super(ShortWriteForm,self).save( recipient=recipient,*args, **kwargs)) if self.request and self.request.FILES: att_form = AttachmentImageForm( self.instance, self.request.POST, self.request.FILES) if att_form.is_valid(): att_form.save() return is_succesful class ShortWriteView(postman_views.riteView): def get_initial(self): initial = super(ShortWriteView, self).get_initial() recipient = self.kwargs.get('recipients') self.recipient = get_object_or_404(User, username=recipient) return initial def get_context_data(self, **kwargs): context = super(ShortWriteView, self).get_context_data(**kwargs) context['recipient'] = self.recipient return context And I get this error: Exception Value: 'ShortWriteForm' object has no attribute 'request'

Read this post in context »

django-admin.py startproject errors: "could not import settings" "is it on sys.path" & more

Posted on April 24, 2014 at 5:52 PM by Stack Overflow RSS

Trying command django-admin.py startproject projectname and I get the following output: Traceback (most recent call last): File "/home/rachelbuntu/Envs/knenv/bin/django-admin.py", line 5, in <module> management.execute_from_command_line() File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command commands = get_commands() File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 107, in get_commands apps = settings.INSTALLED_APPS File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 54, in __getattr__ self._setup(name) File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 49, in _setup self._wrapped = Settings(settings_module) File "/home/rachelbuntu/Envs/knenv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 132, in __init__ % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'project_config.settings.local' (Is it on sys.path? Is there an import error in the settings file?): No module named project_config.settings.local I've also tried python long/path/to/django-admin.py startproject projectname. I searched for the phrase "is it on sys.path" and found something nearly related, the problem here: Error: Could not import settings 'mysite.settings' after setting up virtualenv for Django , but a) I'm on ubuntu, not fedora if that makes a difference, and b) I can't quite parse the solution on there. tried the PYTHONPATH fix to my working dir & that did not help. I also tried making a specific bash file just for this virtualenv to use according to http://www.jeffknupp.com/blog/2013/12/18/starting-a-django-16-project-the-right-way/ as it seems like this is a PATH ...

Read this post in context »

django tastypie imports for other files

Posted on April 24, 2014 at 5:50 PM by Stack Overflow RSS

I an new to django i build a web service for image upload given there Django-Tasypie image upload example with JQuery now i want to do processing on my image which has been uploaded in my media folder by importing other py files but my api.py do not allow any import of other files it gives me error how can i do this can any body help ???

Read this post in context »

invalid syntax (views.py, line 10)

Posted on April 24, 2014 at 5:38 PM by Stack Overflow RSS

I am trying to call this to display a page def index(request): response = HttpResponse() clist = dv.objects.order_by('source').distinct('category') for c in clist: link = "<a href=\"dv/%s\">" % (c.category) response.write("<li>%s</a></li>" % (link, c.category) ) but i am getting an error on for c in clist: what am i missing.

Read this post in context »