Home > Software design >  How to get request value in another class in django?
How to get request value in another class in django?

Time:01-31

It's an example that's as similar as possible, and it's not exactly the same as the actual code.

But I believe it's easy to understand.

class Fruits:

    ...
    def get_sample_data(self, df):
        ...
        data = {
            'put_file_attachment': >here<,
        }
    ...



class DataInputForm(forms.Form):
    attachment = forms.FileField()



class MyView(FormView):
    template_name = 'view.html'
    form_class = DataInputForm

    def get_success_url(self):
        return str(
            reverse_lazy("milk")
        )

    def post(self, request, *args, **kwargs):
        get_file = request.FILES.get('attachment')
        ...

        k = Fruits()
        k.load_data()


        return self.render_to_response(context)

I would like to bring the attachment(In fact, get_file) that the user attached to the web class Fruits's >here<

In other words, I would like to save the file(get_file) in DB column (put_file_attachment) by the user's attachment. How can I get a value passed to a request from another class to another class?

I tried to get 'get_file' by creating a MyView object in the Fruit class, but it doesn't work.

Is that possible in this structure or Am I not understanding the concept of request??

CodePudding user response:

You can pass the get_file value from the MyView class to the Fruits class by making get_file an instance variable of MyView and accessing it in Fruits through an instance of MyView.

Here's an example:

class Fruits:
    def get_sample_data(self, my_view_instance):
        ...
        data = {
            'put_file_attachment': my_view_instance.get_file,
        }
    ...


class MyView(FormView):
    template_name = 'view.html'
    form_class = DataInputForm

    def get_success_url(self):
        return str(
            reverse_lazy("milk")
        )

    def post(self, request, *args, **kwargs):
        self.get_file = request.FILES.get('attachment')
        ...

        k = Fruits()
        k.get_sample_data(self)

        return self.render_to_response(context)


If this helps you please upvote. This is brought to you by Creative AIs, bringing AI generated solutions to everyone. :) If you are curious about us check out our bio!

CodePudding user response:

The variable must be explicitly passed to the class for it to be available. It's currently in a different scope, so it won't be available.

So, either refactor your Fruits class to take your file as an argument to your constructor (ie, __init__), or pass it in some other way, such as a parameter to your load_data method.

  • Related