Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Django Class based view loading another form with data

I am not sure if I am using this Class based view correctly. What I am trying to do I thought was very simple. Basically is a form based on a model where I only use the 'User' field from:

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})
    

From there: the template is pretty simple with a crispy form:

{% 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 %}

What I want though, is to reload the form after they submit with a selected name, and the reloaded form to have all the log in information from OnSiteLog for that user (a select all where user = '...' basically)

I got a good ways there though I am not sure how to get the proper variable out of the request in the def post method, and then as a test I put id 24. So I am not sure how to get that variable out?

Secondly, crispy forms (I think) keeps giving me this error:

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)...']>}]

So in addition to not overly sure how I get the correct variable out in the def post I am also not sure why the rerendering of the form is freaking out.

question from:https://stackoverflow.com/questions/65894039/django-class-based-view-loading-another-form-with-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try instead to override these methods of the FormView, and take the user to the view again with the proper context to fill the form.

# 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

Then you should be able to populate your form with the instance of OnSiteLog that you just created. However, with this you would have to have optional url paramaters in the url Django optional url parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...