1 回答
TA贡献1780条经验 获得超4个赞
你的service是ForeignKey:
service = models.ForeignKey(Services, on_delete=models.CASCADE)
AForeignKey表示您选择单个元素,而不是多个元素。您使用ManyToManyField[Django-doc]选择多个元素:
class Professionals_Services(models.Model):
professional = models.ForeignKey(User, on_delete=models.CASCADE)
service = models.ManyToManyField(Service)
您也不应该重写该post方法,并且可以使用LoginRequiredMixin[Django-doc]来确保用户已登录:
from django.contrib.auth.mixins import LoginRequiredMixin
class EditProfileServicesView(LoginRequiredMixin, CreateView):
login_url = reverse_lazy('professionals:login')
model = Professionals_Services
form_class = ProfileServicesUpdateForm
context_object_name = 'services'
template_name = 'accounts/edit-profile.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
在您中,Form您还应该返回清理后的数据:
class ProfileServicesUpdateForm(forms.ModelForm):
service = forms.ModelMultipleChoiceField(required=False, queryset=Services.objects.all())
class Meta:
model = Professionals_Services
fields = ['service']
def clean(self):
# this condition only if the POST data is cleaned, right?
cleaned_data = super(ProfileServicesUpdateForm, self).clean()
print(cleaned_data.get('service'))
return cleaned_data
注意:通常使用
settings.AUTH_USER_MODEL
[Django-doc]来引用用户模型比直接使用User
模型 [Django-doc]更好。
注意:Django 中的模型是用PerlCase编写的,而不是Snake_case,因此您可能需要将模型从 重命名
Professionals_Services
为ProfessionalService
。
注意:通常 Django 模型有一个单一的名称,所以
Services
而不是Service
.
添加回答
举报