Django Modelform-将字段值设置为外键

时间:2019-07-09 03:24:15

标签: python django django-forms modelform

我在我的应用程序中创建了两个模型:“处方”和“处方状态”。当用户在“ New_prescription”模型表单上单击“保存”时,我需要在“ Prescription”中添加“ Prescription_status”。

例如,在下面,我想添加“草稿”状态(PK = 1)。我不想设置默认状态。我一直在尝试一切,我想念的是什么?预先感谢!

models.py

# Static Prescription Status Types
class Prescription_status(models.Model):
    status = models.CharField(max_length=200)
    status_definition = models.TextField()

    def __str__(self):
        return '%s' % (self.status)

# Prescription Model
class Prescription(models.Model):
    order_id = models.AutoField(primary_key=True, unique=True)
    status = models.ForeignKey(Prescription_status, models.SET_NULL, null=True)

我将以下Prescription_status对象保存到数据库中,以供用户保存或编辑处方时参考:
status_id为“草稿”状态= 1
status_id为“准备签名”状态= 2
status_id的“已签名和授权”状态= 3

database chart showing PK for each status

forms.py

class PrescriptionForm(forms.ModelForm):
    class Meta:
        model = Prescription
        fields = ('medication', 'quantity', 'directions', 'refills', 'earliest_permitted_fill_date', 'daw',)
        widgets = {
             'earliest_permitted_fill_date': DatePickerInput(), # default date-format %m/%d/%Y will be used

     }

views.py

def new_rx(request):
    if request.method == "POST":
        form = PrescriptionForm(request.POST)
        if form.is_valid():
            prescription = form.save(commit=False)
            prescription.status = Prescription_status.objects.get(pk=form.cleaned_data['1'])
            prescription.save()
            return redirect('home')
    else:
        form = PrescriptionForm()
    return render(request, 'app/new_rx.html', {'form': form})

以上结果导致“ NameError:名称'Prescription_status'未定义”。正确的方法是什么?

0 个答案:

没有答案