2016-10-09 2 views
0

私のビューからフォームにIDが渡されます。このIDは別のテーブルからの外部キーです。私はIDをデータベーステーブルに保存できません。 (ID:私は、フォームを保存していたにvoucher_id、テーブル:TmpPlInvoicedet)Djangoモデルフォームに外部キーテキストを保存する方法

私は

をやりたいが、(ビュー)からvoucher_idを送信するために---> TmpFormDetForm(フォーム) - - > TmpPlInvoicedet(DB)(PKとしてvoucher_idた)テーブル 'TmpPlInvoice' からインスタンスを取得し、フォームに保存しようとすると

は私に新しい/ TmpPlInvoiceミリアンペア/時

のDoesNotExistを与えます質問が存在しません

私は間違っていますか?

Views.py

def new_invoic(request): 

    # Create a voucher id according to my criteria 
    temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct() 
    if not temp_vid: 
      voucher_id = str(1).zfill(4) 
    else: 
      voucher_id = str(int(max(temp_vid)) + 1).zfill(4) 

    # POST METHOD TRying to show the voucher_id in the form in readonly format 
    if request.method == 'POST': 
      form_pk = TmpForm(request.POST or None, voucher_id=voucher_id,initial={'voucher_id': voucher_id}) 

      if form.is_valid(): 
       form_pk.save() 
       form = TmpFormDetForm(request.POST or None, voucher=voucher_id, initial={'voucher': voucher_id}) 
       # My assumption is that since i have save the voucher_id in the TmpInvoice table so i can get the PK voucher_id value and save it in the TmpInvoiceDetForm 
       form.save() 
       return HttpResponseRedirect('/new/') 
      else: 
       return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request)) 
    else: 
      form_pk = TmpForm(voucher_id=voucher_id,initial={'voucher_id': voucher_id}) 
      form = TmpFormDetForm(voucher=voucher_id, initial={'voucher': voucher_id}) 
      return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request)) 

Forms.py

# This form contains the FK. This one is giving errors while saving. 

class TmpFormDetForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     voucher = kwargs.pop('voucher', None) 
     super(TmpFormDetForm, self).__init__(*args, **kwargs) 
     self.fields['voucher'].initial = TmpPlInvoice.objects.get(voucher_id=voucher) 

    voucher = forms.CharField(widget=forms.TextInput(attrs={'size':'40'})) 

    class Meta: 
      model = TmpPlInvoicedet 
      exclude = ['emp_id','particulars','qty', 'rate' , 'itemtot', 'stock_code' ] 
      widgets = { 
       'voucher': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required': 'False', 'name': 'voucher','readonly': 'readonly'}), 
       'lineitem': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Total', 'required': 'False', 'blank': 'True'})} 

# This form takes the PK. I save the PK here first. 
class TmpForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     voucher_id = kwargs.pop('voucher_id', None) 
     super(TmpFor, self).__init__(*args, **kwargs) 
     self.fields['voucher_id'].initial = voucher_id 

    pos_code = MyModelChoiceField(queryset=Positions.objects.all(), widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'})) 
    cust = MyModelChoiceField(queryset=Custodian.objects.all(), to_field_name='acct_id',widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'})) 
    acct = MyModelChoiceField(queryset=Item.objects.all(), to_field_name='stock_code',widget=forms.Select(attrs={'class':'select2_single form-control', 'blank': 'True'})) 

    voucher_date = forms.DateField(widget=forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'})) 

class Meta: 
    model = TmpPlInvoice 
    exclude = ['net_amt', 'post_date', 'address', 'posted'] 
    widgets = { 
       'voucher_id': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required':'False', 'name': 'voucher_id', 'readonly': 'readonly'}), 
       'voucher_date': forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}), 
       'particulars': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Particulars', 'required':'False'}), 
      } 

Models.py

class TmpPlInvoicedet(models.Model): 
    stock_code = models.CharField(max_length=13, blank=True, null=True) 
    voucher = models.ForeignKey(TmpPlInvoice, db_column='voucher_id') 
    lineitem = models.CharField(max_length=6) 
    particulars = models.CharField(max_length=200, blank=True, null=True) 
    qty = models.FloatField(blank=True, null=True) 
    rate = models.FloatField(blank=True, null=True) 
    itemtot = models.FloatField(blank=True, null=True) 
    emp_id = models.CharField(max_length=8, blank=True, null=True) 

class Meta: 
    managed = False 
    db_table = 'tmp_pl_invoicedet' 
    unique_together = (('voucher', 'lineitem'),) 

答えて

0

簡単peesy。

def master_detail(request): 
    def get_new_voucher_id(): 
     temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct() 
     logger.info('Voucher ID already present %s', temp_vid) 
     if not temp_vid: 
      voucher_id = str(1).zfill(4) 
     else: 
      voucher_id = str(int(max(temp_vid)) + 1).zfill(4) 
     return voucher_id 

    voucher_id = get_new_voucher_id() 
    author_form = TmpForm(initial={'voucher_id': voucher_id}) 
    author = TmpPlInvoice() 
    BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet, exclude=('emp_id', 'itemtot', 'voucher', 'lineitem','id'), 
            form=TmpFormDetForm, extra=1) 
    formset = BookFormSet(instance=author) 

    if request.method == 'POST': 
     logger.info('*'*50) 
     author = TmpForm(request.POST, initial={'voucher_id': voucher_id}) 
     if author.is_valid(): 
      logger.info('Data for Author is %s', author.cleaned_data) 
      created_author = author.save() 
      formset = BookFormSet(request.POST, instance=created_author) 

      if formset.is_valid(): 
       logger.info('Data for Book is %s', formset.cleaned_data) 
       formset.save() 
      else: 
       logger.info('Formset errors %s', formset.errors) 
     else: 
      logger.info('Master form errors %s', author.errors) 
      logger.info('*'*50) 
     return HttpResponseRedirect('/new/') 
    else: 
     logger.info('Formset from GET is %s', formset.errors) 
     return render_to_response('new_invoice.html', 
           {'form': author_form, 'formset': formset},context_instance=RequestContext(request)) 
0

あなたはcreatのように見えます新しい請求書IDを入力し、そのIDと一致する請求書を取得しようとします。しかし、その請求書はまだ作成されていないため、まだ存在しません。

請求書が存在しない場合は、get_or_createを使用して確実に作成することができます。

+0

偉大な観測!同じビューでは、IDを別のフォームに渡して、IDをテーブル 'TmpPlInvoice'に保存しています。それ以上の合併症を避けるために私はそれを加えなかった。私のために愚かさ。私はこれを編集させてください。 –

関連する問題