Search Results

Search found 3555 results on 143 pages for 'django reinhardt'.

Page 89/143 | < Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >

  • Extending a form field to add new validations.

    - by duallain
    I've written an app that uses forms to collect information that is then sent in an email. Many of these forms have a filefield used to attach files to the email. I'd like to validate two things, the size of the file (to ensure the emails are accepted by our mail server. I'd also like to check the file extension, to discourage attaching file types not useable for our users. (This is the python class I'm trying to extend) class FileField(Field): widget = FileInput default_error_messages = { 'invalid': _(u"No file was submitted. Check the encoding type on the form."), 'missing': _(u"No file was submitted."), 'empty': _(u"The submitted file is empty."), 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'), } def __init__(self, *args, **kwargs): self.max_length = kwargs.pop('max_length', None) super(FileField, self).__init__(*args, **kwargs) def clean(self, data, initial=None): super(FileField, self).clean(initial or data) if not self.required and data in EMPTY_VALUES: return None elif not data and initial: return initial # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages['invalid']) if self.max_length is not None and len(file_name) > self.max_length: error_values = {'max': self.max_length, 'length': len(file_name)} raise ValidationError(self.error_messages['max_length'] % error_values) if not file_name: raise ValidationError(self.error_messages['invalid']) if not file_size: raise ValidationError(self.error_messages['empty']) return data

    Read the article

  • Get value of selected field from a dropdown list

    - by 47
    I have this class in my model: class ServiceCharge(models.Model): name = models.CharField(max_length=30) amount = models.PositiveIntegerField() extends_membership = models.BooleanField(default=False) def __unicode__(self): return str(self.name) What I want to have is in the form for charging users a service charge, when a charge is selected from the dropdown menu, the two values for amount and extends_membership are updated on the form depending on the selected charge. My forms.py: class vModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s" % obj.name class PayServiceChargeForm(PaymentsForm): service_charge = vModelChoiceField(queryset=ServiceCharge.objects.all(), empty_label=" ") class Meta(PaymentsForm.Meta): exclude = ('member', 'payment_type', 'transacted_by', 'description') Then the form template: <table border="0"> <tr> <td><strong>{% trans "Service Charge" %}</strong></td> <td>{{ form.service_charge }}</td> <td><strong>{% trans "Extends Membership" %}</strong></td> <td>{{ form.extends_membership }}</td> </tr> <tr> <td valign="top"><strong>{% trans "Expiry Date" %}</strong></td> <td valign="top">{{ form.expiry_date }}</td> <td valign="top"><strong>{% trans "Amount" %}</strong></td> <td>{{ form.amount }}</td> </tr> </table> I was trying out some jQuery but I got stuck after getting the currently selected charge: <script type="text/javascript"> $(document).ready(function(){ $("#id_service_charge").change(onSelectChange); }); function onSelectChange(){ var selected = $("#id_service_charge option:selected"); var output = ""; if(selected.val() != 0){ charge = selected.val(); .... (update values) .... } } </script>

    Read the article

  • passing an argument to a custom save() method

    - by Nick
    How do I pass an argument to my custom save method, preserving proper *args, **kwargs for passing to te super method? I was trying something like: form.save(my_value) and def save(self, my_value=None, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) print my_value But this doesn't seem to work. What am I doing wrong?

    Read the article

  • Post and Comment with the same Model.

    - by xRobot
    I have created a simple project where everyone can create one or more Blog. I want to use this models for Post and for Comment: class Post_comment(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(_('object ID')) content_object = generic.GenericForeignKey() # Hierarchy Field parent = models.ForeignKey('self', null=True, blank=True, default=None, related_name='children') # User Field user = models.ForeignKey(User) # Date Fields date_submitted = models.DateTimeField(_('date/time submitted'), default = datetime.now) date_modified = models.DateTimeField(_('date/time modified'), default = datetime.now) title = models.CharField(_('title'), max_length=60, blank=True, null=True) post_comment = models.TextField(_('post_comment')) markup = models.IntegerField(choices=MARKUP_CHOICES, default=DEFAULT_MARKUP, null=True, blank=True) if it is a comment the parent is not null. So in most case the text field will contain a little bit of text. Can I use this model for both Post and Comment ?

    Read the article

  • How to design model for multi-tiered data?

    - by Chris
    Say I have three types of object: Area, Subarea and Topic. I want to be able to display an Area, which is just a list of Subareas and the Topics contained in those Subareas. I never want to be able to display Subareas separately - they're just for breaking up the Topics. Topics can, however, appear in multiple Areas (but probably under the same Subarea). How would I design a model for this? I could use ForeignKey from Topic to Subarea and from Subarea to Area, but it seems unnecessarily complex given that I never want to interact with subareas themselves. Also, none of these objects are ever altered or added to by the user. They're just for me to represent information. Maybe there is a better way to represent it all?

    Read the article

  • URL redirection if wrong url

    - by xRobot
    I have this method in my book model: def get_absolute_url(self): return "/book/%s/%s/%i/%i/" % ( self.book_title, self.book_editor, self.book_pages, self.id) So the urls of each book are like this: example.com/book/the-bible/gesu-crist/938/12/ I want that if there is an error in the url, then I get redirected to the real url by using book.id in the end of the url. For example if I go to: example.com/book/A-bible/gesu-crist/938/12/ the I will get redirected to: example.com/book/the-bible/gesu-crist/938/12/ How can I do that ?

    Read the article

  • ManyToManyField error when having recursive structure. How to solve it?

    - by luc
    Hello, I have the following table in the model with a recursive structure (a page can have children pages) class DynamicPage(models.Model): name = models.CharField("Titre",max_length=200) parent = models.ForeignKey('self',null=True,blank=True) I want to create another table with manytomany relation with this one: class UserMessage(models.Model): name = models.CharField("Nom", max_length=100) page = models.ManyToManyField(DynamicPage) The generated SQL creates the following constraint: ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`); I would like to have the ManyToMany with the page itself (the id) and not with the parent field. How to modify the model to make the constraint using the id and not the parent? Thanks in advance

    Read the article

  • How to set title and class in the HTML for the options of a ModelChoiceField?

    - by celopes
    I have a model class MyModel(models.Model): name = models.CharField(max_length=80, unique=True) parent = models.ForeignKey('self', null=True, blank=True) I want to render a ModelChoiceField for that model that looks like: <select name="mymodel" id="id_mymodel"> <option value="1" title="Value 1" class="">Value 1</option> <option value="2" title="Value 2" class="Value 1">Value 2</option> </select> The differences between this output and the default output for a ModelChoiceField are the title and class elements in the OPTION tag. They don't exist in ModelChoiceField's default output. For my purposes: The title element is supposed to be the Option Name. The class element is supposed to be self.parent.name. (this is my problem) So, in the HTML snippet above, Value 1 has no parent and Value 2 has a parent of Value 1. What is the best mechanism to change ModelChoiceField's default HTML output? EDIT: I understand how to create a new Widget for rendering HTML. The problem is how to render a value from the underlying model in each of the options.

    Read the article

  • How to save links in TextFields

    - by xRobot
    I have a simple Blog model with a TextField. What is the best way to save links in the TextField ? 1) Saving link in the database in this form: http://www.example.com and then using some filter in the template to trasform it in form: <a rel="nofollow" href="http://www.example.com>http://www.example.com</a> 2) Saving link in the database directly in this form: <a rel="nofollow" href="http://www.example.com>http://www.example.com</a>

    Read the article

  • Best Practice for Context Processors vs. Template Tags?

    - by mawimawi
    In which cases is it better to create template tags (and load them into the template), than creating a context processor (which fills the request automatically)? e.g. I have a dynamic menu that has to be included into all templates, so I'm putting it into my base.html. What is the preferred usage: context processor or custom template tag? And why?

    Read the article

  • Getting the last member of a group on an intermediary M2M

    - by rh0dium
    If we look at the existing docs, what is the best way to get the last member added? This is similar to this but what I want to do is to be able to do this. group = Group.objects.get(id=1) group.get_last_member_added() #This is by ('-date_added') <Person: FOO> I think the best way is through a manager but how do you do this on an intermediary model? class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64)

    Read the article

  • What is an alternative to eval in this situation?

    - by CppLearner
    Many of my view functions do similar things. For the most part, they reverse to a different views upon clicking a button / a text link. So I wrote a helper function render_reverse def render_reverse(f, args): # args are all string type return eval('reverse(' + f + ', ' + args + ')' ) eval is a bad practice, and is pretty slow. It takes 3 seconds to start redirecting, whereas calling reverse directly takes less than 1 second to start redirecting. What alternative do I have? By the way, the function above doesn't work properly. I was modelling after this line (which works) eval('reverse("homepage", args=["abcdefg"])') Thanks.

    Read the article

  • Select_related() backwards relation - auto model population

    - by Nick
    Hi. If I have the following model: class Contact(models.Model) name = models.CharField(max_length=100) ... class ContactAddress(models.Model) line1 = models.CharField(max_length=100) line2 = models.CharField(max_length=100) ... contact = models.ForeignKey(Contact) I now want to grab all Contacts and for the address to be auto populated. What would be the best way to do this? The only way I have found so far is to filter out the Contacts I want and loop around each contact and assign this to Contact.addresses. I then use this for outputting each Contacts address within a template. Is there a better way of doing this? Select_related() almost does what I want, but doesn't seem to be able to work in the opposite direction. Thanks in advance for your help on this one!

    Read the article

  • What are the requirements for gettings django translations to work?

    - by Espen Christensen
    Hi, I am hosting several djangosites on a CentOS 5 box. But I'm having difficulties with translations. So first i had to upgrade the gettext package from 0.14 to 0.16, but that didn't help. Now i can make and compile tranlsations files with the managment commands, but the translations does not show. I am sure that the translation files are located at the right place since they work with the same setup on a local installation, and django's own translation files does not work. (e.g the admin is not translated). What could i be missing in my server setup that makes this happen?

    Read the article

  • Painless deployment of a Django app (port from Drupal). Do I have to switch to a VPS?

    - by Monden
    I'm about to complete porting my Drupal based community site to Django. My Drupal site is hosted at a shared hosting (Dreamhost) for last 4 years, and stability & performance has been satisfactory. The site gets around 5k unique visitors with 70-80k page views a day. This will be my first deployment of a Django application and I'm not comfortable with managing my own VPS. I use Ubuntu as a dev. server, but I don't have experience with it at the production env. I have an unrelated internal CRM app (Django) that I host with Webfaction. However security and performance isn't an issue as it's only accessed by 5 people. Unfortunately, I don't have much time to learn and maintain a VPS at this moment. I would like to know if I can host a site with this much traffic at Webfaction's shared environment? How would performance differ in comparison to Linode or Slicehost? Google AppEngine isn't an option at the moment as I'll be using my current Postgresql database.

    Read the article

  • How to run django on localhost with nginx and uwsgi?

    - by user2426362
    How to run django on localhost with nginx and uwsgi? This im my config but not works. nginx: server { listen 80; server_name localhost; access_log /var/log/nginx/localhost_access.log; error_log /var/log/nginx/localhost_error.log; location / { uwsgi_pass unix:///tmp/localhost.sock; include uwsgi_params; } location /media/ { alias /home/user/projects/zt/myproject/myproject/media/; } location /static/ { alias /home/user/projects/zt/myproject/myproject/static/; } } uwsgi: [uwsgi] vhost = true plugins = python socket = /tmp/localhost.sock master = true enable-threads = true processes = 2 wsgi-file = /home/user/projects/zt/myproject/myproject/wsgi.py virtualenv = /home/user/projects/zt chdir = /home/user/projects/zt/myproject touch-reload = /home/user/projects/zt/myproject/reload This config work on my ubuntu server with normal domain (not localhost) but on localhost not working. If I run localhost in web browser I have Welcome to nginx!

    Read the article

  • Fulltext search for django : Mysql not so bad ? (vs sphinx, xapian)

    - by Eric
    I am studying fulltext search engines for django. It must be simple to install, fast indexing, fast index update, not blocking while indexing, fast search. After reading many web pages, I put in short list : Mysql MYISAM fulltext, djapian/python-xapian, and django-sphinx I did not choose lucene because it seems complex, nor haystack as it has less features than djapian/django-sphinx (like fields weighting). Then I made some benchmarks, to do so, I collected many free books on the net to generate a database table with 1 485 000 records (id,title,body), each record is about 600 bytes long. From the database, I also generated a list of 100 000 existing words and shuffled them to create a search list. For the tests, I made 2 runs on my laptop (4Go RAM, Dual core 2.0Ghz): the first one, just after a server reboot to clear all caches, the second is done juste after in order to test how good are cached results. Here are the "home made" benchmark results : 1485000 records with Title (150 bytes) and body (450 bytes) Mysql 5.0.75/Ubuntu 9.04 Fulltext : ========================================================================== Full indexing : 7m14.146s 1 thread, 1000 searchs with single word randomly taken from database : First run : 0:01:11.553524 next run : 0:00:00.168508 Mysql 5.5.4 m3/Ubuntu 9.04 Fulltext : ========================================================================== Full indexing : 6m08.154s 1 thread, 1000 searchs with single word randomly taken from database : First run : 0:01:11.553524 next run : 0:00:00.168508 1 thread, 100000 searchs with single word randomly taken from database : First run : 9m09s next run : 5m38s 1 thread, 10000 random strings (random strings should not be found in database) : just after the 100000 search test : 0:00:15.007353 1 thread, boolean search : 1000 x (+word1 +word2) First run : 0:00:21.205404 next run : 0:00:00.145098 Djapian Fulltext : ========================================================================== Full indexing : 84m7.601s 1 thread, 1000 searchs with single word randomly taken from database with prefetch : First run : 0:02:28.085680 next run : 0:00:14.300236 python-xapian Fulltext : ========================================================================== 1 thread, 1000 searchs with single word randomly taken from database : First run : 0:01:26.402084 next run : 0:00:00.695092 django-sphinx Fulltext : ========================================================================== Full indexing : 1m25.957s 1 thread, 1000 searchs with single word randomly taken from database : First run : 0:01:30.073001 next run : 0:00:05.203294 1 thread, 100000 searchs with single word randomly taken from database : First run : 12m48s next run : 9m45s 1 thread, 10000 random strings (random strings should not be found in database) : just after the 100000 search test : 0:00:23.535319 1 thread, boolean search : 1000 x (word1 word2) First run : 0:00:20.856486 next run : 0:00:03.005416 As you can see, Mysql is not so bad at all for fulltext search. In addition, its query cache is very efficient. Mysql seems to me a good choice as there is nothing to install (I need just to write a small script to synchronize an Innodb production table to a MyISAM search table) and as I do not really need advanced search feature like stemming etc... Here is the question : What do you think about Mysql fulltext search engine vs sphinx and xapian ?

    Read the article

  • Setting up Django on an internal server (os.environ() not working as expected?)

    - by monkut
    I'm trying to setup Django on an internal company server. (No external connection to the Internet.) Looking over the server setup documentation it appears that the "Running Django on a shared-hosting provider with Apache" method seems to be the most-likely to work in this situation. Here's the server information: Can't install mod_python no root access Server is SunOs 5.6 Python 2.5 Apache/2.0.46 I've installed Django (and flup) using the --prefix option (reading again I probably should've used --home, but at the moment it doesn't seem to matter) I've added the .htaccess file and mysite.fcgi file to my root web directory as mentioned here. When I run the mysite.fcgi script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser. It seems that it may be a problem with the PYTHONPATH setting since I'm using the prefix option. I've noticed that if I run mysite.fcgi from the command-line without setting the PYTHONPATH enviornment variable it throws the following error: prompt$ python2.5 mysite.fcgi ERROR: No module named flup Unable to load the flup package. In order to run django as a FastCGI application, you will need to get flup from http://www.saddi.com/software/flup/ If you've already installed flup, then make sure you have it in your PYTHONPATH. I've added sys.path.append(prefixpath) and os.environ['PYTHONPATH'] = prefixpath to mysite.fcgi, but if I set the enviornment variable to be empty on the command-line then run mysite.fcgi, I still get the above error. Here are some command-line results: >>> os.environ['PYTHONPATH'] = 'Null' >>> >>> os.system('echo $PYTHONPATH') Null >>> os.environ['PYTHONPATH'] = '/prefix/path' >>> >>> os.system('echo $PYTHONPATH') /prefix/path >>> exit() prompt$ echo $PYTHONPATH Null It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by os.environ['key'] = value (?) at least when installing via the --prefix option. I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup: import sys; sys.__plen = len(sys.path) ./setuptools-0.6c6-py2.5.egg ./flup-1.0.1-py2.5.egg import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy s.path[p:p]=new; sys.__egginsert = p+len(new) It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?

    Read the article

  • How do I construct a Django reverse/url using query args?

    - by Andrew Dalke
    I have URLs like http://example.com/depict?smiles=CO&width=200&height=200 (and with several other optional arguments) My urls.py contains: urlpatterns = patterns('', (r'^$', 'cansmi.index'), (r'^cansmi$', 'cansmi.cansmi'), url(r'^depict$', cyclops.django.depict, name="cyclops-depict"), I can go to that URL and get the 200x200 PNG that was constructed, so I know that part works. In my template from the "cansmi.cansmi" response I want to construct a URL for the named template "cyclops-depict" given some query parameters. I thought I could do {% url cyclops-depict smiles=input_smiles width=200 height=200 %} where "input_smiles" is an input to the template via a form submission. In this case it's the string "CO" and I thought it would create a URL like the one at top. This template fails with a TemplateSyntaxError: Caught an exception while rendering: Reverse for 'cyclops-depict' with arguments '()' and keyword arguments '{'smiles': u'CO', 'height': 200, 'width': 200}' not found. This is a rather common error message both here on StackOverflow and elsewhere. In every case I found, people were using them with parameters in the URL path regexp, which is not the case I have where the parameters go into the query. That means I'm doing it wrong. How do I do it right? That is, I want to construct the full URL, including path and query parameters, using something in the template. For reference, % python manage.py shell Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.urlresolvers import reverse >>> reverse("cyclops-depict", kwargs=dict()) '/depict' >>> reverse("cyclops-depict", kwargs=dict(smiles="CO")) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Python/2.6/site-packages/django/core/urlresolvers.py", line 356, in reverse *args, **kwargs))) File "/Library/Python/2.6/site-packages/django/core/urlresolvers.py", line 302, in reverse "arguments '%s' not found." % (lookup_view_s, args, kwargs)) NoReverseMatch: Reverse for 'cyclops-depict' with arguments '()' and keyword arguments '{'smiles': 'CO'}' not found.

    Read the article

  • How to call bash process from within django / wsgi?

    - by chang
    I'm using mod_wsgi apache2 adapter for a django site and I like to call some bash process within a view, using the usual ... p = subprocess.Popen("/home/example.com/restart-tomcat.sh", shell=True) sts = os.waitpid(p.pid, 0)[1] ... This code works perfectly from within a usual python shell but does nothing (I can trace right now) when called within django. Am I missing some wsgi constraints? The script has 755 perms, so it should be executable. Thanks.

    Read the article

  • How can I add dynamic field in the model in django ?

    - by Wu Jie
    Hello, I'm using django to create a application download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would like the user can admin the model by using an add button to add the download link with a download version. But I don't know how to do this in django.

    Read the article

  • How do I get the number of objects per day using django?

    - by Keith
    I have a django model with a DateTimeField. class Point(models.Model): somedata = models.CharField(max_length=256) time = models.DateTimeField() I want to get a count of the number of these objects for each day. I can do this with the following SQL query, but don't know how to do it through django. SELECT DATE(`time`), Count(*) FROM `app_point` GROUP BY DATE(`time`) Being able to restrict the results to a date range would also be good.

    Read the article

  • What is the best Django syncdb crash debugging technique ?

    - by user367752
    What is the best Django syncdb crash debugging technique ? I've previously asked a question about a problem with manage.py syncdb returning an exception and the answer was that the app has a wrong import. http://stackoverflow.com/questions/2734721/django-manage-py-syncdb-not-working I'd like to know the technique used to find the place where there is a wrong import. I tried ./manage.py syncdb --verbosity=2 but I didn't get any more information that way.

    Read the article

< Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >