4

我正在尝试在 python django 中创建我自己的第一个项目。到目前为止,我所做的是一个简单的商店。当我点击这个:

item_details.html

<a href="{% url 'buy_item' pk=item.pk %}" class="submit">Kup teraz</a>

我将被重定向

网址.py

path('buy/<int:pk>', ItemCreate.as_view(), name='buy_item')

到这个表格:

表格.py

class BuyForm(forms.ModelForm):

    class Meta:
        model = Order
        fields = (
        'item',
        'delivery',
        'price',
        'buyer',)

有了这个观点:

视图.py

class ItemCreate(CreateView):
    model = Order
    fields = ['item', 'price', 'buyer', 'delivery']

    def get_initial(self):
        item = get_object_or_404(Item, pk=self.kwargs['pk'])
        self.initial.update({
            'buyer': self.request.user,
            'price': item.price,
            'item': item.pk,
        })
        return super(ItemCreate, self).get_initial()

模型.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.title
class Item(models.Model):
    seller = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    price = models.FloatField(null=False, blank=False)
    img = models.ImageField(blank=True, null=True,
        upload_to='covers/%Y/%m/%D/')
    published_date = models.DateTimeField(default=timezone.now)
    def __str__(self):
        return self.title

class Supplier(models.Model):
    title = models.CharField(max_length=100)
    def __str__(self):
        return self.title

class Delivery(models.Model):
    title = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    price_of_delivery = models.FloatField(null=False, blank=False)
    def __str__(self):
        return self.title

class Order(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE)
    order_date = models.DateTimeField(default=timezone.now)
    buyer = models.ForeignKey(User, on_delete=models.CASCADE)
    price = models.FloatField(null=False, blank=False)
    def __str__(self):
        return self.item

因为用户不应该编辑初始数据,所以我想让它们只读。

到目前为止我尝试过的是:

class BuyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super(BuyForm, self).__init__(*args, **kwargs)
       self.fields['buyer'].widget.attrs['readonly'] = True    

    class Meta:
        model = Order
        fields = (
        'item',
        'delivery',
        'price',
        'buyer',)

我的控制台中没有错误,但也没有结果。

我的 order_form.html 看起来:

{% extends 'shop/base.html' %}
{% block content %}

<div align="center">
    <h1>Buy item</h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Buy</button>
    </form>
</div>
<
{% endblock %}

我应该怎么做才能使“买家”、“价格”和“商品”只读?

4

4 回答 4

3

所有其他答案都很好且正确,但是当我创建您的示例时,这并没有解决问题。

实际的问题是您的视图从不首先使用您的表单 - 这就是为什么覆盖属性什么也没做!

更多关于基于类的视图和来自django 文档的自定义表单

视图.py

from django.shortcuts import get_object_or_404
from django.views.generic import CreateView
from .models import Item
from .forms import BuyForm

class ItemCreate(CreateView):
    form_class = BuyForm
    template_name = 'order_form.html'
    success_url = '/thanks/'

    def get_initial(self):
        item = get_object_or_404(Item, pk=self.kwargs['pk'])
        self.initial.update({
            'buyer': self.request.user.id,
            'price': item.price,
            'item': item.pk,
        })
        return super(ItemCreate, self).get_initial()

表格.py

from django import forms
from .models import Order


class BuyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BuyForm, self).__init__(*args, **kwargs)
        self.fields['buyer'].disabled = True

    class Meta:
        model = Order
        fields = (
            'item',
            'delivery',
            'price',
            'buyer',)
于 2019-04-18T15:42:01.380 回答
0

尝试这个:

class BuyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super(BuyForm, self).__init__(*args, **kwargs)
       self.fields['buyer'].required = False
       self.fields['buyer'].widget.attrs['disabled'] = "disabled" 

       ...

    def clean_buyer(self):
        instance = getattr(self, 'instance', None)
        if instance:
            return instance.buyer
        else:
            return self.cleaned_data.get('buyer', None)

但是禁用 attr 的文件将发布blank数据。这就是为什么我们重写该clean方法以将字段的值设置为实例中最初的值。

于 2019-04-18T13:51:17.417 回答
0

您正在寻找的是表单字段的disabled属性:
https ://docs.djangoproject.com/en/2.2/ref/forms/fields/#disabled

于 2019-04-18T14:13:47.250 回答
-2

另一种方法是使它们成为隐藏字段。将此添加到元...

class Meta:
    widgets = {
        'buyer': forms.HiddenInput(),
        'price': forms.HiddenInput(),
        'item': forms.HiddenInput(),
    }
于 2019-04-18T15:58:18.707 回答