0

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.

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

That was my initial thought but it returns the error: Cannot assign "'1'": "Fraction.botany_id" must be a "Botany" instance. I put the post.botany_id = pk between the post = form.save(...) and post.save()
@GaryNobles Try it now, I edited something. Make sure to also import your Botany Model in views.py

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.