【问题标题】:Django auto assign value to foreign key within a form?Django自动为表单中的外键赋值?
【发布时间】:2016-01-08 13:47:46
【问题描述】:

我正在我的模板中呈现一个表单,“患者用户”在其中提交约会。我正在尝试解决这个尴尬的模型层次结构。

我有一个约会请求,它接受患者的外键,其中患者由批准号和内置于 django 中的用户对象的外键组成。

我基本上(在提交预约的表格上)自动填写患者外键数据。这可能吗?

模型.py

#This patient model will extend the user class so we can add the associated medical data for the user
class Patient(models.Model):
    phone_number = PhoneNumberField(blank = True)
    email_address = models.EmailField(blank = True, max_length=254)
    user = models.OneToOneField(User, unique=True,  blank=True, default="", null=True)
    approved = models.IntegerField(default=0, null=False)



#Class for the patients to schedule appointments for their associated doctor
class PatientAppt(models.Model):
    date = models.DateTimeField(auto_now=False, auto_now_add=False, unique=True)
    doctor = models.ForeignKey(Doctor, unique=False, blank=True, default="")
    pain_level = models.IntegerField(validators=[MinValueValidator(0),
                                       MaxValueValidator(10)], default=0)
    medical_conditions = models.CharField(max_length=1000, default="None")
    allergies = models.CharField(max_length=1000, default="None")
    user = models.ForeignKey(Patient, unique=False, blank=True, default="")

【问题讨论】:

  • 请展示您迄今为止为您的观点所写的内容。
  • 您可以在创建表单实例时使用initial_data kwarg。或者您也可以通过上下文在 HTML 端呈现外键 id。方法有很多!

标签: python django database foreign-keys


【解决方案1】:

如果您使用 django 表单(您应该使用),我相信最好的方法是覆盖 save 方法并传递患者对象。通过隐藏字段通过表单传递 id 意味着无论如何你都需要在服务器端验证它,而如果你从会话中传递 id,你就知道它是安全的。

# Your View
def post(self, request):
    ...
    if context['form'].is_valid():
        context['form'].save(patient=request.user.patient)

# Your form
def save(self, commit=True, patient=patient):
    self.instance.user = patient
    return super(PatientApptForm, self).save(commit=commit)

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多