Django 如何在不使用默认用户的情况下使用WishList分配UserProfile

Django 如何在不使用默认用户的情况下使用WishList分配UserProfile,django,django-models,django-rest-framework,django-views,Django,Django Models,Django Rest Framework,Django Views,我有一个包含模型UserProfile()的应用程序 连接到默认用户(用户)。我想用一个愿望列表模型连接我的用户 class WishList(models.Model): toy_name_wish = models.ForeignKey(Toy, on_delete=models.CASCADE) user_wish = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self

我有一个包含模型UserProfile()的应用程序

连接到默认用户(用户)。我想用一个愿望列表模型连接我的用户

class WishList(models.Model):
    toy_name_wish = models.ForeignKey(Toy, on_delete=models.CASCADE)
    user_wish = models.ForeignKey(UserProfile, on_delete=models.CASCADE)

    def __str__(self):
        return self.user_wish
使用带有
def post(self,request)的通用视图:
我为一个玩具创建了简单的逻辑,它将作为用户的愿望项目显示在管理部分

class DetailToyView(TemplateView):
    template_name = 'app/detail_toy.html'
    #other defs

    def post(self, request, toy_id):
        toy = get_object_or_404(Toy, pk=toy_id)
        user_profile = UserProfile()
        wishlist = WishList() 
        try:
            selected_toy = get_object_or_404(Toy, pk=toy_id) 
    except(KeyError, Toy.DoesNotExist):
        return render(request, 'app/detail_toy.html', {'toy': toy})
    else:
        user_profile.user = self.request.user
        user = user_profile.user
        wishlist.toy_name_wish = toy
        wishlist.user_wish = user
        wishlist.save()
        return HttpResponseRedirect(reverse('app:detail-category-toy', args=(toy.id,)))
如果重要的话,这是我的url.py文件

from django.urls import path
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views

app_name = 'app'
urlpatterns = [
    path('', views.index, name='index'), # INDEX
    path('personal-page/', views.personal_page, name='personal-page'),
    # SIGN_IN, SIGN_OUT AND SIGN_UP
    path('sign-in/', auth_views.login,
        {'template_name': 'app/sign_in.html'},
        name='sign-in'),
    path('sign-out/', auth_views.logout,
        {'next_page': '/'},
        name='sign-out'),
    path('sign-up/', views.sign_up, name='sign-up'),
    # DETAIL_PAGES
    #url(r'^book-detail/(?P<book>[0-9]+)/$', views.detail_book, name='book'),
    url(r'^detail_category_toy/(?P<category_id>[0-9]+)/$', views.detail_category_toy, name='detail-category-toy'),
    url(r'^detail-toy/(?P<toy_id>[0-9]+)/$', views.DetailToyView.as_view(), name='toy')]
从django.url导入路径
从django.conf.url导入url
从…起导入视图
从django.contrib.auth导入视图作为auth_视图
应用程序名称='应用程序'
URL模式=[
路径(“”,views.index,name='index'),#index
路径('personal-page/',views.personal_page,name='personal-page'),
#登录、注销和注册
路径('sign-in/',auth_views.login,
{'template_name':'app/sign_in.html'},
name='sign-in'),
路径('sign-out/',auth_views.logout,
{'next_page':'/'},
name='sign-out'),
路径('sign-up/',views.sign_-up,name='sign-up'),
#详情页
#url(r“^book detail/(?P[0-9]+)/$”,views.detail_book,name='book'),
url(r“^detail\u category\u toy/(?P[0-9]+)/$”,views.detail\u category\u toy,name='detail-category-toy'),
url(r'^detailtoy/(?P[0-9]+)/$),views.DetailToyView.as_view(),name='toy')]
因此,当我点击按钮时,问题是我得到了一个错误

ValueError at /detail-toy/2/
Cannot assign "<SimpleLazyObject: <User: admin>>": "WishList.user_wish" must be a "UserProfile" instance.
ValueError位于/detail/2/
无法分配“”:“愿望列表。用户\u愿望”必须是“UserProfile”实例。
这意味着我不能使用user.username 那么,如何获得UserProfile实例而不是基本用户模型呢


附言:很抱歉有些愚蠢的变量被称为

嗯,你眼前的问题是你正在将用户设置为愿望列表对象,而不是用户配置文件。保存前的行应为:

wishlist.user_wish = user_profile
但这里确实发生了很多奇怪的事情。一个用户只能有一个UserProfile,听起来不错,但在这个视图中,您总是创建一个新的UserProfile;如果该用户已经有配置文件,这将导致错误。您的愿望列表模型实际上不是一个列表,而是一个个人资料和一个玩具之间的单一关系

这里您实际需要的是UserProfile和Toy之间的多对多关系,即愿望列表:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=50, default='')
    phone = models.IntegerField(default='0')
    image = models.ImageField(upload_to='profile_image', blank=True)
    wishlist = models.ManyToManyField('Toy')
(而且您根本不需要愿望列表模型)

在您的视图中,使用
get\u或\u create
获取现有配置文件或创建新配置文件:

def post(self, request, toy_id):
    toy = get_object_or_404(Toy, pk=toy_id)
    user_profile = get_or_create(UserProfile, user=request.user)
    user_profile.wishlist.add(toy)
    return HttpResponseRedirect(reverse('app:detail-category-toy', args=(toy.id,)))

好的,您当前的问题是您正在将用户设置为愿望列表对象,而不是用户配置文件。保存前的行应为:

wishlist.user_wish = user_profile
但这里确实发生了很多奇怪的事情。一个用户只能有一个UserProfile,听起来不错,但在这个视图中,您总是创建一个新的UserProfile;如果该用户已经有配置文件,这将导致错误。您的愿望列表模型实际上不是一个列表,而是一个个人资料和一个玩具之间的单一关系

这里您实际需要的是UserProfile和Toy之间的多对多关系,即愿望列表:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=50, default='')
    phone = models.IntegerField(default='0')
    image = models.ImageField(upload_to='profile_image', blank=True)
    wishlist = models.ManyToManyField('Toy')
(而且您根本不需要愿望列表模型)

在您的视图中,使用
get\u或\u create
获取现有配置文件或创建新配置文件:

def post(self, request, toy_id):
    toy = get_object_or_404(Toy, pk=toy_id)
    user_profile = get_or_create(UserProfile, user=request.user)
    user_profile.wishlist.add(toy)
    return HttpResponseRedirect(reverse('app:detail-category-toy', args=(toy.id,)))

谢谢,帮了大忙汉克斯,帮了大忙