Django Admin 没有将数据保存到数据库

Django Admin not saving data to the Database

我正在尝试将数据从我的 Django Admin 保存到我的数据库,但不知何故它没有发生。我在我的一个应用程序中创建了一个表单,我的管理员 uses.I 是 Django 的新手,我们将不胜感激任何帮助。 下面是相关代码:

models.py

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from django.db import models

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=100)
    bio = models.TextField(max_length=1000, blank=True, null=True)
    image = models.FileField()
    country = CountryField()
    city = models.CharField(max_length=100)
    twitter = models.CharField(max_length=100, null=True, blank=True)
    linkedin = models.CharField(max_length=100, null=True, blank=True)
    location = models.TextField()

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name


class Mentor(models.Model):
    mentor = models.CharField(max_length=100)
    mentee = models.CharField(max_length=100)

    def __unicode__(self):
        return self.mentee

    def __str__(self):
        return self.mentee

forms.py

from django import forms
from models import UserProfile, Mentor
from django_countries.fields import CountryField
from django.contrib.auth.models import User
from reports.models import Reports

class UserProfileForm(forms.ModelForm):

    name = forms.CharField(max_length=100)
    bio = forms.Textarea()
    image = forms.FileField(label='Profile Photo')
    country = CountryField(blank_label='(Select Country)')
    city = forms.CharField(max_length=100)
    twitter = forms.CharField(max_length=100, required=False)
    linkedin = forms.CharField(max_length=100, required=False)

    class Meta:
        model = UserProfile
        exclude = ('user',)

class MentorForm(forms.ModelForm):
    mentor_choices = tuple(UserProfile.objects.filter(user__is_staff=1).order_by('name').values_list('name', 'name'))
    mentee_choices = tuple(UserProfile.objects.exclude(user__is_staff=1).order_by('name').values_list('name', 'name'))
    mentor_name = forms.ChoiceField(choices=mentor_choices)
    mentee_name = forms.ChoiceField(choices=mentee_choices)

    def save(self, commit=True):
        mentor_name = self.cleaned_data.get('mentor_name', None)
        mentor_name = self.cleaned_data.get('mentee_name', None)
        return super(MentorForm, self).save(commit=commit)

    class Meta:
        model = Mentor
        fields= ('mentor_name', 'mentee_name')

admin.py

from django.contrib import admin
from .models import UserProfile, Mentor
from.forms import MentorForm

class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user',)
    search_fields = ['user']

    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.save()
admin.site.register(UserProfile, UserProfileAdmin )

class MentorAdmin(admin.ModelAdmin):
    list_display = ('__unicode__','mentee')
    search_fields = ['mentee', 'mentor']
    form = MentorForm

    fieldsets = (
        (None,{
            'fields': ('mentor_name', 'mentee_name'),
        }),
    )

    def save_model(self, request, obj, form, change):
        super(MentorAdmin, self).save_model(request, obj, form, change)

admin.site.register(Mentor, MentorAdmin )

UserProfile 工作正常,但管理中的 Mentor 表单没有在数据库中保存任何内容。它在数据库中创建了空白条目,所以我知道前端和后端正在对话,但没有数据被传递。任何帮助都会很有帮助

def save(self, commit=True):
    # here you define `mentor_name`. OK.
    mentor_name = self.cleaned_data.get('mentor_name', None)
    # here you redefine `mentor_name`. I guess it is a typo and should be `mentee_name`.
    mentor_name = self.cleaned_data.get('mentee_name', None)
    # And... you don't do anything with these variables.
    return super(MentorForm, self).save(commit=commit)

此方法等同于:

def save(self, commit=True):
    return super(MentorForm, self).save(commit=commit)

这相当于根本不覆盖保存方法。

那这个呢?

def save_model(self, request, obj, form, change):
    super(MentorAdmin, self).save_model(request, obj, form, change)

重写方法并仅调用具有完全相同参数的父方法的目的是什么?

但实际问题在这里:

mentor_choices = tuple(UserProfile.objects.filter(user__is_staff=1).order_by('name').values_list('name', 'name'))
mentee_choices = tuple(UserProfile.objects.exclude(user__is_staff=1).order_by('name').values_list('name', 'name'))
mentor_name = forms.ChoiceField(choices=mentor_choices)
mentee_name = forms.ChoiceField(choices=mentee_choices)

class Meta:
    model = Mentor
    fields = ('mentor_name', 'mentee_name')

您使用 ModelForm,但 Mentor 的字段中的 none 在 fields 中。除了使用 Mentor.mentor = NoneMentor.mentee = None 保存一行之外,您还希望它做什么?你甚至都不提那些领域。

你为什么要使用 CharField 作为 Mentor.mentorMentor.mentee 而你可能需要一个外键。

class Mentor(models.Model):
    mentor = models.ForeignKey(UserProfile, models.PROTECT,
                               related_name='mentees')
    mentee = models.ForeignKey(UserProfile, models.PROTECT,
                               related_name='mentors')

class MentorForm(forms.ModelForm):

    class Meta:
        model = Mentor
        fields = ('mentor', 'mentee')

    mentor = forms.ModelChoiceField(queryset=UserProfile.objects.filter(
        user__is_staff=True).order_by('name'))
    mentee = forms.ModelChoiceField(queryset=UserProfile.objects.exclude(
        user__is_staff=True).order_by('name'))

甚至更好:

class Mentor(models.Model):
    mentor = models.ForeignKey(
        UserProfile, models.PROTECT, related_name='mentees',
        limit_choices_to={'user__is_staff': True},
    )
    mentee = models.ForeignKey(
        UserProfile, models.PROTECT, related_name='mentors',
        limit_choices_to={'user__is_staff': False},
    )

这避免了您创建表单。