如何使用输入标签字段,而不是默认的Django? [英] how to use input tag field instead default django?

查看:31
本文介绍了如何使用输入标签字段,而不是默认的Django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个在线订购系统.某人可以同时订购几件商品.因此,我使用了 inlineformset ,有时使用了 {{form.field_name}} 来防止某些样式和js事件,为此,我决定手动使用输入字段>< input> 标签,在我以前的项目中我没有遇到过这样的挑战.现在我很困惑如何实现它?

i'm trying to make an online order system. someone can order several items at the same time. for that reason i have used inlineformset and sometimes using {{form.field_name}} prevent some styles and js events , for that purpose i decided to use input fields manually <input> tags , i didnt faced such challenges in my previous projects. now im confused how to achieve it?

这是我的模特.py

class Item(models.Model):
     items = models.CharField(max_length=50)
     #others
     def __str__(self):
        return self.items 

class Invoice(models.Model):
     seller = models.ForeignKey(User,on_delete=models.CASCADE)
     customer = models.CharField(max_length=50)
     items = models.ManyToManyField(Item,through='ItemsInvoice')

class ItemsInvoice(models.Model):
     invoice= models.ForeignKey(Invoice,on_delete=models.CASCADE)
     item = models.ForeignKey(Item,on_delete=models.CASCADE)
     quantity = models.IntegerField()
     price = models.IntegerField()

我在视图中使用了基于函数的视图这是我的views.py

i used function based view in view and this is my views.py

@login_required
def createClientInoiveView(request):
item_names = Item.objects.all()
if request.method == 'POST':
    customer = request.POST['customer']
    seller = request.user
    obj = CustomerInvoice.objects.create(seller=seller,customer=customer)        
    # inlineformset fields 
    item = request.POST['items']
    quantity = request.POST['quantity']
    price = request.POST['price']
    cash = request.POST['cash']
    discount = request.POST['discount']
    items = InvoiceItem.objects.create(item=item,quantity=quantity,price=price,cash=cash,discount=discount)
    
    with transaction.atomic():
        obj = obj.save(commit=False)
        if obj.is_valid and item.is_valid():
            item.invoice = obj
            obj.save()
            item.save()
            return redirect(reverse_lazy('invoiceapp:detail-invoice',kwargs={'pk':obj.pk}))

return render(request,'invoiceapp/create_invoice.html',{'item_names':item_names})

这是我的html表单

<form method="POST">{% csrf_token %}
    {{items.management_form}}

    <div class="w-full  md:w-11/12 mx-auto realative p-2 bg-gray-200 wasll" style="direction: ltr !important;">
    
        <div class="p-1 pr-2 pb-1 text-xs border border-black rounded-lg flex flex-wrap">          
            <div class="flex w-8/12 lg:w-9/12">              
                <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted">
                  <input type="text" name="customer" class="bg-transparent w-full text-right focus:outline-none" id="">
                </div>  
                <div class="">
                  :  name
                </div>
            </div>
        </div>
        <!-- table -->
        <div class="mt-1 border border-black">
            <!-- header -->
            <div class="flex flex-wrap grayBG text-sm text-white">                             
                <div class="w-16 md:w-1/12  border-r text-center">
                    price
                </div>
                <div class="w-16 md:w-2/12  border-r text-center">
                    quantity
                </div>
                <div class="w-20 md:w-2/12  border-r text-center">
                    items
                </div>
            
            </div>
            <!-- inputs -->
            <div id="allInp">
                <div class="flex flex-wrap grayBG text-sm text-black inp">

                    <div class="w-16 md:w-1/12 p-2 border-r text-center ">
                        <input type="number" name="price" onkeyup="totalSum()"  class="rounded-lg nrx focus:outline-none py-1 w-full">
                    </div>
                    <div class="w-16 md:w-2/12 p-2 border-r text-center ">
                        <input type="number" name="quantity" onkeyup="totalSum()"  class="rounded-lg focus:outline-none py-1 w-full">
                    </div>
                    <div class="w-20 md:w-2/12 p-2 border-r text-center">
                        <datalist id="types">
                            {% for i in item_names %}
                            <option value="{{i}}">
                            {% endfor %}
                          </datalist>
                        <input type="text" name="items" list="types" class="w-full rounded-lg focus:outline-none py-1">                    
                    </div>
                
                </div>
            </div>
        </div>
        
    </div>

    <div class="w-6/12 text-center mt-1 mx-auto mb-6">
        <button class="w-full bg-white text-gray-900" id="submit">submit</button>
    </div>
</form>
<script>
    $(function(){

        $('#allInp').formset({
            prefix:'{{items.prefix}}',
            addText:'add new row',
            addCssClass:'btn btn-info ',
            deleteText:'delete',
            deleteCssClass:'delFun',

        })  
  
</script>

但是我一直收到此错误消息

but i keep getting this error message

无法分配'mouse'":"ItemsInvoice.item";必须是"Item"实例.

Cannot assign "'mouse'": "ItemsInvoice.item" must be a "Item" instance.

还有我的这些表格.py

and also these my forms.py

class CustomerInvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice
        fields = [
            'customer'
        ]

class CustomerInvoiceItemForm(forms.ModelForm):
item = forms.ModelChoiceField(queryset=Item.objects.all(),empty_label='---')
class Meta:
    model = ItemsInvoice
    fields = ['item','quantity','price']

CustomerInvoiceInlineFormset = inlineformset_factory(
     Invoice,ItemsInvoice,form=CustomerInvoiceItemForm,
     fields=('item','quantity','price'),extra=1
     )   

我也尝试过使用它

#other code

obj=CustomerInvoiceItemForm()
#instead of > CustomerInvoice.objects.create(seller=seller,customer=customer)
#other code
#and using this > items = CustomerInvoiceInlineFormset(request.POSt)
#instead of  > items = InvoiceItem.objects.create(item=item,quantity=quantity,price=price,cash=cash,discount=discount)

但是什么也没保存?为了得到我想要的东西,我不应该改变一些东西吗?

but saves nothing? isn't there something i should change in order to get what i trying for?

推荐答案

在模板< option value =" {{i}}"> 中输出Ìtem.__ str __ 作为键,因此无法解析Ìtem.

In template <option value="{{i}}"> outputs Ìtem.__str__ as the key and no Ìtem can be resolved from this.

更改为< option value =" {{i.pk}}>

这篇关于如何使用输入标签字段,而不是默认的Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆