简体   繁体   English

将额外的字段保存到 django model 除了 django 表单中存在的字段(对于同一型号)

[英]Save extra fields to django model apart from the fields which were present in django form(for the same model)

I have a Django model with few fields, In the django forms which is created using that django models. I have a Django model with few fields, In the django forms which is created using that django models. While using the forms.save method I also want to save the extra fields which were not present in Django forms but present in django models.在使用 forms.save 方法时,我还想保存 Django forms 中不存在但存在于 Z2B9AFB89A6ACC10ADCA75B1 模型中的额外字段。

models.py模型.py

class NewProvisionalEmployeeMail(models.Model):
    STATUS_CHOICES = (
    (1, ("Permanent")),
    (2, ("Temporary")),
    (3, ("Contractor")),
    (4, ("Intern"))
    )
    PAY_CHOICES = (
    (1, ("Fixed")),
    (2, ("Performance Based")),
    (3, ("Not Assigned")),
    )
    POSITION_CHOICES = ()
    for i, name in enumerate(Position.objects.values_list('position_name')):
        POSITION_CHOICES += ((i, name[0]),)
    email = models.EmailField(max_length=70, null=False, blank=False, unique=False)
    token = models.TextField(blank=False, null=False)
    offer_sent_by = models.CharField(max_length=50)
    position_name = models.IntegerField(choices=POSITION_CHOICES, null=True, blank=True)
    accepted = models.BooleanField(default=False)
    name=models.CharField(max_length=30)
    user_name=models.CharField(max_length=30)
    pay = models.IntegerField(default=0)
    title = models.CharField(max_length=25, null=True, blank=True)
    pay_type = models.IntegerField(choices=PAY_CHOICES, default=3)
    emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1)

    def __str__(self):
        return str(self.offer_sent_by) +" to " + str(self.email)


    def clean(self):
        if(NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).exists()):
            NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).delete()

    def save(self, **kwargs):
        self.clean()
        return super(NewProvisionalEmployeeMail, self).save(**kwargs)

If you see it has following fields: email , token , offer_sent_by , position_name , accepted , name , user_name , pay , title , pay_type , emp_type .如果您看到它有以下字段: emailtokenoffer_sent_byposition_nameacceptednameuser_namepaytitlepay_typeemp_type Now I only want the following fields in my forms: email , position_name , name , user_name , pay , title , pay_type , emp_type and not token and offer_sent_by whose values will be determined in my views.py using some logic.现在我只想要 forms 中的以下字段: emailposition_namenameuser_namepaytitlepay_typeemp_type而不是tokenoffer_sent_by ,它们的值将在我的 views.py 中使用一些逻辑来确定。

forms.py forms.py

class NewProvisionalEmployeeMailForm(ModelForm):
    class Meta:
        model = NewProvisionalEmployeeMail
        fields = ['email', 'position_name',
        'name', 'user_name', 'pay',
        'title', 'pay_type', 'emp_type',
        ]

According to my logic in my views.py the other fields values are generated inside the function, but since to save the model we have to use formname.save , here it is NewProvisionalEmployeeMailForm.save() .根据我在 views.py 中的逻辑,其他字段值是在 function 中生成的,但是由于要保存 model,我们必须使用formname.save ,这里是NewProvisionalEmployeeMailForm.save() However this will only save the fields which were coming from my template form, how do I also add other left fields while saving using this dunction.但是,这只会保存来自我的模板表单的字段,如何在使用此功能保存时添加其他左侧字段。

views.py视图.py

def sendoffer(request):
    context = {}
    new_emp_form = NewProvisionalEmployeeMailForm();
    context['form'] = new_emp_form
    hostname = request.get_host() + "/dummyoffer"
    if request.method=='POST':
        new_emp_form = NewProvisionalEmployeeMailForm(request.POST)
        if(new_emp_form.is_valid()):
            token = VALUE COMES FROM LOGIC
            offer_sent_by = VALUE COMES FROM LOGIC
            # I also want to save the fields token, offer_sent_by in my models using this form save method
            new_emp_form.save()

    return render(request, 'mainapp/offer.html',context)

As you see new_emp_form save method will only save only those fields that are present in the form and not the fields token and offer_sent_by which is also part of the model.如您所见new_emp_form保存方法将仅保存表单中存在的那些字段,而不保存字段token和 offer_sent_by,这也是offer_sent_by的一部分。 How do save the fields using form.save method?如何使用 form.save 方法保存字段?

Saving the form returns an instance of NewProvisionalEmployeeMail , so you can simply catch the returned object in a variable and set it's properties afterwards:保存表单会返回一个NewProvisionalEmployeeMail的实例,因此您可以简单地将返回的 object 捕获到一个变量中,然后设置它的属性:

if(new_emp_form.is_valid()):
    token = VALUE COMES FROM LOGIC
    offer_sent_by = VALUE COMES FROM LOGIC
    new_emp = new_emp_form.save(commit=False)
    new_emp.token = token
    new_emp.offer_sent_by = offer_sent_by
    new_emp.save()

for the first time we can change it as following new_emp = new_emp_form.save(commit=False) so that i wont save to the database.我们第一次可以将其更改为new_emp = new_emp_form.save(commit=False)这样我就不会保存到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM