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>
Related
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>
What is the best way to upload a CSV file information and then saving it into a PostgreSQL table?
If the upload is successful I will check on the database, I don't want to show the table anywhere in the templates.
Please inform if you need more info.
template where the upload will happen:
{% extends "product_register/base.html" %}
{% block content %}
<form action="" method="post" autocomplete="off">
{% csrf_token %}
<label for="file1">Upload a file: </label>
<input type="file" id="file1" name="file">
<div class="row">
<div class="col-md-8">
<button type="submit" class="btn btn-success btn-block btn-lg"><i class="far fa-save"></i>
Submit</button>
</div>
<div class="col-md-4">
<a href="{% url 'product_list' %}" class="btn btn-secondary btn-block btn-lg">
<i class="fas fa-stream"></i> Lista de Produtos
</a>
</div>
</div>
</form>
{% endblock content %}
views.py
def category_form(request):
"""Cadastro de Categorias"""
if request.method == "GET":
return render(request, "product_register/category_form.html")
else:
#CSV UPLOAD HERE
return render(request, "/product")
models.py
class Category(models.Model):
"""Classe Categoria"""
name = models.CharField(max_length=20)
def __str__(self):
return self.name
forms.py
class CategoryUpload(forms.ModelForm):
"""Upload de Categorias"""
class Meta:
model = Category
fields = "__all__"
Use django-import-export and use foreign key widget for look ups.
also there are lots of widgets with this package.
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 am trying to generate a form dynamically and want to assign indentation of form fields. I am trying to assign an custom attribute offset to forms.CharField in subclass. I plan to use this logic to create a form dynamically from an xml file, where the fields would be indented based on the depth of the node.
I am unable to retrieve the value of offset while rendering the template and hence unable to assign the margin-left style parameter. The final html output is also shown.
Can someone please help. I have searched some other answers on this site where it appears that arbitrary attributes can be assigned and retrieved in template. e.g.as in thread here where an arbitrary label_class attribute is assigned
My forms.py file :
class MyCharField(forms.CharField):
def __init__(self, *args, **kwargs):
self.offset = kwargs.pop('offset', 0)
super(MyCharField, self).__init__(*args, **kwargs)
class MyDynamicForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyDynamicForm, self).__init__(*args, **kwargs)
self.fields["Field_A"] = MyCharField(label="Input A", offset="5")
self.fields["Offset_Field_B"] = MyCharField(label="Input B", offset="50")
My Views.py looks like this:
class MyDynamicView(View):
template_name = 'demo/myform.html'
form_class = MyDynamicForm
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
My template file using bootstrap looks like this:
{% extends 'demo/base.html' %}
{% load bootstrap3 %}
{% block content %}
<form role="form" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group bootstrap3-required">
<label class="col-md-3 control-label " style = "margin-left: {{field.offset}}px" for="{{ field.name }}">{{ field.label}}</label>
<div class="col-md-9">
<input class="form-control" id="id_{{field.name}}" name="{{ field.name }}" placeholder="{{field.label}}" style="margin-left:{{field.offset}}px" title="" required="" type="text"/>
</div>
</div>
{% endfor %}
{% buttons submit='OK' reset='Cancel' layout='horizontal' %}{% endbuttons %}
</form>
{% endblock %}
The html output is:
<form role="form" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='lTy0rc2r9KNiNNPosUoriUlNzYBpgoVpael1MYLOczFECO7H7LXdES6EGBhUoXx0' />
<div class="form-group bootstrap3-required">
<label class="col-md-3 control-label " style = "margin-left: px" for="Field_A">Input A</label>
<div class="col-md-9">
<input class="form-control" id="id_Field_A" name="Field_A" placeholder="Input A" style="margin-left:px" title="" required="" type="text"/>
</div>
</div>
<div class="form-group bootstrap3-required">
<label class="col-md-3 control-label " style = "margin-left: px" for="Offset_Field_B">Input B</label>
<div class="col-md-9">
<input class="form-control" id="id_Offset_Field_B" name="Offset_Field_B" placeholder="Input B" style="margin-left:px" title="" required="" type="text"/>
</div>
</div>
<div class="form-group"><label class="col-md-3 control-label"> </label><div class="col-md-9"><button class="btn btn-default" type="submit">OK</button> <button class="btn btn-default" type="reset">Cancel</button></div></div>
</form>
It not necessary to instantiate from CharField for that. Probably such initialization of the field in form will be enough for you:
field_a = forms.CharField('Input_A',
widget=forms.TextInput(attrs={'placeholder': 'Input_A', 'style': 'margin-left: 50px'}))
I want to create an account registration page that links directly to an account info page and displays the account info. I'm having a hard time getting the form to save the account info into my model and I don't know why.
models.py:
class Owner(models.Model):
fullname = models.CharField(max_length=255)
username = models.CharField(max_length=255)
password = models.CharField(max_length=255)
email = models.EmailField()
def __unicode__(self):
return self.fullname
""" This is a Form class and not a regular Model class """
class OwnerForm(forms.Form):
class Meta:
model = Owner
fields = ['fullname', 'username', 'password', 'email']
views.py:
def register(request):
form = OwnerForm()
if request.POST:
form = OwnerForm(request.POST)
if form.is_valid():
fullname = request.POST.get('fullname', '')
username = request.POST.get('username', '')
password = request.POST.get('password', '')
email = request.POST.get('email', '')
owner_obj = Owner(fullame=fullname, username=username, password=password, email=email)
owner_obj.save()
return HttpResponseRedirect('courses/accountinfo.html')
else:
form = OwnerForm()
return render_to_response('courses/register.html', {'form': form}, context_instance=RequestContext(request))
register.html:
{% extends "layout.html" %}
{% load static from staticfiles %}
{% block title %}{{ page.title }}{% endblock %}
{% block content %}
<article>
<div id="Register">
<form action="{% url 'courses:accountinfo' %}" method="post"> {% csrf_token %}
<p>
<label for="fullname">Full name:</label>
<input id="fullname" name="fullname" type="text">
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" type="text">
</p>
<p>
<label for="username">Username</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password">
<span>Enter a password longer than 8 characters</span>
</p>
<p>
<label for="confirm_password">Confirm Password</label>
<input id="confirm_password" name="confirm_password" type="password">
<span>Please confirm your password</span>
</p>
<p>
<input type="submit" value="REGISTER" id="submit">
</p>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="{% static 'js/app.js' %}" charset="utf-8"></script>
</div>
</article>
{% endblock %}
You can call this after checking if the form.is_valid, then send the redirect and let your other view handle the rest. The issue may also be with the accountinfo view, but you didn't post that code.
owner = form.save()
owner.set_password(owner.password)
owner.save()
Use the save method on the form to save the data rather than creating a model object once the form is valid. However I see that the template contains additional fields. Do you have something in the valid method?
What is the error that you are getting? are you posting to the correct url?