Django CreateView get_initial外键

时间:2018-06-14 13:21:08

标签: python django django-models django-forms django-class-based-views

我有一个表单,我正在尝试使用get_initial方法设置外键。该模型是

class CardioRecord(models.Model):
    date_uploaded = models.DateField(auto_now=True)
    client = models.ForeignKey(User, on_delete=models.CASCADE)
    run_dist = models.FloatField(blank=True, null=True)
    run_time = models.FloatField(blank=True, null=True)

表单是

class CardioRecordForm(forms.ModelForm):
        class Meta:
            model = CardioRecord
            fields = [
                        'client',
                      'run_dist',
                      'run_time',
                      ]
            labels = {
                'run_dist': 'Distance (km)',
                'run_time': 'Time (min)',
            }
            widgets = {
                'client': forms.HiddenInput()
            }

视图是

class CardioCreateView(CreateView):
    model = CardioRecord
    form_class = CardioRecordForm
    template_name = 'training/cardio_form.html'

    def get_initial(self):
        initial = super(CardioCreateView, self).get_initial()
        initial['client'] = self.request.user.pk
        return initial

我得到的错误是

null value in column "client_id" violates not-null constraint
看起来像初始值的

没有传递给表单。如何将外键传递给表单?

1 个答案:

答案 0 :(得分:0)

使用隐藏字段不会阻止用户编辑值。如果要在视图中设置值,请将其从import java.util.ArrayList; import java.util.Collections; public class Calc { // private ArrayList<Wimpel> w = new ArrayList<Brick>(); private String bKette = ""; public String bestOrder(ArrayList<Brick> w) { while (!w.isEmpty()) { if (w.get(0).getFrequency() > 0) { bChain += w.get(0).getColor() + "|"; Brick brick = new Wimpel(w.get(0).getVariant(), w.get(0).getFrequency() - 1); w.remove(0); w.add(brick); // bestOrder(w); } else { w.remove(0); } bestOrder(w); } return bOrder; } public int Solutions(ArrayList<Wimpel> w) { ArrayList<Brick> tmp = new ArrayList<Brick>(w); int l = 1; int counter = (int) w.stream().filter(c -> Collections.max(tmp).getFrequency() == c.getFrequency()).count(); l = (int) (fakultaet(counter) * fakultaet((tmp.size() - counter))); return l; } public static long fakultaet(int n) { return n == 0 ? 1 : n * fakultaet(n - 1); } } 中删除,格式为:

fields

然后在class CardioRecordForm(forms.ModelForm): class Meta: model = CardioRecord fields = [ 'run_dist', 'run_time', ] 方法中的表单实例上设置值:

form_valid

然后,您可以删除class CardioCreateView(CreateView): def form_valid(self, form): form.instance.client = self.request.user return super(CardioCreateView. self).form_valid(form) 方法。