Search Results

Search found 8610 results on 345 pages for 'django filter'.

Page 10/345 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Overwrite clean method in Django Custom Forms

    - by John
    Hi I have wrote a custom widget class AutoCompleteWidget(widgets.TextInput): """ widget to show an autocomplete box which returns a list on nodes available to be tagged """ def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, name=name) if not self.attrs.has_key('id'): final_attrs['id'] = 'id_%s' % name if not value: value = '[]' jquery = u""" <script type="text/javascript"> $("#%s").tokenInput('%s', { hintText: "Enter the word", noResultsText: "No results", prePopulate: %s, searchingText: "Searching..." }); $("body").focus(); </script> """ % (final_attrs['id'], reverse('ajax_autocomplete'), value) output = super(AutoTagWidget, self).render(name, "", attrs) return output + mark_safe(jquery) class MyForm(forms.Form): AutoComplete = forms.CharField(widget=AutoCompleteWidget) this widget uses a jquery function which autocompletes a word based on entries from the database. You can preset its initial values by setting prePopulate to a json string in the form ['name': 'some name', 'id': 'some id'] I do this by setting the inital value of the form field to this json string jquery_string = ['name': 'some name', 'id': 'some id'] form = MyForm(initial={'AutoComplete':jquery_string}) When submitting the form the the value of AutoComplete is returned as a comma seperated list of the selected ids e.g. 12,45,43,66 which if what I want. However if there is an error in the form, for example a required field has not been entered the value of the AutoComplete field is now 12,45,43,66 and not the json string which it requires. What is the best way to solve this. I was thinking about overwriting the clean method in the form class but I'm not sure how to find out if any other element has returned an error. e.g. if forms.errors form.cleaned_date['autocomplete'] = json string return form.cleaned_data Thanks

    Read the article

  • django admin: Add a "remove file" field for Image- or FileFields

    - by w-
    I was hunting around the net for a way to easily allow users to blank out imagefield/filefields they have set in the admin. I found this http://www.djangosnippets.org/snippets/894/ What was really interesting to me here was the code posted in the comment by rfugger remove_the_file = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_the_file'): object.the_file = '' return object When i try to use this in my own form I basically added this to my admin.py which already had a BlahAdmin class BlahModelForm(forms.ModelForm): class Meta: model = Blah remove_img01 = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_img01'): object.img01 = '' return object when i run it I get this error maximum recursion depth exceeded while calling a Python object at this line object = super(self.__class__, self).save(*args, **kwargs) When i think about it for a bit, it seems obvious that it is just infinitely calling itself causing the error. My problem is i can't figure out what is the correct way i should be doing this. Any suggestions? thanks

    Read the article

  • int() error in django views

    - by Hulk
    def displaydata(request): response_dict = {} offset = int(request.GET.get('iDisplayStart')) There is an error as, int() argument must be a string or a number at the above said line (i.e,`request.GET.get('iDisplayStart')) And in the template code, $(document).ready(function() { $.ajaxSetup({ cache: false }); oTable = $('#qp_table').dataTable( { "aoColumns": [ {"sWidth": "5%" }, {"sWidth": "35%" }, {"sWidth": "27%" }, {"sWidth": "15%"}, { "bSortable": false, "sWidth": "0%"}, {"bSortable": false, "sWidth": "0%"} ], "aaSorting": [[0, 'asc']], "bProcessing": true, "bServerSide": true, "sAjaxSource": "/diaplaydata/", "bJQueryUI": true, "sPaginationType": "full_numbers", "bFilter": false, "oLanguage" : { "sZeroRecords": "No data found", "sProcessing" : "Fetching Data" } });

    Read the article

  • django templates array assignment

    - by Hulk
    The following is in views: rows=query.evaluation_set.all() row_arr = [] for row in rows: row_arr.append(row.row_details) dict.update({'row_arr' : row_arr ,'col_arr' : col_arr}) return render_to_response('valuemart/show.html',context_instance=RequestContext(request,{'dict': dict})) How to extract the row_Arr array in the templates in javascript and list out all its values.row_Arr contains data of a column <script> var row_arr = '{{dict.row_arr}}'; //extract values here </script> Thanks..

    Read the article

  • Django syncdb error

    - by Hulk
    /mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... class Details(): ...... When DB i synced there is an error saying Error: One or more models did not validate: project4: Accessor for field 'detail' clashes with related field . Add a related_name argument to the definition for 'detail'. How can this be solved.. thanks..

    Read the article

  • queries in django

    - by Hulk
    How to query Employee to get all the address related to the employee, Employee.Add.all() doe not work.. class Employee(): Add = models.ManyToManyField(Address) parent = models.ManyToManyField(Parent, blank=True, null=True) class Address(models.Model): address_emp = models.CharField(max_length=512) description = models.TextField() def __unicode__(self): return self.name()

    Read the article

  • Django and ImageField Question

    - by Hellnar
    Hello I have a such model: Foo (models.Model): slug = models.SlugField(unique=True) image = models.ImageField(upload_to='uploads/') I want to do two things with this: First of all, I want my image to be forced to resize to a specific width and height after the upload. I have tried this reading the documentation but seems to getting error: image = models.ImageField(upload_to='uploads/', height_field=258, width_field=425) Secondly, when adding an item via admin panel, I want my image's file name to be renamed as same as slug, if any issue arises (like if such named image already exists, add "_" to the end as it used to do. IE: My slug is i-love-you-guys , uploaded image such have i-love-you-guys.png at the end.

    Read the article

  • Django and floatformat tag

    - by Hellnar
    Hello, I want to modify / change the way the floatformat works. By default it changes the input decimal as such: {{ 1.00|floatformat }} -> 1 {{ 1.50|floatformat }} -> 1.5 {{ 1.53|floatformat }} -> 1.53 I want to change this abit as such: If there is a floating part, it should keep the first 2 floating digits. If no floating (which means .00) it should simply cut out the floating part. IE: {{ 1.00|floatformat }} -> 1 {{ 1.50|floatformat }} -> 1.50 {{ 1.53|floatformat }} -> 1.53

    Read the article

  • Tricky model inheritance - Django

    - by RadiantHex
    Hi folks, I think this is a bit tricky, at least for me. :) So I have 4 models Person, Singer, Bassist and Ninja. Singer, Bassist and Ninja inherit from Person. The problem is that each Person can be any of its subclasses. e.g. A person can be a Singer and a Ninja. Another Person can be a Bassist and a Ninja. Another one can be all three. How should I organise my models? Help would be much appreciated!

    Read the article

  • Django Admin Form for Many to many relationship

    - by Anand
    I have a many to many relationship between 2 tables Users an Domains. I have defined this relationship in the Domains class. So in the admin interface I see the Users when I am viewing Domains. But I do not see Domains when I am viewing Users. How can I achieve this.

    Read the article

  • Filtering manager for django model, customized by user

    - by valya
    Hi there! I have a model, smth like this: class Action(models.Model): def can_be_applied(self, user): #whatever return True and I want to override its default Manager. But I don't know how to pass the current user variable to the manager, so I have to do smth like this: [act for act in Action.objects.all() if act.can_be_applied(current_user)] How do I get rid of it by just overriding the manager? Thanks.

    Read the article

  • django admin - adding fields on the fly

    - by Thomas
    Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. However I am kind of at a loss as to how to do this. What would be the best way to do this?

    Read the article

  • Django Custom Widget For ManyToMany field

    - by John
    Does anyone know of a widget that displays 2 select boxes. One shows a list of all object in a model and the other shows the objects which have been selected. The user can then select an object from the first list, click an button which moves it to the 'selected' list. Then when the form is saved the objects in the selected list are saved in the manytomany field. Thanks

    Read the article

  • Changing data in a django modelform

    - by Matt Hampel
    I get data in from POST and validate it via this standard snippet: entry_formset = EntryFormSet(request.POST, request.FILES, prefix='entries') if entry_formset.is_valid(): .... The EntryFormSet modelform overrides a foreign key field widget to present a text field. That way, the user can enter an existing key (suggested via an Ajax live search), or enter a new key, which will be seamlessly added. I use this try-except block to test if the object exists already, and if it doesn't, I add it. entity_name = request.POST['entries-0-entity'] try: entity = Entity.objects.get(name=entity_name) except Entity.DoesNotExist: entity = Entity(name=entity_name) entity.slug = slugify(entity.name) entity.save() However, I now need to get that entity back into the entry_formset. It thinks that entries-0-entity is a string (that's how it came in); how can I directly access that value of the entry_formset and get it to take the object reference instead?

    Read the article

  • Prepopulating inlines based on the parent model in the Django Admin

    - by Alasdair
    I have two models, Event and Series, where each Event belongs to a Series. Most of the time, an Event's start_time is the same as its Series' default_time. Here's a stripped down version of the models. #models.py class Series(models.Model): name = models.CharField(max_length=50) default_time = models.TimeField() class Event(models.Model): name = models.CharField(max_length=50) date = models.DateField() start_time = models.TimeField() series = models.ForeignKey(Series) I use inlines in the admin application, so that I can edit all the Events for a Series at once. If a series has already been created, I want to prepopulate the start_time for each inline Event with the Series' default_time. So far, I have created a model admin form for Event, and used the initial option to prepopulate the time field with a fixed time. #admin.py ... import datetime class OEventInlineAdminForm(forms.ModelForm): start_time = forms.TimeField(initial=datetime.time(18,30,00)) class Meta: model = OEvent class EventInline(admin.TabularInline): form = EventInlineAdminForm model = Event class SeriesAdmin(admin.ModelAdmin): inlines = [EventInline,] I am not sure how to proceed from here. Is it possible to extend the code, so that the initial value for the start_time field is the Series' default_time?

    Read the article

  • Django ModelForm for Many-to-Many fields

    - by theycallmemorty
    Consider the following models and form: class Pizza(models.Model): name = models.CharField(max_length=50) class Topping(models.Model): name = models.CharField(max_length=50) ison = models.ManyToManyField(Pizza, blank=True) class ToppingForm(forms.ModelForm): class Meta: model = Topping When you view the ToppingForm it lets you choose what pizzas the toppings go on and everything is just dandy. My questions is: How do I define a ModelForm for Pizza that lets me take advantage of the Many-to-Many relationship between Pizza and Topping and lets me choose what Toppings go on the Pizza?

    Read the article

  • [Django] Automatically Update Field when a Different Field is Changed

    - by Gordon
    I have a model with a bunch of different fields like first_name, last_name, etc. I also have fields first_name_ud, last_name_ud, etc. that correspond to the last updated date for the related fields (i.e. when first_name is modified, then first_name_ud is set to the current date). Is there a way to make this happen automatically or do I need to check what fields have changed each time I save an object and then update the related "_ud" fields. Thanks a lot!

    Read the article

  • Django Foreign key queries

    - by Hulk
    In the following model: class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() class options(models.Model): opt_details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() If there is a row in the database for table header as Id=1, title=value-mart , createdby=CEO How do i query criteria and options tables to get all the values related to header table id=1 Also can some one please suggest a good link for queries examples, Thanks..

    Read the article

  • Django - Form validation error

    - by Igor G.
    Hello, I have a model like this: class Entity(models.Model): entity_name = models.CharField(max_length=100) entity_id = models.CharField(max_length=30, primary_key=True) entity_parent = models.CharField(max_length=100, null=True) photo_id = models.CharField(max_length=100, null=True) username = models.CharField(max_length=100, null=True) date_matched_on = models.CharField(max_length=100, null=True) status = models.CharField(max_length=30, default="Checked In") def __unicode__(self): return self.entity_name class Meta: app_label = 'match' ordering = ('entity_name','date_matched_on') verbose_name_plural='Entities' I also have a view like this: def photo_match(request): ''' performs an update in the db when a user chooses a photo ''' form = EntityForm(request.POST) form.save() And my EntityForm looks like this: class EntityForm(ModelForm): class Meta: model = Entity My template's form returns a POST back to the view with the following values: {u'username': [u'admin'], u'entity_parent': [u'PERSON'], u'entity_id': [u'152097'], u'photo_id': [u'2200734'], u'entity_name': [u'A.J. McLean'], u'status': [u'Checked Out'], u'date_matched_on': [u'5/20/2010 10:57 AM']} And form.save() throws this error: Exception in photo_match: The Entity could not be changed because the data didn't validate. I have been trying to figure out why this is happening, but cannot pinpoint the exact problem. I can change my Entities in the admin interface just fine. If anybody has a clue about this I would greatly appreciate it! Thanks, Igor

    Read the article

  • Django javascript escape characters

    - by Hulk
    There is a text area in which the data is entered as, 122 //Enter button pushed Address Name //Enter button pushed 1 And the same is tored in the db.And the data is fetched in views and returned it to template as, <script> {% for i in dict.row_arr %} var ii= ('{{ i }}'); row_arr.push( ii ); {% endfor %} </script> Here there is an error as Error: unterminated string literal Line: 40, Column: 12 Source Code: var ii= ('1212 And when the html source shows up as, var ii= ('1212 1 21 11212121212'); row_arr.push( ii ); How should the escape function be applied here. Thanks..

    Read the article

  • Django: Overriding the clean() method in forms - question about raising errors

    - by Monika Sulik
    I've been doing things like this in the clean method: if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: raise forms.ValidationError('The type and organization do not match.') if self.cleaned_data['start'] > self.cleaned_data['end']: raise forms.ValidationError('The start date cannot be later than the end date.') But then that means that the form can only raise one of these errors at a time. Is there a way for the form to raise both of these errors? EDIT #1: Any solutions for the above are great, but would love something that would also work in a scenario like: if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: raise forms.ValidationError('The type and organization do not match.') if self.cleaned_data['start'] > self.cleaned_data['end']: raise forms.ValidationError('The start date cannot be later than the end date.') super(FooAddForm, self).clean() Where FooAddForm is a ModelForm and has unique constraints that might also cause errors. If anyone knows of something like that, that would be great...

    Read the article

  • Reorganizing many to many relationships in Django

    - by Galen
    I have a many to many relationship in my models and i'm trying to reorganize it on one of my pages. My site has videos. On each video's page i'm trying to list the actors that are in that video with links to each time they are in the video(the links will skip to that part of the video) Here's an illustration Flash Video embedded here Actors... Ted smith: 1:25, 5:30 jon jones: 5:00, 2:00 Here are the pertinent parts of my models class Video(models.Model): actor = models.ManyToManyField( Actor, through='Actor_Video' ) # more stuff removed class Actor_Video(models.Model): actor = models.ForeignKey( Actor ) video = models.ForeignKey( Video) time = models.IntegerField() Here's what my Actor_Video table looks like, maybe it will be easier to see what im doing id actor_id video_id time (in seconds) 1 1 3 34 2 1 3 90 i feel like i have to reorganize the info in my view, but i cant figure it out. It doesn't seem to be possible in the template using djangos orm. I've tried a couple things with creating dictionaries/lists but i've had no luck. Any help is appreciated. Thanks.

    Read the article

  • How to create a UserProfile form in Django with first_name, last_name modifications ?

    - by Natim
    If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it. However, I could not find any help on the django documentation or in the Django Book. When you want to do a UserProfile form in with Django Forms, you'd like to modify the profile fields as well as some User field. But there is no forms.UserProfileForm (yet?) ! How do you do that ?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >