我有一个django电子商务项目,在我决定对其进行改进之前,它的运行情况良好。用户下订单,每次下订单时都必须始终输入其详细信息(姓名,emil,地址等),所以我决定升级该应用程序,以便用户注册后无需再次输入详细信息。
orders / models.py
from django.db import models
from django.contrib.auth.models import User
from shop.models import Product
from decimal import Decimal
from django.core.validators import MinValueValidator,MaxValueValidator
from coupons.models import Coupons
class order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
postal_code = models.CharField(max_length=50)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
coupon = models.ForeignKey(Coupons,related_name='orders',on_delete=models.CASCADE ,null=True,blank=True)
discount = models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(100)])
class Meta:
ordering = ('-created',)
verbose_name = "order"
verbose_name_plural = "orders"
def __str__(self):
return 'Order {}'.format(self.id)
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
def get_total_cost_after_discount(self):
total_cost = sum(item.get_cost() for item in self.items.all())
return total_cost - total_cost * (self.discount / Decimal('100'))
class OrderItem(models.Model):
order = models.ForeignKey(order,related_name='items',on_delete=models.CASCADE)
product = models.ForeignKey(Product,related_name='order_items',on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10,decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
class Meta:
verbose_name = "OrderItem"
verbose_name_plural = "OrderItems"
def __str__(self):
return '{}'.format(self.id)
def get_cost(self):
return self.price * self.quantity
我创建了帐户应用程序和扩展的django用户,以便用户可以注册地址,以便用户不必每次下订单时都键入地址。 account / models.py
class UserProfile(models.Model):
user = models.OneToOneField(User,related_name='UserProfiles',on_delete=models.CASCADE)
country = models.CharField(max_length=300, default='Saudi Arabia')
city = models.CharField(max_length=100, default='')
phone = models.CharField(max_length=15,default='')
image = models.ImageField(upload_to='profile_image', blank=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(null=True)
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
并重写: orders / models.py
class order(models.Model):
user = models.ForeignKey(User,on_delete=models.DO_NOTHING)
address = models.ForeignKey(UserProfile,on_delete=models.DO_NOTHING)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
coupon = models.ForeignKey(Coupons,related_name='orders',on_delete=models.CASCADE ,null=True,blank=True)
discount = models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(100)])
现在我的问题是,如果用户之前输入过信息,或者用户使用地址填写表单,我该如何修复视图以显示带有信息的用户地址表格
views.py
@login_required
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
if cart.coupon:
order.coupon = cart.coupon
order.discount = cart.coupon.discount
order.save()
for item in cart:
OrderItem.objects.create(
# user = User.username,
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
cart.clear()
context = {
'order':order,
}
return render(request, 'created.html',context)
else:
form = OrderCreateForm()
context = {
'cart':cart,
'form':form
}
return render(request, 'create.html',context)
orders / forms.py
from django import forms
from .models import order
class OrderCreateForm(forms.ModelForm):
class Meta:
model = order
fields = ('first_name','last_name','email','address','postal_code','city',)
答案 0 :(得分:0)
我没有看到您的OrderCreateForm
,但是我假设它具有与UserProfile
中的字段匹配的字段。如果是这样,请尝试更改视图代码以从配置文件中提取数据以填充initial
数据:
@login_required
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
if cart.coupon:
order.coupon = cart.coupon
order.discount = cart.coupon.discount
order.save()
for item in cart:
OrderItem.objects.create(
# user = User.username,
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
cart.clear()
context = {
'order':order,
}
return render(request, 'created.html',context)
else:
if request.user and hasattr(request.user, 'UserProfiles'):
profile = request.user.UserProfiles
initial = {
'first_name', request.user.first_name,
'last_name', request.user.last_name,
'email', request.user.email,
'address': profile.address,
'city': profile.city
}
else:
initial = {}
form = OrderCreateForm(initial=initial)
context = {
'cart':cart,
'form':form
}
return render(request, 'create.html',context)