how to pass value from html to view in django?

Viewed 424

I have made this HTML code:

<h3>your major is {{user.userprofile.major}}</h3>

This will correctly show the major on the webpage, but I want to use this string to get something from another table in view.

How would I pass this string to view?

edit: Here is my view.py

def dashboardView(request):
    obj = BooksFile.objects.all()
    query = BooksFile.objects.filter(book_major='cs)
    return render(request, 'dashboard.html', {'books': obj, 'major': query})


def registerView(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        profile_form = UserProfileForm(request.POST)
        if form.is_valid() and profile_form.is_valid():
            user = form.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            profile.save()
            return redirect('login_url')
    else:
        form = UserCreationForm()
        profile_form = UserProfileForm()
    context = {'form': form, 'profile_form': profile_form}
    return render(request, 'registration/register.html', context)

here is my template: {% extends 'index.html' %}

{% block content %}
    <h1>Welcome, {{user.username}}</h1>
    <h2>Your major is {{user.userprofile.major}}</h2>

    {% for book in books %}
     <h3>Your book name is {{book.book_name}}</h3>
    {% endfor %}

{% endblock %}

I am trying to show the book names from the booksfile table by corresponding major that user has. Right its showing the books that has "cs" attribute because I manually put "cs" in the get function in view. I am trying to send the major string from template to view, so that I can put what ever the user's major is in the get function. Or is there any other way to do it.

2 Answers

You need to use a form in your template and submit it to call your view. i.e.

<form action="your_view_url" method="POST">
    <input type="text" name="major" value="{{user.userprofile.major}}"/>
    <input type="submit"/>
</form>

an then in your view you access that with:

if request.POST:
    major = request.POST.get('major')

As per documentation: https://docs.djangoproject.com/en/2.2/topics/forms/

First of all you have to get the value of model with help of queryset, and put it in the dictionary and then pass it with the template.

In views:

def get(self, request):
    queryset = Model_name.objects.all()
    ctx = {
        'queryset': queryset,
    }
    return render(request, 'page_name(or template_name).html', ctx)

in template:

<form action="{%url'(your_view_name without brackets)'%}" method="POST">

  {% for data in queryset%}
    <span class="username"><a href="#">{{data.name(field of your model)}}</a> . 
    </span>
    <span class="email"><a href="#">{{data.email(field of your model)}}</a> . 
    </span>
  {% endfor%}
</form>
Related