1

I am creating a form in my django app. My app has a user, a user can have many transactions and a transaction can have many sales. I'm trying to create a form to add sales to the DB. I'm trying to pass a parameter in the URL (transaction_id) and use it in the Django class-based view CreateView to set the corresponding (foreign key) field in the form. Is it possible to do this and if so how could I apply it.

Class based create view below

class SaleCreateView(CreateView):
    model = Sale
    fields = ['amount_sold', 'total_price_sold', 'note']

    def form_valid(self, form):


URL below

path('sale/new/<int:pk>', SaleCreateView.as_view(), name='sale-create'),

Link below

{% url 'sale-create' transaction.id %}

Sale form below

<div>
    <form method="POST">
        {% csrf_token %}
        <fieldset class ="form-group">
            <legend class="border-bottom mb-4">Enter Sale</legend>
            {{ form|crispy }}
        </fieldset>
        <div class="form-group">
            <button class ="btn btn-outline-info" type="submit">Enter</button>
        </div>
    </form>
</div>

1 Answer 1

1

Yes, it is possible.

You will need to use a ModelForm with CreateView. Your SaleCreateView with SaleCreateForm classes should look like this:

class SaleCreateView(CreateView):
    model = Transaction
    fields = ['amount_sold', 'total_price_sold', 'note']
    form_class = SaleCreateForm

    def get_initial(self, *args, **kwargs):
            initial = super(SaleCreateView, self).get_initial(**kwargs)
            return initial

class SaleCreateForm(forms.ModelForm):
    class Meta:
        model = Sale
        exclude = ('transaction',)

    def __init__(self, *args, **kwargs):
        self.transaction = kwargs.pop('transaction')
        super(SaleCreateForm, self).__init__(*args, **kwargs)

Here is a step by step tutorial.

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.