1

This a the class (in Django 1.7.4) I do not understand... in the form_valid() function:

class ImportCsv(FormView):
    template_name = "backend/import.html"
    form_class = UploadFileForm
    success_url = reverse_lazy("b_import_csv")
    csverrors = []

    def get_context_data(self, **kwargs):
        ctx = super(ImportCsv, self).get_context_data(**kwargs)
        ctx.update({
                "csverrors" : self.csverrors,
            })
        return ctx

    def form_valid(self, form):
        self.csverrors.append("Yeah")
        self.template_name+="yeah"
        return super(ImportCsv, self).form_valid(form)

This class just shows what I cannot understand: once the form is valid, form_valid() is called. There I change two things: self.csverrors and self.template_name.

Then I reload my page: the template name is still the original one, but csverrors remembers the "Yeah". I can submit the form again and again: csverrors keeps growing. The point is: I can change also self.form_class and self.success_url, but everything will be restored in the next connection. Why csverrors is still there?

I cannot see the differences between those two variables and why they act differently. I know the function get_gemplate_names() in this particular case, but this is a general question about instance variables.

The goal was just to put something in an instance variable and change get_success_url() accordingly to that variable. Problem: that variable will not go away.

1 Answer 1

4

csverrors points to the single list regardless of the number of ImportCsv views. This list is created at the time then you define ImportCsv class and never recreated again.

So you should create the new list in the form_valid():

def form_valid(self, form):
    self.csverrors = ["Yeah"]
    ...

Or create the new empty list in the dispatch() method:

class ImportCsv(FormView):

    def dispatch(self, *args, **kwargs):
        self.csverrors = []
        return super(ImportCsv, self).dispatch(*args, **kwargs)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.