Search Results

Search found 48 results on 2 pages for 'formset'.

Page 1/2 | 1 2  | Next Page >

  • Django formset doesn't validate

    - by tsoporan
    Hello, I am trying to save a formset but it seems to be bypassing is_valid() even though there are required fields. To test this I have a simple form: class AlbumForm(forms.Form): name = forms.CharField(required=True) The view: @login_required def add_album(request, artist): artist = Artist.objects.get(slug__iexact=artist) AlbumFormSet = formset_factory(AlbumForm) if request.method == 'POST': formset = AlbumFormSet(request.POST, request.FILES) if formset.is_valid(): return HttpResponse('worked') else: formset = AlbumFormSet() return render_to_response('submissions/addalbum.html', { 'artist': artist, 'formset': formset, }, context_instance=RequestContext(request)) And the template: <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} {% for form in formset.forms %} <ul class="addalbumlist"> {% for field in form %} <li> {{ field.label_tag }} {{ field }} {{ field.errors }} </li> {% endfor %} </ul> {% endfor %} <div class="inpwrap"> <input type="button" value="add another"> <input type="submit" value="add"> </div> </form> What ends up happening is I hit "add" without entering a name then HttpResponse('worked') get's called seemingly assuming it's a valid form. I might be missing something here, but I can't see what's wrong. What I want to happen is, just like any other form if the field is required to spit out an error if its not filled in. Any ideas?

    Read the article

  • Django formset unit test

    - by Py
    I can't running Unit Test with formset. I try to do a test: class NewClientTestCase(TestCase): def setUp(self): self.c = Client() def test_0_create_individual_with_same_adress(self): post_data = { 'ctype': User.CONTACT_INDIVIDUAL, 'username': 'dupond.f', 'email': '[email protected]', 'password': 'pwd', 'password2': 'pwd', 'civility': User.CIVILITY_MISTER, 'first_name': 'François', 'last_name': 'DUPOND', 'phone': '+33 1 34 12 52 30', 'gsm': '+33 6 34 12 52 30', 'fax': '+33 1 34 12 52 30', 'form-0-address1': '33 avenue Gambetta', 'form-0-address2': 'apt 50', 'form-0-zip_code': '75020', 'form-0-city': 'Paris', 'form-0-country': 'FRA', 'same_for_billing': True, } response = self.c.post(reverse('client:full_account'), post_data, follow=True) self.assertRedirects(response, '%s?created=1' % reverse('client:dashboard')) and i have this error: ValidationError: [u'ManagementForm data is missing or has been tampered with'] My view : def full_account(request, url_redirect=''): from forms import NewUserFullForm, AddressForm, BaseArticleFormSet fields_required = [] fields_notrequired = [] AddressFormSet = formset_factory(AddressForm, extra=2, formset=BaseArticleFormSet) if request.method == 'POST': form = NewUserFullForm(request.POST) objforms = AddressFormSet(request.POST) if objforms.is_valid() and form.is_valid(): user = form.save() address = objforms.forms[0].save() if url_redirect=='': url_redirect = '%s?created=1' % reverse('client:dashboard') logon(request, form.instance) return HttpResponseRedirect(url_redirect) else: form = NewUserFullForm() objforms = AddressFormSet() return direct_to_template(request, 'clients/full_account.html', { 'form':form, 'formset': objforms, 'tld_fr':False, }) and my form file : class BaseArticleFormSet(BaseFormSet): def clean(self): msg_err = _('Ce champ est obligatoire.') non_errors = True if 'same_for_billing' in self.data and self.data['same_for_billing'] == 'on': same_for_billing = True else: same_for_billing = False for i in [0, 1]: form = self.forms[i] for field in form.fields: name_field = 'form-%d-%s' % (i, field ) value_field = self.data[name_field].strip() if i == 0 and self.forms[0].fields[field].required and value_field =='': form.errors[field] = msg_err non_errors = False elif i == 1 and not same_for_billing and self.forms[1].fields[field].required and value_field =='': form.errors[field] = msg_err non_errors = False return non_errors class AddressForm(forms.ModelForm): class Meta: model = Address address1 = forms.CharField() address2 = forms.CharField(required=False) zip_code = forms.CharField() city = forms.CharField() country = forms.ChoiceField(choices=CountryField.COUNTRIES, initial='FRA')

    Read the article

  • Django Model Formset Pre-Filled Value Problem

    - by user552377
    Hi, i'm trying to use model formsets with Django. When i load forms template, i see that it's filled-up with previous values. Is there a caching mechanism that i should stop, or what? Thanks for your help, here is my code: models.py class FooModel( models.Model ): a_field = models.FloatField() b_field = models.FloatField() def __unicode__( self ): return self.a_field forms.py from django.forms.models import modelformset_factory FooFormSet = modelformset_factory(FooModel) views.py def foo_func(request): if request.method == 'POST': formset = FooFormSet(request.POST, request.FILES, prefix='foo_prefix' ) if formset.is_valid(): formset.save() return HttpResponseRedirect( '/true/' ) else: return HttpResponseRedirect( '/false/' ) else: formset = FooFormSet(prefix='foo_prefix') variables = RequestContext( request , { 'formset':formset , } ) return render_to_response('footemplate.html' , variables ) template: <form method="post" action="."> {% csrf_token %} <input type="submit" value="Submit" /> <table id="FormsetTable" border="0" cellpadding="0" cellspacing="0"> <tbody> {% for form in formset.forms %} <tr> <td>{{ form.a_field }}</td> <td>{{ form.b_field }}</td> </tr> {% endfor %} </tbody> </table> {{ formset.management_form }} </form>

    Read the article

  • Django Formset validation with an optional ForeignKey field

    - by Camilo Díaz
    Having a ModelFormSet built with modelformset_factory and using a model with an optional ForeignKey, how can I make empty (null) associations to validate on that form? Here is a sample code: ### model class Prueba(models.Model): cliente = models.ForeignKey(Cliente, null = True) valor = models.CharField(max_length = 20) ### view def test(request): PruebaFormSet = modelformset_factory(model = Prueba, extra = 1) if request.method == 'GET': formset = PruebaFormSet() return render_to_response('tpls/test.html', {'formset' : formset}, context_instance = RequestContext(request)) else: formset = PruebaFormSet(request.POST) # dumb tests, just to know if validating if formset.is_valid(): return HttpResponse('0') else: return HttpResponse('1') In my template, i'm just calling the {{ form.cliente }} method which renders the combo field, however, I want to be able to choose an empty (labeled "------") value, as the FK is optional... but when the form gets submitted it doesn't validate. Is this normal behaviour? How can i make this field to skip required validation?

    Read the article

  • Django Inline formset for editing multiple related records at once - the right way to go?

    - by Bert
    Hi, When using inline formsets, how does one do paging? I'm using django 1.1. The situation I'm in, is that the user needs to be able to edit the related objects quickly and easily (which is why I think I should be using an inline formset). However, there can be a more than a hundred objects to edit, which makes a pretty large formset, so paging would make sense. Is there a better way to be doing this? Thanks Bert

    Read the article

  • Testing InlineFormset clean methods

    - by Rory
    I have a Django project, with 2 models, a Structure and Bracket, the Bracket has a ForeignKey to a Structure (i.e. one-to-many, one Structure has many Brackets). I created a TabularInline for the admin site, so that there would be a table of Brackets on the Structure. I added a custom formset with some a custom clean method to do some extra validation, you can't have a Bracket that conflicts with another Bracket on the same Structure etc. The admin looks like this: class BracketInline(admin.TabularInline): model = Bracket formset = BracketInlineFormset class StructureAdmin(admin.ModelAdmin): inlines = [ BracketInline ] admin.site.register(Structure, StructureAdmin) That all works, and the validation works. However now I want to write some unittest to test my complex formset validation logic. My first attempt to validate known-good values is: data = {'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-field1':'good-value', … } formset = BracketInlineFormset(data) self.assertTrue(formset.is_valid()) However that doesn't work and raises the exception: ====================================================================== ERROR: testValid (appname.tests.StructureTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/paht/to/project/tests.py", line 494, in testValid formset = BracketInlineFormset(data) File "/path/to/django/forms/models.py", line 672, in __init__ self.instance = self.fk.rel.to() AttributeError: 'BracketInlineFormset' object has no attribute 'fk' ---------------------------------------------------------------------- The Django documentation (for formset validation) implies one can do this. How come this isn't working? How do I test the custom clean()/validation for my inline formset?

    Read the article

  • Create Django formset wihtout multiple queries

    - by Martin
    I need to display multiple forms (up to 10) of a model on a page. This is the code I use for to accomplish this. TheFormSet = formset_factory(SomeForm, extra=10) ... formset = TheFormSet(prefix='party') return render_to_response('template.html', { 'formset' : formset, }) The problem is, that it seems to me that Django queries the database for each of the forms in the formset, even though the data displayed in them is the same. Is this the way Formsets work or am I doing something wrong? Is there a way around it inside django or would I have to use JavaScript for a workaround?

    Read the article

  • Django Passing Custom Form Parameters to Formset

    - by Paolo Bergantino
    I have a Django Form that looks like this: class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) I call this form with something like this: form = ServiceForm(affiliate=request.affiliate) Where request.affiliate is the logged in user. This works as intended. My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this: ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) And then I need to create it like this: formset = ServiceFormSet() Now how can I pass affiliate=request.affiliate to the individual forms this way?

    Read the article

  • Display additional data while iterating over a Django formset

    - by Jannis
    Hi, I have a list of soccer matches for which I'd like to display forms. The list comes from a remote source. matches = ["A vs. B", "C vs. D", "E vs, F"] matchFormset = formset_factory(MatchForm,extra=len(matches)) formset = MatchFormset() On the template side, I would like to display the formset with the according title (i.e. "A vs. B"). {% for form in formset.forms %} <fieldset> <legend>{{TITLE}}</legend> {{form.team1}} : {{form.team2}} </fieldset> {% endfor %} Now how do I get TITLE to contain the right title for the current form? Or asked in a different way: how do I iterate over matches with the same index as the iteration over formset.forms? Thanks for your input!

    Read the article

  • Building a formset dynamically

    - by vorpyg
    I initially wrote code to build a form dynamically, based on data from the DB, similar to what I described in my previous SO post. As SO user Daniel Roseman points out, he would use a formset for this, and now I've come to the realization that he must be completely right. :) My approach works, basically, but I can't seem to get validation across the entire form to be working properly (I believe it's possible, but it's getting quite complex, and there has to be a smarter way of doing it = Formsets!). So now my question is: How can I build a formset dynamically? Not in an AJAX way, I want each form's label to be populated with an FK value (team) from the DB. As I have a need for passing parameters to the form, I've used this technique from a previous SO post. With the former approach, my view code is (form code in previous link): def render_form(request): teams = Team.objects.filter(game=game) form_collection = [] for team in teams: f = SuggestionForm(request.POST or None, team=team, user=request.user) form_collection.append(f) Now I want to do something like: def render_form(request): teams = Team.objects.filter(game=game) from django.utils.functional import curry from django.forms.formsets import formset_factory formset = formset_factory(SuggestionForm) for team in teams: formset.form.append(staticmethod(curry(SuggestionForm, request.POST or None, team=team, user=request.user))) But the append bit doesn't work. What's the proper way of doing this? Thanks!

    Read the article

  • Formset Messages

    - by Dave
    I want to be able to send a message using the new messages framework. Something along the lines of : ... if formset.is_valid return HttpResponseRedirect( some page ) messages.add_message(request,messages.INFO, '%i objects added') %formset.number_of_forms But two questions: Im not sure if i should put the messages before or after the render to response Is there a method akin to number_of_forms

    Read the article

  • Dynamic model choice field in django formset using multiple select elements

    - by Aryeh Leib Taurog
    I posted this question on the django-users list, but haven't had a reply there yet. I have models that look something like this: class ProductGroup(models.Model): name = models.CharField(max_length=10, primary_key=True) def __unicode__(self): return self.name class ProductRun(models.Model): date = models.DateField(primary_key=True) def __unicode__(self): return self.date.isoformat() class CatalogItem(models.Model): cid = models.CharField(max_length=25, primary_key=True) group = models.ForeignKey(ProductGroup) run = models.ForeignKey(ProductRun) pnumber = models.IntegerField() def __unicode__(self): return self.cid class Meta: unique_together = ('group', 'run', 'pnumber') class Transaction(models.Model): timestamp = models.DateTimeField() user = models.ForeignKey(User) item = models.ForeignKey(CatalogItem) quantity = models.IntegerField() price = models.FloatField() Let's say there are about 10 ProductGroups and 10-20 relevant ProductRuns at any given time. Each group has 20-200 distinct product numbers (pnumber), so there are at least a few thousand CatalogItems. I am working on formsets for the Transaction model. Instead of a single select menu with the several thousand CatalogItems for the ForeignKey field, I want to substitute three drop-down menus, for group, run, and pnumber, which uniquely identify the CatalogItem. I'd also like to limit the choices in the second two drop-downs to those runs and pnumbers which are available for the currently selected product group (I can update them via AJAX if the user changes the product group, but it's important that the initial page load as described without relying on AJAX). What's the best way to do this? As a point of departure, here's what I've tried/considered so far: My first approach was to exclude the item foreign key field from the form, add the substitute dropdowns by overriding the add_fields method of the formset, and then extract the data and populate the fields manually on the model instances before saving them. It's straightforward and pretty simple, but it's not very reusable and I don't think it is the right way to do this. My second approach was to create a new field which inherits both MultiValueField and ModelChoiceField, and a corresponding MultiWidget subclass. This seems like the right approach. As Malcolm Tredinnick put it in a django-users discussion, "the 'smarts' of a field lie in the Field class." The problem I'm having is when/where to fetch the lists of choices from the db. The code I have now does it in the Field's __init__, but that means I have to know which ProductGroup I'm dealing with before I can even define the Form class, since I have to instantiate the Field when I define the form. So I have a factory function which I call at the last minute from my view--after I know what CatalogItems I have and which product group they're in--to create form/formset classes and instantiate them. It works, but I wonder if there's a better way. After all, the field should be able to determine the correct choices much later on, once it knows its current value. Another problem is that my implementation limits the entire formset to transactions relating to (CatalogItems from) a single ProductGroup. A third possibility I'm entertaining is to put it all in the Widget class. Once I have the related model instance, or the cid, or whatever the widget is given, I can get the ProductGroup and construct the drop-downs. This would solve the issues with my second approach, but doesn't seem like the right approach.

    Read the article

  • Django Formset management-form validation error

    - by gramware
    I have a form and a formset on my template. The problem is that the formset is throwing validation error claiming that the management form is "missing or has been tampered with". Here is my view @login_required def home(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) blogz = list(blog.objects.filter(deleted='0')) delblog = modelformset_factory(blog, exclude=('poster','date' ,'title','content')) if request.user.is_staff== True: staff = 1 else: staff = 0 staffis = 1 if request.method == 'POST': delblogformset = delblog(request.POST) if delblogformset.is_valid(): delblogformset.save() return HttpResponseRedirect('/home') else: delblogformset = delblog(queryset=blog.objects.filter( deleted='0')) blogform = BlogForm(request.POST) if blogform.is_valid(): blogform.save() return HttpResponseRedirect('/home') else: blogform = BlogForm(initial = {'poster':user.id}) blogs= zip(blogz,delblogformset.forms) paginator = Paginator(blogs, 10) # Show 25 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: blogs = paginator.page(page) except (EmptyPage, InvalidPage): blogs = paginator.page(paginator.num_pages) return render_to_response('home.html', {'user':user, 'blogform':blogform, 'staff': staff, 'staffis': staffis, 'blog':blogs, 'delblog':delblogformset}, context_instance = RequestContext( request )) my template {%block content%} <h2>Home</h2> {% ifequal staff staffis %} {% if form.errors %} <ul> {% for field in form %} <H3 class="title"> <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p> </H3> {% endfor %} </ul> {% endif %} <h3>Post a Blog to the Front Page</h3> <form method="post" id="form2" action="" class="infotabs accfrm"> {{ blogform.as_p }} <input type="submit" value="Submit" /> </form> <br> <br> {% endifequal %} <div class="pagination"> <span class="step-links"> {% if blog.has_previous %} <a href="?page={{ blog.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ blog.number }} of {{ blog.paginator.num_pages }}. </span> {% if blog.has_next %} <a href="?page={{ blog.next_page_number }}">next</a> {% endif %} </span> <form method="post" action="" class="usertabs accfrm"> {{delblog.management_form}} {% for b, form in blog.object_list %} <div class="blog"> <h3>{{b.title}}</h3> <p>{{b.content}}</p> <p>posted by <strong>{{b.poster}}</strong> on {{b.date}}</p> {% ifequal staff staffis %}<p>{{form.as_p}}<input type="submit" value="Delete" /></p>{% endifequal %} </div> {% endfor %} </form> {%endblock%}

    Read the article

  • Form (or Formset?) to handle multiple table rows in Django

    - by Ben
    Hi, I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once? At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean. Currently, my views.py has this code: def survey(request): ScoreFormSet = formset_factory(ScoreForm) if request.method == 'POST': formset = ScoreFormSet(request.POST, request.FILES) if formset.is_valid(): return HttpResponseRedirect('/') else: formset = ScoreFormSet() return render_to_response('cf/survey.html', { 'formset':formset, }) And my survey.html has this: <form action="/survey/" method="POST"> <table> {{ formset }} </table> <input type = "submit" value = "Submit"> </form> Oh, and the definition of ScoreForm and Score from models.py are: class Score(models.Model): movie = models.ForeignKey(Movie) score = models.IntegerField() user = models.ForeignKey(User) class ScoreForm(ModelForm): class Meta: model = Score So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score. If anyone can point me at the right sort of approach to this, I'd be most grateful. Thanks, Ben

    Read the article

  • Django: Adding inline formset rows without javascript

    - by Brant
    This post relates to this: http://stackoverflow.com/questions/520421/add-row-to-inlines-dynamically-in-django-admin Is there a way to achive adding inline formsets WITHOUT using javascript? Obviously, there would be a page-refresh involved. So, if the form had a button called 'add'... I figured I could do it like this: if request.method=='POST': if 'add' in request.POST: PrimaryFunctionFormSet = inlineformset_factory(Position,Function,extra=1) prims = PrimaryFunctionFormSet(request.POST) Which I thought would add 1 each time, then populate the form with the post data. However, it seems that the extra=1 does not add 1 to the post data.

    Read the article

  • Django inlineformset validation and delete

    - by Andrew Gee
    Hi, Can someone tell me if a form in an inlineformset should go through validation if the DELETE field is checked. I have a form that uses an inlineformset and when I check the DELETE box it fails because the required fields are blank. If I put data in the fields it will pass validation and then be deleted. Is that how it is supposed to work, I would have thought that if it is marked for delete it would bypass the validation for that form. Regards Andrew Follow up - but I would still appreciate some others opinions/help What I have figured out is that for validation to work the a formset form must either be empty or complete(valid) otherwise it will have errors when it is created and will not be deleted. As I have a couple of hidden fields in my formset forms and they are pre-populated when the page loads via javascript the form fails validation on the other required fields which might still be blank. The way I have gotten around this by adding in a check in the add_fields that tests if the DELETE input is True and if it is it makes all fields on the form not required, which means it passes validation and will then delete. def add_fields(self, form, index) #add other fields that are required.... deleteValue = form.fields['DELETE'].widget.value_from datadict(form.data, form.files, form.add_prefix('DELETE')) if bool(deleteValue) or deleteValue == '': for name, field in form.fields.items(): form.fields[name].required= False This seems to be an odd way to do things but I cannot figure out another way. Is there a simpler way that I am missing? I have also noticed that when I add the new form to my page and check the Delete box, there is no value passed back via the request, however an existing form (one loaded from the database) has a value of on when the Delete box is checked. If the box is not checked then the input is not in the request at all. Thanks Andrew

    Read the article

  • Django one form for two models

    - by martinthenext
    Hello! I have a ForeignKey relationship between TextPage and Paragraph and my goal is to make front-end TextPage creating/editing form as if it was in ModelAdmin with 'inlines': several field for the TextPage and then a couple of Paragraph instances stacked inline. The problem is that i have no idea about how to validate and save that: @login_required def textpage_add(request): profile = request.user.profile_set.all()[0] if not (profile.is_admin() or profile.is_editor()): raise Http404 PageFormSet = inlineformset_factory(TextPage, Paragraph, extra=5) if request.POST: try: textpageform = TextPageForm(request.POST) # formset = PageFormSet(request.POST) except forms.ValidationError as error: textpageform = TextPageForm() formset = PageFormSet() return render_to_response('textpages/manage.html', { 'formset' : formset, 'textpageform' : textpageform, 'error' : str(error), }, context_instance=RequestContext(request)) # Saving data if textpageform.is_valid() and formset.is_valid(): textpageform.save() formset.save() return HttpResponseRedirect(reverse(consults)) else: textpageform = TextPageForm() formset = PageFormSet() return render_to_response('textpages/manage.html', { 'formset' : formset, 'textpageform' : textpageform, }, context_instance=RequestContext(request)) I know I't a kind of code-monkey style to post code that you don't even expect to work but I wanted to show what I'm trying to accomplish. Here is the relevant part of models.py: class TextPage(models.Model): title = models.CharField(max_length=100) page_sub_category = models.ForeignKey(PageSubCategory, blank=True, null=True) def __unicode__(self): return self.title class Paragraph(models.Model): article = models.ForeignKey(TextPage) title = models.CharField(max_length=100, blank=True, null=True) text = models.TextField(blank=True, null=True) def __unicode__(self): return self.title Any help would be appreciated. Thanks!

    Read the article

  • Filter Queryset in Django inlineformset_factory

    - by Dave
    I am trying to use inlineformset_factory to generate a formset. My models are defined as: class Measurement(models.Model): subject = models.ForeignKey(Animal) experiment = models.ForeignKey(Experiment) assay = models.ForeignKey(Assay) values = models.CommaSeparatedIntegerField(blank=True, null=True) class Experiment(models.Model): date = models.DateField() notes = models.TextField(max_length = 500, blank=True) subjects= models.ManyToManyField(Subject) in my view i have: def add_measurement(request, experiment_id): experiment = get_object_or_404(Experiment, pk=experiment_id) MeasurementFormSet = inlineformset_factory(Experiment, Measurement, extra=10, exclude=('experiment')) if request.method == 'POST': formset = MeasurementFormSet(request.POST,instance=experiment) if formset.is_valid(): formset.save() return HttpResponseRedirect( experiment.get_absolute_url() ) else: formset = MeasurementFormSet(instance=experiment) return render_to_response("data_entry_form.html", {"formset": formset, "experiment": experiment }, context_instance=RequestContext(request)) but i want to restrict the Measurement.subject field to only subjects defined in the Experiment.subjects queryset. I have tried a couple of different ways of doing this but I am a little unsure what the best way to accomplish this is. I tried to over-ride the BaseInlineFormset class with a new queryset, but couldnt figure out how to correctly pass the experiment parameter.

    Read the article

  • How do I create an empty Django formset using modelformset_factory?

    - by nbolton
    I'm creating a formset, but it seems to populate it with all of the existing data in the table for that object. I can't figure out how to start with a blank formset; the only way seems to be to delete all of the data from the table, but clearly this isn't an option. I will post code if necessary (but there's lots of it, so knowing what is relevant is tricky).

    Read the article

  • Django multiple generic_inline_formset in a view

    - by Can Burak Cilingir
    We have a bunch of formsets: EmailAddressInlineFormSet = generic_inlineformset_factory( EmailAddress, extra=1, exclude=["created_by","last_modified_by"]) emailaddressformset = EmailAddressInlineFormSet( instance=person, prefix="emailaddress") # [ more definitions ] and, in the view, we process them as: emailaddressformset = EmailAddressInlineFormSet( request.POST, instance=person, prefix="emailaddress") # [ more definitions ] So, nothing fancy or unordinary. The unfortunate or unordinary fact is, we have 15 of these formsets, one for email addresses, other for phone numbers etc. so the view code is ugly and not-so-manageable. What would be the most unhackish way to handle this number of formsets in a single view? At the end -i guess- I'm looking for a class or a functionality like multiple_generic_inline_formset and open to all kind of suggestions or discussions.

    Read the article

  • Django ManyToMany Membership errors making associations

    - by jmitchel3
    I'm trying to have a "member admin" in which they have hundreds of members in the group. These members can be in several groups. Admins can remove access for the member ideally in the view. I'm having trouble just creating the group. I used a ManytoManyField to get started. Ideally, the "member admin" would be able to either select existing Users OR it would be able to Add/Invite new ones via email address. Here's what I have: #views.py def membership(request): group = Group.objects.all().filter(user=request.user) GroupFormSet = modelformset_factory(Group, form=MembershipForm) if request.method == 'POST': formset = GroupFormSet(request.POST, request.FILES, queryset=group) if formset.is_valid(): formset.save(commit=False) for form in formset: form.instance.user = request.user formset.save() return render_to_response('formset.html', locals(), context_instance=RequestContext(request)) else: formset= GroupFormSet(queryset=group) return render_to_response('formset.html', locals(), context_instance=RequestContext(request)) #models.py class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(User, related_name='community_members', through='Membership') user = models.ForeignKey(User, related_name='community_creator', null=True) def __unicode__(self): return self.name class Membership(models.Model): member = models.ForeignKey(User, related_name='user_membership', blank=True, null=True) group = models.ForeignKey(Group, related_name='community_membership', blank=True, null=True) date_joined = models.DateField(auto_now=True, blank=True, null=True) class Meta: unique_together = ('member', 'group') Any ideas? Thank you for your help.

    Read the article

  • Django: How can I delete a formset entry if one of it's data is blank?

    - by mkret
    Hi, I have the following scenario: I have a form with data that does not need translation and a formset with a textfield that should be translated into an undefined amount of languages. Both parts are bound to a model. Each translated text is kept in a model with a foreign key that binds it to the untranslatable data. Something like: class Person(models.Model): name = models.CharField(max_length=60) birth_date = models.DateField() class PersonBio(models.Model): person = models.ForeignKey(Person) locale = models.CharField(max_length=10) bio = models.TextField() Each form in the formset has 2 fields: A textfield (with the translated text) A locale field (with the language into which the text was translated) I've got it working with no problems until I tryed to change it's normal behaviour. I wanted to eliminate the need for the DELETE field by deleting an instance of the translated text if the textfield was left blank. I've googled quite a lot now and read the whole documentation for forms, formsets and model validation but had no luck. To be honest, I couldn't even think of a solution. Where should I implement this? On a Form clean() method? On the view? Somewhere in the Fieldset? Fieldset's save() method, maybe? I'll keep trying to find a way to do that, but any help/tip/clue is appreciated. Thanks in advance.

    Read the article

  • django modelformset - one form per related table row

    - by Toby
    Hello, I have two models: class Model1(): name = CharField() url = CharField() class Model2(): model1 = ForeignKey(Model1) user = ForeignKey(User) zzz = CharField() There are 5 rows for model1 in the database, these are fixed and will rarely change. I need to display a formset for model2 that allows users to enter the zzz value, the formset must always show one form per row in the model1 table, the label for each form in the formset must be the name of the related model1. If the user deletes a model2 in the formset the next time the page loads it will render an empty zzz value for that form and the user must be able to edit the previous zzz value - meaning it must be pre populated with all model2 rows associated with the user. The idea is to print each row in the model1 table as a form instead of the user selecting the related model1 name in a select box. I know its not that complicated, but I'm seriously stumped and keep going round in circles!! Many thanks in advance. Similar to http://stackoverflow.com/questions/298779/form-or-formset-to-handle-multiple-table-rows-in-django

    Read the article

  • Override Django inlineformset_factory has_changed() to always return True

    - by John
    Hi, I am using the django inlineformset_factory function. a = get_object_or_404(ModelA, pk=id) FormSet = inlineformset_factory(ModelA, ModelB) if request.method == 'POST': metaform = FormSet (instance=a, data=request.POST) if metaform.is_valid(): f = metaform.save(commit=False) for instance in f: instance.updated_by = request.user instance.save() else: metaform = FormSet(instance=a) return render_to_response('nodes/form.html', {'form':metaform}) What is happening is that if I change any of the data then everything works ok and all the data gets updated. However if I don't change any of the data then the data is not updated. i.e. only entries which are changed go through the for loop to be saved. I guess this makes sense as there is no point saving data if it has not changed. However I need to go through and save every object in the form regardless of whether it has any changes on not. So my question is how do I override this so that it goes through and saves every record whether it has any changes or not? Hope this makes sense Thanks

    Read the article

  • Add data to Django form class using modelformset_factory

    - by dean
    I have a problem where I need to display a lot of forms for detail data for a hierarchical data set. I want to display some relational fields as labels for the forms and I'm struggling with a way to do this in a more robust way. Here is the code... class Category(models.Model): name = models.CharField(max_length=160) class Item(models.Model): category = models.ForeignKey('Category') name = models.CharField(max_length=160) weight = models.IntegerField(default=0) class Meta: ordering = ('category','weight','name') class BudgetValue(models.Model): value = models.IntegerField() plan = models.ForeignKey('Plan') item = models.ForeignKey('Item') I use the modelformset_factory to create a formset of budgetvalue forms for a particular plan. What I'd like is item name and category name for each BudgetValue. When I iterate through the forms each one will be labeled properly. class BudgetValueForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput()) plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput()) category = "" < assign dynamically on form creation > item = "" < assign dynamically on form creation > class Meta: model = BudgetValue fields = ('item','plan','value') What I started out with is just creating a dictionary of budgetvalue.item.category.name, budgetvalue.item.name, and the form for each budget value. This gets passed to the template and I render it as I intended. I'm assuming that the ordering of the forms in the formset and the querset used to genererate the formset keep the budgetvalues in the same order and the dictionary is created correctly. That is the budgetvalue.item.name is associated with the correct form. This scares me and I'm thinking there has to be a better way. Any help would be greatly appreciated.

    Read the article

1 2  | Next Page >