Django中的表单。如何从表单初始化模型字段?

时间:2015-04-16 00:48:57

标签: django forms views models

在models.py中:

class Client(AbstractBaseUser):

    username = models.CharField(max_length=32, unique=True)
    email = models.EmailField('email address', unique=True, db_index=True)
    avatar = models.ImageField('avatar', upload_to='avatars')
    id = id(object)

class Order(models.Model):
    class Meta():
        db_table = 'order'

    short_desc = models.CharField(max_length=30)
    subject = models.ForeignKey(Subject, blank=True)
    user_id = models.ForeignKey('Client', to_field='id', related_name='client_id', default='0', blank=True)
    performer_id = models.ForeignKey('Client', to_field='id', related_name='performer_id', default='0', blank=True)
    worktype = models.ForeignKey(Type, blank=True)
    level = models.IntegerField(default=0, blank=True)
    readiness = models.BooleanField(default=False, blank=True)
    description = models.TextField(max_length=2000, blank=True)
    file = models.FileField(upload_to='orderfiles', blank=True)
    #maxdate = models.DateField(blank=True)
    addate = models.DateField(auto_now=True, blank=True)
    price = models.IntegerField(max_length=10, blank=True)
    responses = models.IntegerField(blank=True)

在forms.py中:

class AddOrderForm(forms.ModelForm):

    short_desc       = forms.CharField(widget=forms.TextInput,label="Краткое описание(послужит именем)")
    subject          = forms.ModelChoiceField(queryset=Subject.objects.all(), label="Предмет")
    worktype         = forms.ModelChoiceField(queryset=Type.objects.all(), label="Тип")
    level            = forms.IntegerField(widget=forms.TextInput,label="Уровень сложности (от 1 до 5)")
    description      = forms.CharField(widget=forms.TextInput,label="Полное описание")
    #maxdate          = forms.DateField(widget=forms.TextInput,label="maxdate")
    price            = forms.IntegerField(widget=forms.TextInput,label="Ваша цена")
    responses        = forms.IntegerField(widget=forms.TextInput,label="Кол-во ответов на заказ")

    class Meta:
        model = Order
        fields = ['short_desc',  'level', 'description', 'price', 'responses', 'subject', 'worktype']

在views.py中:

def addorder(request, user_id):
    """
    Adding Order view
    """
    if request.POST:
        form = AddOrderForm(request.POST)

        if form.is_valid():

            form.save()

            return redirect('/')


    else:
        return redirect('/')
    auth1 = auth.get_user(request).username
    return render_to_response('customer.html', { 'form': form,'username' : auth1}, context_instance=RequestContext(request))

我需要在user_id class Order之后立即初始化add中的字段order()。我应该在哪里做,以哪种方式?我需要这样的逻辑:Client添加OrderAddOrderForm然后user_id的{​​{1}}字段必须用对象初始化class Order class Client的{​​{1}}参数中{id}等于user_id

1 个答案:

答案 0 :(得分:2)

您可以在保存表单时使用commit=False执行此操作。这是使用具有较少字段的模型表单保存对象的典型方法。

def addorder(request, user_id):
    """
    Adding Order view
    """
    if request.POST:
        form = AddOrderForm(request.POST)

        if form.is_valid():

            order = form.save(commit=false)
            order.client_id = Client.objects.get(id=user_id)
            order.save()

            return redirect('/')


    else:
        return redirect('/')
    auth1 = auth.get_user(request).username
    return render_to_response('customer.html', 
             { 'form': form,'username' : auth1}, 
             context_instance=RequestContext(request))

免责声明:处理错误,例如: Client.objects.get()可能会失败。使用适当的字段进行搜索。