Home > database >  How to get database fields inside a form
How to get database fields inside a form

Time:01-18

What I need? I need to put a form on my page, where all fields from my database are shown, and you can change them and save to database. A simple editor for my database table.

What I have?

my HTML:enter code here

<tr>
            <td>{{ form.name }}</td>
            <td>{{ form.token }}</td>
            <td><button >Add</button></td>
</tr>

my models.py

    from django.db import models


# Create your models here.
class TrafficSources(models.Model):
    name = models.CharField('name', max_length=250)
    token = models.CharField('token', max_length=250)

    def __str__(self):
        return self.name

my forms.py

from .models import TrafficSources
from django.forms import ModelForm, TextInput


class TrafficSourcesForm(ModelForm):
    class Meta:
        model = TrafficSources

        fields = ['name', 'token']

        widgets = {
            'name': TextInput(attrs={
                'class': 'form-control',
                'placeholder': {{here I need the name from database table}}
            }),
            'token': TextInput(attrs={
                'class': 'form-control',
                'placeholder': {{here I need the token from database table}}
            })
        }

This is the view.py for that page

def settings(request):
    ts = TrafficSources.objects.all()
    form = TrafficSourcesForm()
    data = {
        'form': form
    }
    url = 'url for API request'
#    
    ts_token = TrafficSources.objects.filter(name='propeller')
    for h in ts_token:
        token = h.token
    headers = {'Authorization': 'Bearer '   token}
    res = requests.get(url, headers=headers)
    return render(request, 'mainpage/dashboard.html', {'ts': ts, 'js': res.text, 'hd': headers, 'form' : form})

My questions: 1) I can put my database table on the HTML page. I can create an empty working form (with the class) BUT I can't do both in one place. 2) If I want be able to save every field to the database ( separately) I need a a form in every row or I can do it from just a 1 form on a page?

For visualization I give you a screenshot how it should look like. enter image description here

CodePudding user response:

You can use instance parameter for passing the object to the form to render it. You can try like this:

# view
def settings(request):
    ...
    forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()]
    return render(request, 'mainpage/dashboard.html', {'ts': ts, 'js': res.text, 'hd': headers, 'forms' : forms})

# template
{% for form in forms %}
<form action="/your-url/{{form.instance.id}}" method="post">
 {{ form.as_p }}
<input type="submit" value="OK">
</form>

More information can be found in documentation.

  • Related