基于 Django Class 的视图用数据加载另一个表单

Django Class based view loading another form with data

我不确定我是否正确使用了这个基于 Class 的视图。我想做的事情我认为很简单。基本上是一种基于模型的表单,其中我只使用来自的 'User' 字段:

class OnSiteLog(models.Model):
    objects = models.Manager()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    checkIn = models.DateTimeField('checkin_date', null=True, blank=True)    
    checkOut = models.DateTimeField('checkout_date', null=True, blank=True)    
    notes = models.CharField(null=True, blank=True,max_length = 200)
    location = models.CharField(null=True, blank=True, max_length=200)
    autoCheckin = models.BooleanField(null=True, blank=True, default=False)


class QueryUser(LoginRequiredMixin, FormView):
    model = OnSiteLog
    form_class = QueryForm
    template_name = 'log/query.html'
    success_url = '/'
    def post(self, request, *args, **kwargs):

        theRecord = OnSiteLog.objects.filter(user_id=24)
        print(theRecord[0].user)
        super(QueryUser, self).post(request, *args, **kwargs)
        return render(request, 'log/query.html', {'log':theRecord})
    

从那里开始:模板非常简单,形式清晰:

{% block content %}
   <div class="breadcrumb-area">


        <!-- Background Curve -->
        <div class="breadcrumb-bg-curve">
            <img src="{% static '/img/core-img/curve-5.png' %}" alt="">
        </div>
    </div>
<div class="container">
    <h2> Query for User </h2>
    <div class="row">
      <div class="col-sm">
            {% crispy form %}
      </div>
    </div>

    <div class="row">
       Logs
      <div class="col-sm">
      <table class="table">
      <tr>
        <th>User</th>
        <th>Check In</th>
        <th>Check Out</th>
        <th>Location</th>
        <th>Notes</th>
       
        </tr>
        {% for ins in log %}
          <tr>
            <td>{{ ins.user }}</td>
            <td>{{ ins.checkIn }}</td>
            <td>{{ ins.checkOut }}</td>
            <td>{{ ins.location }}</td>
            <td>{{ ins.notes }}</td>
            {% if request.user.is_superuser %}
              <td> <a href="{% url 'log_detail' ins.id %}"><button type="button" class="btn btn-primary">Edit Entry</button></td>
            {% endif %}

            <!-- td><a href="{{ ins.id }}"><button type="button" class="btn btn-primary">Edit Insurance</button></a></td>
            <td><button type="button" class="btn btn-danger">Delete Insurance</button></td> -->
          </tr>
        {% endfor %}
      </table>
           
      </div>
    </div>


</div>

{% endblock %}

但我想要的是在他们使用 selected 名称提交后重新加载表单,并且重新加载的表单包含来自 OnSiteLog 的该用户的所有登录信息(select 所有用户 = '...' 基本上)

虽然我不确定如何从 def post 方法中的请求中获取正确的变量,但我有一个很好的方法,然后作为测试我输入了 id 24。所以我不确定如何取出那个变量?

其次,脆皮表格(我认为)一直给我这个错误:

VariableDoesNotExist at /query_user/
Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'log': <QuerySet [<OnSiteLog: OnSiteLog object (100)>, <OnSiteLog: OnSiteLog object (101)>, <OnSiteLog: OnSiteLog object (107)>, <OnSiteLog: OnSiteLog object (109)>, <OnSiteLog: OnSiteLog object (124)>, <OnSiteLog: OnSiteLog object (148)>, <OnSiteLog: OnSiteLog object (152)>, <OnSiteLog: OnSiteLog object (156)>, <OnSiteLog: OnSiteLog object (158)>, <OnSiteLog: OnSiteLog object (163)>, <OnSiteLog: OnSiteLog object (168)>, <OnSiteLog: OnSiteLog object (172)>, <OnSiteLog: OnSiteLog object (178)>, <OnSiteLog: OnSiteLog object (192)>, <OnSiteLog: OnSiteLog object (193)>, <OnSiteLog: OnSiteLog object (550)>, <OnSiteLog: OnSiteLog object (552)>, <OnSiteLog: OnSiteLog object (556)>, <OnSiteLog: OnSiteLog object (559)>, <OnSiteLog: OnSiteLog object (562)>, '...(remaining elements truncated)...']>}]

所以除了不太确定我如何在 def post 中得到正确的变量之外,我也不确定为什么重新呈现表单会出错。

您可以尝试覆盖 FormView 的这些方法,并使用适当的上下文再次将用户带到视图以填写表单。

# get the id of the log that was just created

    def form_valid(self, form, *args, **kwargs):
        user = form.cleaned_data.get('user')
        self.log_id = User.objects.get(username=user).select_related('log').last().id
        return super().form_valid(form, *args, **kwargs) 

# redirect successful form to same view

    def get_success_url(self):
        return reverse('this-view', kwargs={'id': self.log_id})

# render populated form in context

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        try:
            context['form'] = self.form_class(instance=OnSiteLog.objects.get(id=self.kwargs['id']))
        except ObjectDoesNotExist:
            context['form'] = self.form_class()
        finally: 
            return context

然后您应该能够使用刚刚创建的 OnSiteLog 实例填充您的表单。但是,有了这个,您必须在 url Django optional url parameters.

中有可选的 url 参数