排除ModelForm中的字段

时间:2014-05-03 11:04:59

标签: jquery django

根据要求,我将包括我的所有模型和表单字段。

型号:

from django.db import models
from django.contrib.auth.models import User
from taggit.managers import TaggableManager


class StudentProfile(models.Model):

  student = models.OneToOneField(User)
  name = models.CharField(max_length=30)
  website = models.URLField(max_length=50)


  def __unicode__(self):
   return self.user.username

class Skills(models.Model):

   student = models.ForeignKey(StudentProfile)
   title = models.CharField(max_length=50)

   tags = TaggableManager()

   def __unicode__(self):
    return self.student

class Experience(models.Model):

    student = models.ForeignKey(StudentProfile)

    company = models.CharField(max_length=25)
    profile = models.CharField(max_length=25)


    def __unicode__(self):
         return self.student

的ModelForm

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from models import StudentProfile


class StudentProfileForm(forms.ModelForm):

   class Meta:
   model = StudentProfile
       exclude = ['student']

   def __init__(self, user, *args, **kwargs):
         self._user = user
         super(StudentProfileForm, self).__init__(*args, **kwargs)

class UserForm(forms.ModelForm):

    class Meta:
    model = User
    fields = ('username', 'password')

    def clean_username(self):
     username = self.cleaned_data['username']

     try:
       User.objects.get(username = username)
       raise forms.ValidationError("That username is already taken"+username)

     except User.DoesNotExist:

       return username

def clean_password(self):
    password = self.cleaned_data.get('password', '')
    if password == '':
         raise forms.ValidationError("Password be atleast 2 characters ")

    return password 

views.py:

from forms import StudentProfileForm
from django.contrib.auth.models import User


def editbio(request):

 if request.method == 'POST':

    student = User(username = request.user)
    basic_form = StudentProfileForm(data=request.POST, user=student)

    if basic_form.is_valid():

        info = basic_form.save(commit=False)
        info.student = request.user
        info.save()

我正在尝试从modelform中排除'user',因此我可以将当​​前用户添加到其中。但我一直在形成错误:

<ul class="errorlist"><li>student<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

我正在通过以下方式获取帖子数据(来自表格):

$(function editinfo(){

$(".inline-form").submit(function() {

    $.ajax({
    url : "/editbio",
    type : "POST",
    dataType: "json",

    data :

        $(this).serialize(),


    success : function(json) {
            $('.result').html( 'Server Response: ' + json.server_response);
        },

    error: function(data) {
            $(".result").html("Something went wrong!");
        }

    });

    return false;

});

});

我搜索过很多结果但没有成功。虽然我在表单中使用了“排除”,但我仍然在print basic_form.fields中显示“学生”字段 request.POST的内容:http://pastebin.com/eLQfTFB1

让我知道我在这里做错了什么,任何帮助将不胜感激。感谢。

3 个答案:

答案 0 :(得分:0)

basic_form = StudentProfileForm(data=request.POST, user=student) 应该 basic_form = StudentProfileForm(request.POST)

编辑:对于子孙后代,问题结果是一个空白问题。向Python开发人员提供建议,将编辑器设置为仅使用空格或仅使用标签。

答案 1 :(得分:0)

请参阅http://www.djangofoo.com/67/changing-request-post-values-querydict-immutable

...
student = User(username = request.user)
post_values = request.POST.copy()
post_values['student'] = student
basic_form = StudentProfileForm(data=post_values)
.......

答案 2 :(得分:-1)

使用exclude = ['student']代替fields = ('name', 'website'), 它应该工作。

fields用于确定您希望在模板中显示哪些字段(当您使用form.as_pform.as_ul生成表单时,这是必需的)

但这里很棘手:

StudentProfileForm形式覆盖student并使其不是必需的,如下所示:

student = forms.CharField(required=False)

如果你想知道它没有副作用。