Shrey Sharma
Shrey Sharma

Reputation: 63

How to send data in POST request where the data is not entered by the user in Django

I am trying to make a watchlist for stocks for my website. The data i.e name of the Company and the stock price is already being displayed on the webpage. I want that the user should just click on a button on the same webpage and it adds the data to the watchlist of the user.

This is for a website for stock analysis. I dont know how to do this. PS- I'm new to coding

Watchlist Model:

class WatchList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    watchlist = models.CharField(max_length=300, default='')
    price = models.IntegerField(default='')

html:

{% extends 'homepage/layout.html' %}
{% block content %}
{% load static %}
    <head>
        <title>Technical Analysis</title>
        <link rel="stylesheet" href="{% static 'tech_analysis/tech_analysis.css' %}">
    </head>

    <div class="line"></div>
    <div class="head">
        Technical Analysis
    </div>
    <div class="coname">
        <ul class="ticker_table">
            <li class="ticker_name">{{ ticker }}-</li>
            <li class="ticker_price">{{ price }}</li>
            <li class="diff_green">{{ diff_green }}</li>
            <li class="diff_red">{{ diff_red }}</li>
        </ul>
        <form action="{% url 'bsh_user:Userpage' %}" method="post">
            {% csrf_token %}
             <input class="watchlist" type="submit" value="Add To Watchlist +">
        </form>

    </div>

the information such as {{ticker}} and {{price}} is the data that is to be posted to the model and displayed to the user on a different html.

Expected outcome is to add a company and its price to the watchlist model with a click.

Upvotes: 1

Views: 61

Answers (1)

Kamo Petrosyan
Kamo Petrosyan

Reputation: 234

  1. You can set required=False in django.forms.Form
    class WatchListForm(forms.Form)
        user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput())
        watchlist = models.CharField(widget=forms.TextInput({'class': 'watchlist'}))
        price = models.IntegerField(widget=forms.HiddenInput())
    <form action="{% url 'bsh_user:Userpage' %}" method="post">
        {% csrf_token %}
        {{ form.user }}
        {{ form.price }}
        {{ form.watchlist }}
    </form>

initial form with request.user and price and save

or you can set values in view after form.is_valid function called

if form.is_valid():
    data = form.cleaned_data
    data.update({'user': request.user, 'price': some_price})

or update POST data with your params

    request.POST.update({'user': request.user, 'price': some_price})

Upvotes: 1

Related Questions