因此,我看到在不同情况下发布了相同的问题,但我无法让我的工作。基本上试图找到一个模型实例,如果它已经存在并创建一个新实例,如果它不存在 - 基于实例是否与用户的用户名具有相同的字段
我尝试了 get_object_or_404 甚至将主键更改为模型类中的字段。
这是models.py
class Cart(models.Model):
user = models.CharField(max_length=30)
@classmethod
def create(cls, user):
user = cls(user=user)
return user
def __str__(self):
"""String for representing the Model object."""
return f'{self.id} {self.user}'
这是views.py
def cart(request, pk):
try:
pizza = PizzaInstance.objects.get(id=pk)
# get the topping(s)
topping_1 = int(request.POST["topping1"])
topping = PizzaTopping.objects.get(pk=topping_1)
# get the username
user = request.user.username
# check if the user already has an order
try:
order = Cart.objects.get(user=user)
except KeyError:
order = Cart.create([user])
order.save()
用户创建
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
我希望看到订单被保存,新实例被创建,甚至新实例被添加到购物车中。
错误是 get is - 购物车匹配查询不存在。
哆啦的时光机
哔哔one
慕莱坞森
相关分类