невозможно разрешить ключевое слово 'user' в поле - django ошибка - PullRequest
0 голосов
/ 23 апреля 2020

это сообщение об ошибке, которое я получаю ---> Невозможно разрешить ключевое слово 'user' в поле. Возможные варианты: date_joined, электронная почта, подтверждение электронной почты, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, порядок, пароль, профиль, user_permissions, useraddress, userdefaultaddress, username, userstripe <---- это подсветка эти две части кода являются ключевыми областями, в которых, кажется, возникает проблема. <strong>new_order = Order.objects.get (корзина = корзина) ///// new_order.user = User.objects.get (пользователь = request.user)

вся помощь будет очень полезна в решении этой проблемы!

views.py - orders

import time 
import stripe

from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.contrib.auth.models import User
from django.shortcuts import render, HttpResponseRedirect
from django.urls import reverse



# Create your views here.

from users.forms import UserAddressForm
from carts.models import Cart
from .models import Order
from users.models import Profile, UserAddress, UserAddressManager
from .utils import id_generator


stripe.api_key = settings.STRIPE_SECRET_KEY 

def orders(request):
    context = {}
    template = "orders/user.html"
    return render(request, template, context)

@login_required
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponseRedirect(reverse("cart"))

    try:
        **new_order = Order.objects.get(cart=cart)**
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart=cart
        **new_order.user = User.objects.get(user=request.user)**
        new_order.order_id = id_generator()
        new_order.final_total = cart.total 
        new_order.save()
    except:
        return HttpResponseRedirect(reverse("cart"))

    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None

    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None


    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(user=request.user)


    if new_order.status == "Finished":
        del request.session['cart_id']
        del request.session['items_total']
        return HttpResponseRedirect(reverse("cart"))

    key = settings.STRIPE_PUBLISHABLE_KEY

    context = {
    "order": new_order,
    "address_form": address_form,
    "current_addresses": current_addresses,
    "billing_addresses": billing_addresses,
    "key": key,
    }
    template = "orders/checkout.html"
    return render(request, template, context)

models.py -orders

from django.db import models

# Create your models here.
from carts.models import Cart
from django.conf import settings
from django.contrib.auth.models import User

STATUS_CHOICES =(
        ("Started", "Started"),
        ("Abandoned", "Abandoned"),
        ("Finished", "Finished"),
    )

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
    order_id = models.CharField(max_length=120, default='ABC', unique=True)
    cart = models.ForeignKey('carts.Cart', on_delete=models.CASCADE)
    status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Started")
    final_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __string__(self):
        return self.order_id

models.py - users

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

1 Ответ

1 голос
/ 23 апреля 2020

Может быть

**new_order.user = User.objects.get(user=request.user)**

new_order.user = User.objects.get(pk=request.user.pk)
...