Spatial Digger
Spatial Digger

Reputation: 1993

Django passing variable to a form

I'm trying to pass a primary key variable straight into a form (foreign key) so the user doesn't have to select it. This is what I have:

I have an HTML button

<a href="{% url 'addfraction' pk=botany.botany_id %}" class="btn btn-primary" role="button">Add Fraction</a>

It passes the primary key of the botany table (botany_id) through the urls.py

url(r'^addfraction/(?P<pk>\d+)/$', views.addfraction, name='addfraction'),

The pk comes in to the def addfraction

def addfraction(request, pk):
    if request.method == "POST":
        form = FractionForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('allbotany')
    else:
        form = FractionForm()
    return render(request, 'fraction/create_fraction.html', {'form': form})

And the data in the form is saved to the database.

class FractionForm(forms.ModelForm):
    class Meta:
        model = Fraction
        fields = (
        #'fraction_id',
        'botany_id',
        'proportion_analysed',
        'soil_volume',
        'sample_volume',
        'sample_weight',
        )

botany_id is a foreign key, it becomes a dropdown box, this needs to be greyed out and contain the botany_id pk. Where have I gone wrong? Any pointers welcome.

Upvotes: 0

Views: 58

Answers (1)

Mostafa Elgayar
Mostafa Elgayar

Reputation: 352

You can eliminate botany_id from the form fields, and you can just assign it to the post instance directly from your addfraction function in views.py without involving your user in the process.

Just add this line before post.save():

 botany = get_object_or_404(Botany, pk=pk)
 post.botany_id = botany

Hope that is what you're trying to do, good luck!

Upvotes: 1

Related Questions