I am trying to create 2 forms and display it in a single Django HTML page. I created 2 Modelform class like this
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = "__all__"
class ToyForm(forms.ModelForm):
class Meta:
model = Toy
fields = "__all__"
In the HTML page I am only able to embed the model = Company. How can I embed the Model = Toy in the same page, what I tried brings up the same Company Form. Here is the html code
<form method="post">
{% csrf_token %}
<h2> Company Form </h2>
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
<form method="post">
{% csrf_token %}
<h2> Toy Form </h2>
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
In views.py
from django.shortcuts import render
from myapp.form import CompanyForm, ToyForm
def index(request):
cform = CompanyForm()
tform = ToyForm()
context={'cform':cform, 'tform':tform}
return render(request,"index.html",context)
In HTML Page
<form method="post">
{% csrf_token %}
<h2> Company Form </h2>
{{ cform.as_p }}
<input type="submit" value="Submit" />
</form>
<form method="post">
{% csrf_token %}
<h2> Toy Form </h2>
{{ tform.as_p }}
<input type="submit" value="Submit" />
</form>
Related
I have a website where user submitted entries are displayed and have an upvote count along with a button to upvote it yourself. These are represented with the Entry model. How do I pass the id of the particular Entry instance the user upvotes to a view?
html:
{% for entry in entries %}
<div id="upvote_count">
<form action="upvote" method="GET">
{% csrf_token %}
{{ entry.upvotes }}
<button id="upvote" type="submit">Upvote</button>
</form>
</div>
{% endfor %}
models.py:
class Entry(models.Model):
#...
upvotes = models.IntegerField( blank = True, null=True)
current url:
url(r'^upvote$', views.upvote),
You can pass it inside a hidden input, such as:
<form ...>
...
<input type="hidden" name="id" value="{{ entry.id }}">
<button ...>
</form>
and access to it in your view:
def upvote(request):
entry_id = int(request.GET.get("id"))
...
When I render the form in HTML, I use this view. the patient_id is used to denote what patient the check in is for and for name display and such.
def Checkin(request, patient_id):
patient = get_object_or_404(PatientInfo, pk=patient_id)
form = forms.PatientCheckinForm()
return render(request, 'patientRecords/checkin.html', {'patient': patient, 'form':form})
When I submit the patient form filled out as a POST method, I still need access to the patient_id. Currently this is the view that accepts the filled form:
def CheckinSubmit(request):
if request.method == 'POST':
form = forms.PatientCheckinForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.date_time_of_checkin = dt.now()
instance.patient = patient.patient_id
instance.save()
return redirect('patientRecords/index.html')
I want to set the instance.patient to the patient_id that was part of patient from the Checkin view. Is there a way to pass the patient data back along with the POST method or is there another way this can be done?
For reference, here is my template and I am using ModelForm not form.
{% block content %}
<div class="container">
<h1>Patient Checkin</h1>
<h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
<form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
Thanks in advance!
You should be able to simply add a hidden input to your form to capture the patient ID:
{% block content %}
<div class="container">
<h1>Patient Checkin</h1>
<h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
<form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
<input type="hidden" name="patient_id" value="{{patient.patient_id}}" />
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
(Note this assumes that the patient ID is accessible from the patient_id property of the patient object.)
Then, in your CheckinSubmit method, you can access this value via request.POST.get('patient_id')
Alternatively, it appears that your check in form loads with the patient ID in the URL. In your CheckinSubmit method, you should be able to access this URL through the request.META.HTTP_REFERER property. You could then parse the URL (e.g., using request.META.HTTP_REFERER.split('/')[len(request.META.HTTP_REFERER.split('/')) - 1] to pull out the patient ID.
Example
<form method="post" action = "{% url 'user_search_from_group' %}">
<div class="module-option clearfix">
<div class="input-append pull-left">
<input type="hidden" name="groupname" value="{{ gpname }}" />
{% csrf_token %}
<input type="text" class="span3" placeholder="Filter by name" id="username3" name="username3" required>
<button type="submit" class="btn" name="submit">
<i class="icon-search"></i>
</button>
</div>
</div>
</form>
Here a hidden field is used to pass a value along form.
def user_search_from_group(request):
if request.method == 'POST':
username3 = request.POST.get('username3')
gname = request.POST.get('groupname')
Using request we are use the value inside view
I want to replace the DetailView in Djangos Poll Tutorial with a UpdateView. Unfortunately what it is showing is a List of Polls instead of a list of Choices + Votes.
My models Poll, Choices are unchanged. The template for the voting view is kept simplest:
<h1>{{ poll }}</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Vote" />
</form>
How can I have the form to show a specific poll and a list of the choices as in the manually build form of the detail view in the tutorial:
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Use the ModelChoiceField and RadioSelect widget:
class ChoicesForm(forms.Form):
choice = forms.ModelChoiceField(queryset=Choice.objects.none(),
widget=forms.RadioSelect,
required=True,
empty_label=None)
def __init__(self, *args, **kwargs):
poll = kwargs.pop('poll')
super(ChoicesForm, self).__init__(*args, **kwargs)
self.fields['choice'].queryset = poll.choice_set.all()
form = ChoicesForm(poll=poll)
So I got to the end of my tether. I need to create a database that allows me to choose user names stored in auth_user table in the 'username' column. The model.py looks like this:
from django.db import models
from django.contrib.auth.models import User
class basehw(models.Model):
name = models.ForeignKey(User)
dept = models.CharField(verbose_name='dept', max_length=50, null=False)
location = models.CharField(verbose_name='location', max_length=50, null=False)
form:
from django.forms import ModelForm
from baza.models import basehw
class baseForm(ModelForm):
class Meta:
def __init__(self):
pass
model = basehw
add.html template(for now, it's a text field):
{% extends 'base/base.html' %}
{% load staticfiles %}
{% block content %}
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8" language="javascript" src="{% static 'base/js/dataTables.bootstrap.js' %}"></script> </head>
<body>
<form action="{% url 'baza.views.add' %}" method="post">{% csrf_token %}
<div class="row">
<div class="col-md-4">
<label for="name">name:</label>
<input type="text" class="form-control" id="name" placeholder="name" name="name">
</div>
<div class="col-md-4">
<label for="site">site:</label>
<select class="form-control" id="site" name="site">
<option value="W16">W16</option>
<option value="W1602">W1602</option>
</select>
</div>
<div class="col-md-4">
<label for="hostname">hostname:</label>
<input type="text" class="form-control" id="hostname" name="hostname" placeholder="hostname">
</div>
<div class="col-md-4">
<label for="SN">serial number:</label>
<input type="text" class="form-control" id="SN" name="SN" placeholder="serial number">
</div>
</div>
<br />
<input class="btn btn-primary" type="submit" value="save"/>
<a href="{% url 'baza.views.Table' %}" class="btn btn-danger" type="button" >cancel</a>
<br /><br />
</form>
</body>
</html>
{% endblock %}
views.py:
def Table(request):
table = basehw.objects.all
return render_to_response('../templates/baza/baza.html',
{'table': table},
context_instance=RequestContext(request))
def add(request):
if request.method == 'POST':
form = baseForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/baza/')
else:
form = baseForm()
return render(request, 'baza/add.html', {
'form': form,
})
Using the following model, I am able to populate the 'name' field only by using the id of the whole record. Namely, when I enter '1', I get the user name that was saved as first in the auth_user table, when '2', the second one... Moreover, such model allows me to update the 'name' field only – no other field are possible to alter. The application uses an HTML template, and I'd like to turn the 'name' field to dropdown menu. So the problems are:
How should I create the model in order to make all fields editable?
What should I do to select a user's name instead of an ID from dropdown menu (dropdown menu fed from auth_user)? How should I describe in HTML?
Huge thanks in advance!
That's not how you write a template for a Django form. You need to use the form fields provided by the form object. For example:
<div class="col-md-4">
{{ form.name.label_tag }}
{{ form.name }}
{{ form.name.errors }}
</div>
i have created a form with minimal fields(for testing) , but it never enters form.is_valid()
Here is the minimal code
in the models.py
from django.db import models
class sample(models.Model):
field1=models.CharField(max_length=100)
field2=models.CharField(max_length=100)
in the forms.py
from django.forms import ModelForm
from app.models import sample
class someform(ModelForm):
class Meta:
model=sample
in the views.py
some imports
def index(request):
return render(request, 'app/index.html')
def contact(request):
if request.method=='POST':
form=someform(request.POST)
if form.is_valid():
field1=form.cleaned_data['field1']
field2=form.cleaned_data['field2']
return HttpResponse("valid")
else:
return HttpResponse("invalid")
else:
form=someform()
return HttpResponse("error")
The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help
in the index.html
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="submit" id="submit" name="submit">
</form></body></html>
First pass your form to index.html, when the request is not POST in views.py:
else:
form=someform()
return render(request, 'index.html', locals())
In template you should make it like this:
<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Submit</button>
</form>
When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="id_field1" name="field1">
<input type="text" id="id_field2" name="field2">
<input type="submit" id="submit" name="submit">
</form>
</body>
</html>
Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside or tags automatically.
You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.