如何在django中保存db中的单选按钮值

时间:2021-10-29 13:46:20

forms.py

Date_Format = (
    ('0', ' dd / mm / yyyy'),
    ('1', 'mm / dd / yyyy'),
)

Time_Format = (
    ('0', ' 12 hour AM / PM '),
    ('1', ' 24 hour '),
)

class DateFormatForm(Form):
    date_format = forms.ChoiceField(choices=Date_Format,widget=forms.RadioSelect())

class TimeFormatForm(Form):
    time_format = forms.ChoiceField(choices=Time_Format,widget=forms.RadioSelect())

models.py

class Settings(models.Model):
    user = models.ForeignKey(User, null=True)
    date_format = models.CharField('Date format', max_length=100)
    time_format = models.CharField('Time format', max_length=100)
  1. I had kept the two forms namely,DateFormatForm and TimeFormatForm in template for selecting the date ad time formats.

    我在模板中保留了两种形式,即DateFormatForm和TimeFormatForm,用于选择日期广告时间格式。

  2. In models their are two field namely, i.date_format and ii.time_format for which forms choices are created.So if the user clicks this format ('0', ' dd / mm / yyyy'), and press save,the corresponding value is "0" which should be saved in date_format.

    在模型中,它们是两个字段,即i.date_format和ii.time_format,为其创建表单选项。如果用户单击此格式('0','dd / mm / yyyy'),并按保存,则相应的值是“0”,应保存在date_format中。

3.So date formats are saved in their appropriate fields with "0"'s or "1".

3.所有日期格式都保存在“0”或“1”的相应字段中。

I can't use forms form validation and save because i am not using modelsForm,So how to save it in database.

我不能使用表单表单验证和保存因为我没有使用modelsForm,所以如何将其保存在数据库中。

Please share me a slight idea to perform this with out form.

请与我分享一个简单的想法,以表格形式执行此操作。

Thanks

1 个解决方案

#1


1  

I think that your model could be refactored and you should use Django ModelForm.

我认为你的模型可以重构,你应该使用Django ModelForm。

But, why do you want to save the human-readable part in db if you have hardcored them in your code? do you want get it after?

但是,如果您在代码中对它们进行了硬编码,为什么要在db中保存人类可读的部分?你想要得到它吗?

if you want to get the human-readable part, just use get_date_format_display() for DateFormat model and get_time_format_display() for TimeFormat model. Django generates these methods

如果你想获得人类可读的部分,只需对DateFormat模型使用get_date_format_display(),为TimeFormat模型使用get_time_format_display()。 Django生成这些方法

see this Documentation

请参阅此文档

Hope this helpsvalue

希望这有助于获得价值

#1


1  

I think that your model could be refactored and you should use Django ModelForm.

我认为你的模型可以重构,你应该使用Django ModelForm。

But, why do you want to save the human-readable part in db if you have hardcored them in your code? do you want get it after?

但是,如果您在代码中对它们进行了硬编码,为什么要在db中保存人类可读的部分?你想要得到它吗?

if you want to get the human-readable part, just use get_date_format_display() for DateFormat model and get_time_format_display() for TimeFormat model. Django generates these methods

如果你想获得人类可读的部分,只需对DateFormat模型使用get_date_format_display(),为TimeFormat模型使用get_time_format_display()。 Django生成这些方法

see this Documentation

请参阅此文档

Hope this helpsvalue

希望这有助于获得价值