How to create registration form in django? - django

I am trying to insert values into postgress for a simple registration form but it is not inserting the values into the database.
I tried this code.
.HTML
<form id="form_id" method="post">
{% csrf_token %}
<h1>Registration</h1>
<body>
<table class="center">
<tr>
<td>Name:<input type="text" id="nm_id"></td>
</tr>
<tr><td>Address:<input type="text" id="ad_id">
</td>
</tr>
<tr><td>Email:<input type="text" id="em_id"></td></tr>
<tr><td> Mob No:<input type="text" id="mo_id"></td></tr>
</table>
<input type="submit" id="sub_id">
</form>
View.py
def dc(request):
n=request.POST.get["Name"]
ad=request.POST.get["Add"]
em=request.POST.get["Email"]
m=request.POST.get["mo"]
queryset1=registration.objects.values("n")
queryset2=registration.objects.values("ad")
queryset1=registration.objects.values("em")
queryset1=registration.objects.values("m")
return render(request,'demo1.html')
Models.py
class registration(models.Model):
Name = models.CharField(max_length=255)
Add = models.CharField(max_length=255)
email = models.CharField(max_length=400)
mo = models.CharField(max_length=400)
but its not work properly can anybody helpme for registration of these fields?

You need to create and save the instance.
new_user = registration(Name=n,Add=ad,email=em,mo=m)
new_user.save()

Related

How get multiple BooleanFields in a form using Django

I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid.
The field "who paid" is a table containing the name of all users and a checkbox.
Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text).
How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name?
model.py
from django.db import models
#created_date attibute needs it
from django.utils import timezone
# This Model is a super class "Financial Transaction"
class GroupTransaction(models.Model):
name = models.CharField(max_length=257, default='')
who_paid = models.CharField(max_length=257, default='')
value = models.DecimalField(max_digits=6, decimal_places=2)
justification = models.CharField(max_length=257, default='')
created_date = models.DateTimeField(default=timezone.now)
date = models.CharField(max_length=257, default='')
receipt = models.FileField(upload_to='comprovantes', blank=True, null=True)
its_type = models.CharField(max_length=257, default='')
def __str__(self):
#INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant)
return "%s - %s" % (self.name , self.who_paid)
view.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from deposit.forms import DepositForm,MonthlyDepositForm
from django.contrib.auth.models import User
# Create your views here.
#login_required
def deposito(request):
if request.method == 'POST':
form = DepositForm(request.POST, request.FILES)
if form.is_valid():
form.save()
HttpResponseRedirect('/historico/')
else:
print (str(form.errors.as_data()))
else:
form = DepositForm()
groupForm = MonthlyDepositForm()
return render(request, 'shell/app_shell.html', {
'is_deposit' : True,
'title' : 'Deposit',
'transaction' : form,
'groupTransaction' : groupForm,
'users': User.objects.all()
})
form.py
class MonthlyDepositForm(forms.ModelForm):
value = forms.DecimalField()
date = forms.CharField(widget=forms.TextInput(attrs={
'class':'datepicker picker__input',
'readonly':'',
'tabindex':'54',
'aria-haspopup':'True',
'aria-expanded':'false',
'aria-readonly':'false',
'aria-owns':'birthdate_root'
}))
who_paid = forms.BooleanField()
its_type = forms.CharField(widget=forms.HiddenInput(attrs={'readonly':True}),
initial='Deposito Mensal')
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
template.html:
<form class="col s12">
{% csrf_token %}
{{ groupTransaction.its_type }}
<div class="row"></div>
<!-- Nome do evento -->
<div class="row">
<div class="input-field col s6">
<!-- <input id="nome_evento" type="number" value="10" step="any" min="0.05" max="400" class="validate" required> -->
{{ groupTransaction.value }}
<label for="nome_evento">Value</label>
</div>
<div class="input-field col s6">
<!-- <input type="text" class="datepicker picker__input" readonly="" tabindex="54" aria-haspopup="true" aria-expanded="false" aria-readonly="false" aria-owns="birthdate_root" required> -->
{{ groupTransaction.date }}
<label for="data-mensal" data-error="Data inválida">Date</label>
</div>
</div>
<!-- Petianos que irão para o evento -->
<table class="striped">
<thead>
<!-- Cabeçalho tabela -->
<tr>
<th>Who Paid</th>
<th>
<div class="switch">
<b class="center-align">Default</b>
<label>
<input type="checkbox">
<span class="lever"></span>
</label>
</div>
</th>
</tr>
<!-- ============= -->
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.get_full_name }}</td>
<td>
<div class="switch">
<label>
<!-- <input type="checkbox"> -->
{{ groupTransaction.who_paid }}
<span class="lever"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="row"></div>
<div class="row"></div>
<!-- Botão de registrar saque (submit) -->
<div class="row">
<button class="btn waves-effect waves-light col s6 m3 offset-s6 offset-m9 blue" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
How the form is:
You need to make who_paid a ManyToManyField(User). Then in the form you can set its widget like this:
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
widgets = {
'who_paid': forms.CheckboxSelectMultiple(),
}
That will give you the right structure. Then you can render it manually if you want to change the display.

how to write join query in django?

I have googled several hours but couldn't understand how to write sql join(raw or ORM) related queries.
Below is my model with two tables sandBox1 and licenseType where they will have common item "email" on which join will be performed
class sandBox1(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=200)
website = models.TextField(validators=[URLValidator()])
comment = models.TextField(default='-')
gender = models.CharField(max_length=6)
def __str__(self):
return self.email
class licenseType(models.Model):
#1=other, 2=two-wheeler 4=four-wheeler
licenseId = models.IntegerField()
email = models.EmailField()
template file : index.html
<html><form id="form1" method="post" action="{% url "sandbox" %}">
{% csrf_token %}
Name: <input type="text" name="name" >
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website" >
<span class="error"></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<hr>Check the license type you have:-<br>
<input type="checkbox" name="license[]" value=2 > 2 wheeler<br>
<input type="checkbox" name="license[]" value=4 > 4 wheeler<br>
<input type="checkbox" name="license[]" value=1 > Other <br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div>
{% for obj in sandBoxObj %}
<p>
{{ obj.name }}<br>
{{ obj.email }}<br>
{{ obj.website }}<br>
{{ obj.gender }}<br>
{{ obj.comment }}<br>
{% endfor %}
</div>
</html>
here is a view file that needs correction. I want to show the result of this sql query:
select sandBox1.email,sandBox1.name,licenseType.licenseId from sandBox1
innerjoin licenseType on sandBox1.email=licenseType.email;
View file
def sandbox(request):
template_name='domdom.html'
sandBoxObj = sandBox1.objects.all()
context = { 'sandBoxObj':sandBoxObj }
print request.POST
if request.method == 'POST':
website=request.POST.get('website','')
comment=request.POST.get('comment','')
name=request.POST.get('name','')
gender=request.POST.get('gender','')
email=request.POST.get('email', '')
license=request.POST.getlist('license[]')
for id in license:
licInst = licenseType(licenseId=id,email=email)
licInst.save()
sbinstance = sandBox1(website=website,comment=comment,name=name,gender=gender,email=email)
sbinstance.save()
return render(request,template_name,context)
Raw sql method/ but im still confused on ORM method
def sandbox(request):
template_name='domdom.html'
sandBoxObj = sandBox1.objects.all()
con = sqlite3.connect('/home/user1/PycharmProjects/djrest/invoicesproject/db.sqlite3') #sqlite database file location
cursor = con.cursor()
cursor.execute(''' select todos_sandBox1.email,todos_sandBox1.name,todos_sandBox1.website,todos_sandBox1.comment,todos_sandBox1.gender,todos_licenseType.licenseId from todos_sandBox1
join todos_licenseType on todos_sandBox1.email=todos_licenseType.email
''') #it looks like django appends app name to table eg. appname = todos
result = cursor.fetchall()
#https://www.youtube.com/watch?v=VZMiDEUL0II
context = { 'result':result }
print request.POST
if request.method == 'POST':
website=request.POST.get('website','')
comment=request.POST.get('comment','')
name=request.POST.get('name','')
gender=request.POST.get('gender','')
email=request.POST.get('email', '')
license=request.POST.getlist('license[]')
for id in license:
licInst = licenseType(licenseId=id,email=email)
licInst.save()
sbinstance = sandBox1(website=website,comment=comment,name=name,gender=gender,email=email)
sbinstance.save()
return render(request,template_name,context)
Sorry if this answers the wrong question, but you may want to consider a different data model/ architecture. You are hardcoding SANDBOX1 which implies that there might be multiple Sandboxes and you are listing email fields which aren't tied to the User object. Some basic abstractions may simplify the work. Maybe something like:
from django.contrib.auth.models import User
...
class LicenseTypes(models.Model):
name = models.CharField(max_length=500)
class Customer(models.Model):
name = models.CharField(max_length=500)
license = models.ForeignKey(LicenseType)
class RegisteredUser(models.Model):
customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
user = models.ForeignKey(User)
I like this architecture better because it uses a lot more native django functionality. And makes joins really basic. Check this out in a view:
def django_view(request):
registered_user = RegisteredUser(user=request.user)
#example of how to use the join implicitly/ directly
license = registered_user.customer.license.name

How to save a checkboxed values to ManyToManyField in django with a through relationship?

I'm currently working on a fairly simple django project and could use some help.Currently I am stuck on saving form using checkboxes.
I have the following models with a ManyToMany and through relationship:
class ProfileMatch(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,unique=True)
profiles = models.ManyToManyField(UserProfile,blank=True)
def __unicode__(self):
return "Profile id: %s" %(self.user.id)
I created a HTML form for this with checkbox .Selected profiles_id should save with associate user_id
<form action="." method="POST" class="post-form">{% csrf_token %}
<thead>
<th>Select</th>
<th>Profile-ID</th>
</thead>
<tbody>
{% for user in userprofiles %}
<tr>
<label class="checkbox">
<input type="checkbox" name="user" data-toggle="checkbox" value="{{ user.pk }}">
</label>
<td>{{ user.profile_id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit" class="save btn btn-default">Add Selected </button>
</form>
And a simple view to save the form:
def PremuiumUserProfileSelectList(request, pk):
match = ProfileMatch.objects.get(pk=pk)
if request.method == 'POST':
if request.POST.getlist("user", None):
checked = request.POST.getlist("user", None)
premium_user = User.objects.get(pk=pk)
m = match(user=premium_user, profiles=checked)
m.save()
else:
return render(request, "premiumuser/selected_list.html", context)
else:
return render(request, "premiumuser/selected_list.html", context)
This doesn't saves the form.Form fields were rendered and all selected profiles_id's are showing in a list .How do I save this Form ?I want to save all selected checkbox values in associated user.How do I save it?
You just do, assuming checked is list of ids.
match.profiles.add(*checked)

saving changes to a row in django

I have a table with a user as a foreign key. I'm displaying the data in a template.
I'd like the user to be able to edit or delete the data. I know that there's a save() method for doing this, but I don't understand how to access a particular row. If I have the following model:
class Inventory(models.Model):
item = models.CharField(max_length=20, blank=True)
needs_repairs = models.BooleanField(default=True)
date = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return '%s %s'%(self.item, self.needs_repairs)
And here's my form:
class InventoryForm(ModelForm):
class Meta:
model = Inventory
fields = '__all__'
And a view:
def inventory(request):
model = Inventory
stuff = Inventory.objects.all()
form = InventoryForm(data = request.POST)
if request.method == "POST":
if form.is_valid():
obj = form.save(commit=False)
obj.save()
# return redirect('index')
else:
form = InventoryForm()
context = RequestContext(request)
return render_to_response('inventory.html', {
'form':form, 'stuff':stuff
}, RequestContext(request))
And my template that collects and displays data:
<div>
<div class="formfloatleft">
<h2>Truck Inventory </h2>
<div class="tablewrap">
<table class="gradienttable">
<thead>
<tr>
<th><p>Whatcha got?</p></th>
<th><p>Needs Repairs</p></th>
<th><p>Change</p></th>
</tr>
</thead>
<div class="datatables">
{% for things in stuff %}
<tr class="datarow">
<td>{{things.item}}</td>
<td>{{things.needs_repairs}}</td>
<td>
<form method="post">
{% csrf_token %}
<input type="submit" value="edit or remove me">
</form>
</td>
</tr>
{% endfor %}
</div>
</table>
</div>
</div>
<div class='formfloatright' >
<h2>Add stuff</h2>
<form action="" method="post">
{% csrf_token %}
<ul>
{{ form.as_ul}}
</ul>
</ul>
<input type="submit" value="Save" />
</form>
</div>
</div>
I've tried setting up a function which was called when the user clicked the edit button. This didn't work.
def delete_item(item_id):
thing = Inventory.objects.get(pk=id)
thing.item = None
thing.save()
It didn't work, and then I wound up with circuitous errors. I've deleted it, and can't replicate them (sorry).
How can I allow a user (who has permissions) to select and edit a row using the provided button? Let's say one of the items gets repaired or breaks, for example. I've read the docs, and googled extensively, and I'm still confused about how this is done.
Thanks so much.
This may be giving you Integrity error, I Think so error will be..
null value in column "item" violates not-null constraint
Try this -
def delete_item(item_id):
thing = Inventory.objects.get(pk=id)
thing.item = ''
thing.save()
OR
Inventory.objects.filter(id=id).update(item='')
Hope this will work for you.

how to auto increament id field by 1 in text box?

i want to auto increament for car_id field which is primary key but after saving registration data the car_id field should automaticaly increament so please anyone can suggest me for this.and my code is as follow.
models.py
class car(models.Model):
car_id = models.IntegerField(max_length=400, primary_key=True)
plate_no = models.IntegerField(max_length=400)
brand = models.CharField(max_length=400)
model = models.CharField(max_length=400)
Condition = models.CharField(max_length=400)
daily_price = models.IntegerField()
def __str__(self):
return ' '.join([
self. ordering,
])
views.py
def display_car(request):
carid_query = car.objects.values('car_id')
plate = car.objects.values('plate_no')
brand = car.objects.values('brand')
model = car.objects.values('model')
price = car.objects.values('daily_price')
condition = car.objects.values('Condition')
query_all = car.objects.all()
data={
'carid_query': carid_query,
'plate': plate,
'brand': brand,
'model': model,
'price': price,
'condition': condition,
'query_all': query_all,
}
return render(request, 'view_car.html', data)
HTML
<body>
<div class="center">
Home&nbsp Car Registration&nbsp Rent
</div>
<form action="/car/" id="form_id" method="post">
{% csrf_token %}
<div id="head_div">
<h3>car Registration</h3></div>
<table class="center">
<tr><td>
Car_id:<input type="text" name="car_id"><td>
<td>plate no:<input type="text" id="plate_id" name="plate_id"></td></tr>
<tr><td>Brand:<input type="text" id="brand_id" name="brand_id"><td>
<td>Model:<input type="text" name="model_id"></td></tr>
<tr><td>
Daily Price:<input type="text" id="price_id" name="price_id"></td>
<td>
Condition:<select name="select_id"><option value="Good">simple</option>
<option value="middle">A/C</option>
<option value="bad">good</option></select></td>
</tr>
<tr>
<td><input type="submit" id="sub_id" onclick="demo(this.form)"> <input type="button" id="cancel_id" VALUE="Cancel"></td>
</tr>
</table>
</form>
</body>