我正在尝试用python django创建我自己的第一个项目。到目前为止,我所做的是一家简单的商店。 当我单击此按钮时:
item_details.html
<a href="{% url 'buy_item' pk=item.pk %}" class="submit">Kup teraz</a>
我将被重定向
urls.py
path('buy/<int:pk>', ItemCreate.as_view(), name='buy_item')
此表单:
form.py
class BuyForm(forms.ModelForm):
class Meta:
model = Order
fields = (
'item',
'delivery',
'price',
'buyer',)
使用此视图:
views.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()
models.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 %}
我应该怎么做才能使“买方”,“价格”和“项目”变为只读状态?
答案 0 :(得分:1)
所有其他答案都是正确的,但是当我创建您的示例时,这并不能解决问题。
实际的问题是,您的视图永远不会首先使用您的表单-这就是为什么覆盖属性什么都不做的原因!
有关来自django docs的自定义表单的基于类的视图的更多信息
views.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()
forms.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',)
答案 1 :(得分: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)
但具有禁用的属性的文件将发布blank
数据。这就是为什么我们重写clean
方法将字段的值设置为实例中原来的值的原因。
答案 2 :(得分:0)
您要查找的是表单字段的disabled
属性:
https://docs.djangoproject.com/en/2.2/ref/forms/fields/#disabled
答案 3 :(得分:0)
另一种方法是使它们成为隐藏字段。将此添加到Meta ...
class Meta:
widgets = {
'buyer': forms.HiddenInput(),
'price': forms.HiddenInput(),
'item': forms.HiddenInput(),
}