Django ManyToMany与ModelMultipleChoice错误的关系

时间:2019-01-11 05:19:49

标签: django django-models django-forms

我是Django的新手。因此,尝试使用内置功能而不是重写功能。我已经在用户和服务之间建立了ManyToMany关系。

意味着用户可以拥有许多服务,并且可以由许多用户获得服务。 (不确定我是否正确)

以下是我的模特

用户数据

from django.db import models
from django.contrib.auth.models import User
from services.models import Services

class Userdata(models.Model):
    username=models.OneToOneField(User,on_delete=models.CASCADE)
    tel=models.CharField(max_length=10,unique=True)
    address=models.CharField(max_length=100,null=True,blank=True)
    city=models.CharField(max_length=10,null=True,blank=True)
    zipcode=models.CharField(max_length=6,null=True,blank=True)
    services=models.ManyToManyField(Services,through='dashuser.UpcomingUserServices')

服务

from django.db import models

class Services(models.Model):
    sname=models.CharField(max_length=20)
    scost=models.IntegerField()

    def __str__(self):
        return self.sname

UpcomingUserService

from django.db import models
from services.models import Services
from log.models import Userdata

class UpcomingUserServices(models.Model):
    userdata=models.ForeignKey(Userdata,on_delete=models.CASCADE)
    service=models.ForeignKey(Services,on_delete=models.CASCADE)
    name=models.CharField(max_length=20)
    phone=models.CharField(max_length=10)
    date=models.DateField()
    address=models.CharField(max_length=100)
    zipcode=models.IntegerField()
    remarks=models.CharField(max_length=100,null=True,blank=True)

ServiceForm

from django import forms
from .models import UpcomingUserServices

class ServiceForm(forms.ModelForm):
    service=forms.ModelMultipleChoiceField(Services.objects.all(),widget=forms.CheckboxSelectMultiple())

    class Meta:
        model=UpcomingUserServices
        exclude=['userdata']

视图

def book(request):
    if request.method=='POST':
        serlist=[]
        f=ServiceForm(request.POST)
        if f.is_valid():
            s=f.save(commit=False)
            u=request.user
            u1=Userdata.objects.get(username_id=u.id)
            s.userdata_id=u1.id
            f.save()
            f.save_m2m()
            return HttpResponse('Done')
        else:
            return render(request,'ns.html',{'f':f})
    else:
        u=request.user
        u1=Userdata.objects.get(username_id=u.id)
        i={
            'name':u.first_name+" "+u.last_name,
            'phone':u1.tel,
            'email':u.email,
            'address':u1.address,
            'zipcode':u1.zipcode
        }
        f = ServiceForm(initial=i)
        return render(request,'ns.html',{'f':f})
# ns.html is where the form is rendered

提交表单时,出现以下错误

ValueError at /user/book
Cannot assign "<QuerySet [<Services: Lawn Mowing>, <Services: Lawn Fertilization>]>": "UpcomingUserServices.service" must be a "Services" instance

(/ user / book是视图的URL)

引用:

Traceback:

File "F:\My Projects\login\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "F:\My Projects\login\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "F:\My Projects\login\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "F:\My Projects\login\venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "F:\My Projects\login\dashuser\views.py" in book
  63.         if f.is_valid():

File "F:\My Projects\login\venv\lib\site-packages\django\forms\forms.py" in is_valid
  185.         return self.is_bound and not self.errors

File "F:\My Projects\login\venv\lib\site-packages\django\forms\forms.py" in errors
  180.             self.full_clean()

File "F:\My Projects\login\venv\lib\site-packages\django\forms\forms.py" in full_clean
  383.         self._post_clean()

File "F:\My Projects\login\venv\lib\site-packages\django\forms\models.py" in _post_clean
  398.             self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

File "F:\My Projects\login\venv\lib\site-packages\django\forms\models.py" in construct_instance
  60.             f.save_form_data(instance, cleaned_data[f.name])

File "F:\My Projects\login\venv\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
  854.         setattr(instance, self.name, data)

File "F:\My Projects\login\venv\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
  210.                     self.field.remote_field.model._meta.object_name,

Exception Type: ValueError at /user/book
Exception Value: Cannot assign "<QuerySet [<Services: Lawn Mowing>, <Services: Lawn Fertilization>]>": "UpcomingUserServices.service" must be a "Services" instance.

1 个答案:

答案 0 :(得分:0)

您通过中间模型使用UpcomingUserServices模型。因此UpcomingUserServices模型必须采用一个user和一个service。但是您的ServiceFormforms.ModelMultipleChoiceField接受了多项服务。

我知道您要实现的目标。但这是不正确的。

您正在使用中间表。因此,请检查intermediary many to manysimilar case question