我正在尝试在 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 %}
我应该怎么做才能使“买家”、“价格”和“商品”只读?