Initial data for inline formsets of Django related models? -


i'm trying create updateview page allows me edit customer's information affiliated users' information in form. customerform works fine, i'm not sure how set initial data inline formsets. tried dictionary of users going through self.object.user_set.all() loop. can't seem make change userformset. here's code:

forms.py

class customerform(modelform):      class meta:          model = customer          fields = ['name', 'system', 'bill_amount', 'exchanges', 'due_date', 'invoice_date', 'keycodes_expire', 'paid_date', 'active']          success_url = reverse_lazy('index')  userformset = inlineformset_factory(customer, user, fields=['name', 'expiration_date'], extra=1, can_delete=true) 

models.py

class customer(models.model):     active = models.booleanfield(default = false)        bill_amount = models.decimalfield(max_digits=7, decimal_places=2)        due_date = models.datefield(default = timezone.now() + timedelta(days=30), blank = true, null = true)        exchanges = models.integerfield(default = 0)         invoice_date = models.datefield(default = timezone.now(), blank = true, null = true)     keycodes_expire = models.datefield(default = timezone.now() + timedelta(days=120), blank = true, null = true)        name = models.charfield(max_length = 128)     paid_date = models.datefield(default = timezone.now() + timedelta(days=30), blank = true, null = true)     edge_hosted = 'edge (hosted)'     edge_nonhosted = 'edge (non-hosted)'     edge_risk_hosted = 'edge risk (hosted)'     edge_risk_nonhosted = 'edge risk (non-hosted)'     tradepad = 'tradepad'        system_choices = (         (edge_hosted, 'edge (hosted)'),         (edge_nonhosted, 'edge (non-hosted)'),         (tradepad, 'tradepad'),         (edge_risk_hosted, 'edge risk (hosted)'),         (edge_risk_nonhosted, 'edge risk (non-hosted)')     )     system = models.charfield(max_length=64, choices = system_choices, default = edge_hosted)      def get_absolute_url(self):         return reverse('customer-detail', kwargs={'pk': self.pk})  class user(models.model):     customer = models.foreignkey('customer')     expiration_date = models.datefield(default = timezone.now() + timedelta(days=120))       name = models.charfield(max_length = 64, default = 'user') 

views.py

class customerupdate(generic.updateview):     model = customer     form_class = customerform     template_name_suffix = '_update_form'     success_url = reverse_lazy('index')      def get_context_data(self, **kwargs):         userdata = []         x in range(0,len(self.object.user_set.all())):             foo = {'name' : self.object.user_set.all()[x].name, 'expiration_date' : self.object.user_set.all()[x].expiration_date}                   userdata.append(foo)         users = inlineformset_factory(customer, user, fields=['name', 'expiration_date'], extra=len(self.object.user_set.all()), can_delete=true)         userlist = users(queryset = self.object.user_set.all())         ctx = super(customerupdate, self).get_context_data(**kwargs)         if self.request.post:             ctx['inlines'] = userlist         else:             ctx['inlines'] = userlist         return ctx 

customer_update_form.html

<h1>update customer</h1> <form id="customer_form" action="" method="post">{% csrf_token %}    {% f in form %}     <div>{{ f.label }}:<br />{{ f }}         {% if f.errors %}              {% v in f.errors %}                         <br /><span style="color:red;">{{ v }}</span>                 {% endfor %}             {% endif %}         </div> {% endfor %} <h2>update user(s)</h2> <table> {% f2 in inlines %}     <tr id="{{ f2.prefix }}-row-0">             <td>                 {{ f2.name.label }}:              {{ f2.name }}         {% if f2.name.errors %}             <span style="color:red;">{{ f2.name.errors }}</span>         {% endif %}             </td>     </tr>     <tr id="{{ f2.prefix }}-row-1">         <td>             {{ f2.expiration_date.label }}:              {{ f2.expiration_date }}         {% if f2.expiration_date.errors %}             <span style="color:red;">{{ f2.expiration_date.errors }}</span>         {% endif %}         </td>     </tr>     <tr id="{{ f2.prefix }}-row-2">         <td>             {{ f2.delete.label }}?              {{ f2.delete }}         {% if f2.delete.errors %}             <span style="color:red;">{{ f2.delete.errors }}</span>         {% endif %}         </td>     </tr>     {{ f2.as_p }} {% endfor %} </table> {{ inlines.management_form }} <input type="submit" value="create customer / user(s)" /> 

want usernames , expiration dates initial values in each formset, accessing users , fields seems near impossible, , changing values users doesn't seem anything.

change in views:

userlist = users(     queryset=self.object.user_set.all(),     instance=self.object ) 

also cannot have request.post in get_context_data - absurd! remove if self.request.post: get_context_data

if want save data should implement in post method

def post(self, request, *args, **kwargs):         if self.pk_url_kwarg:             self.object = self.get_object()             form = self.form_class(request.post, instance=self.object)             inlines = users(request.post, request.files, instance=self.object)         else:             form = self.form_class(request.post)             inlines = users(request.post, request.files)          if form.is_valid() , inlines.is_valid():             return self.form_valid(form, inlines)         else:             return self.form_invalid(form, inlines)     def form_valid(self, form, inlines):         if not self.object:             self.object = form.save()         else:             form.save()          inlines.instance = self.object         inlines.save()           return httpresponseredirect(self.get_success_url())    def form_invalid(self, form, inlines):         return self.render_to_response(             self.get_context_data(                 form=form,                 inlines=inlines             )         )      def get_success_url(self):         return reverse('some_app:url_name') 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -