I created two classes: Client (attributes: name and sex) and Account (attributes: customer[fk], the payment status). I show the form from templates; When I click the link "Add Customer" it opens the form of creation, from what has in models.py, other words can only create a client to "name and sex," but not I can integrate in the same form payment situation.
models.py
from django.db import models
class Cliente(models.Model):
SEXO = (
('M', 'Masculino'),
('F','Feminino'),
)
nome = models.CharField("Nome do cliente", max_length=255)
sexo = models.CharField("Sexo", max_length=1, choices=SEXO)
def __unicode__(self):
return self.nome
class Meta:
verbose_name = 'Cliente'
verbose_name_plural = 'Clientes'
class Conta(models.Model):
STATUS_CONTA = (
('A', 'A Pagar'),
('P', 'Pago'),
)
cliente = models.ForeignKey(Cliente, related_name='conta')
situacao = models.CharField("Situação", max_length=50, choices=STATUS_CONTA)
class Meta:
verbose_name = 'Conta'
verbose_name_plural = 'Contas'
def __unicode__(self):
return self.cliente.nome
forms.py
from django.forms.models import ModelForm
from cadastro.models import Cliente, Conta
__author__ = 'Admin'
class ClienteForm(ModelForm):
class Meta:
model = Cliente
index.html
<html>
<body>
<a href='/adicionar_cliente/'>Adicionar cliente</a>
{% for cliente in clientes %}
{% for conta in cliente.conta.all %}
<p>Nome: {{cliente.nome}}</p>
<p>Sexo: {{cliente.get_sexo_display}} </p>
<p>Situação do pedido: {{conta.get_situacao_display}}</p>
{% endfor %}
<p><a href='/excluir/{{cliente.id}}/'>Excluir?</a></p>
<p><a href='/editar/{{cliente.id}}/'>Editar</a></p>
<hr>
{% empty %}
<h3>Não existe nenhum cliente.</h3>
{% endfor %}
</body>
</html>
form.html
<html>
<body>
<form action='/{{action}}/' method='post'>
{% csrf_token %}
<table>
{{form}}
</table>
<input type='submit' value='Adicionar' />
</form>
</body>
</html>
You can create two forms to accomplish this task.
forms.py
...
class ClienteForm(ModelForm):
class Meta:
model = Cliente
class ContaForm(ModelForm):
class Meta:
model = Conta
exclude = ("cliente") #exclude the cliente field from showing up in the form rendering.
form.html
<html>
<body>
<form action='/{{ action }}/' method='post'>
{% csrf_token %}
<table>
{{ form.as_table }} <!-- added as table which was missing from original post. -->
{{ form2.as_table }}
</table>
<input type='submit' value='Adicionar' />
</form>
</body>
views.py
...
def form(request):
if request.method == 'POST':
form = ClienteForm(request.POST)
form2 = ContaForm(request.POST)
if form.is_valid() and form2.is_valid():
client = form.save()
conta = form2.save(commit=False)
conta.cliente = client
contra.save()
else:
form = ClienteForm()
form2 = ContaForm()
return render_to_response('form.html', locals(), context_instance = RequestContext(request))
Related
I'm trying to get a list of objects in Django from a model.
I just want to get the list of 'dht node' from the request user, but it shows nothing in the html file (as if the list was empty). The user that I'm using has 2 'dht nodes' and they're shown in the django admin.
I don't know what is wrong, because if I use the instruction "member.dht.create(...)" in the views function and a create a new 'dht node' like this, this is shown. Only 'dht nodes' that I enter by form do not show. Can be the form?
Thanks a lot, Here's my code:
Models.py
class Node(models.Model):
name = models.CharField(primary_key=True, null=False, max_length= 50)
description= models.CharField(default=None, null=False, max_length= 250)
topic=models.CharField(default=None, null=False, max_length= 50, unique=True)
def __unicode__(self):
return self.name
class dht(Node):
temp = models.IntegerField(default=None, null=True)
hum = models.IntegerField(default=None, null=True)
class UserProfile(User):
uid = models.CharField(default=None, null=False, max_length= 250)
dht = models.ManyToManyField(dht, blank=True)
def __unicode__(self):
return self.user.username
Views.py -dht list-
#login_required(login_url = '/web/login')
def listDhtSensor(request):
member = request.user.userprofile
list = member.dht.all()
return render(request, 'web/listDhtSensor.html', {'list':list})
Html -listDhtSensor.html-
{% block content %}
{% for dht in list %}
{{ dht.name }}
{{ dht.topic }}
{% endfor %}
{% endblock %}
Forms.py
class newDHTSensorForm(forms.ModelForm):
class Meta:
model = dht
field = ['name',
'description',
'topic',]
labels = {'name': 'Name' ,
'description': 'Description',
'topic': 'Topic',}
exclude = ['temp', 'hum']
Views.py -dht form-
#login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Html -newDhtSensor.html-
{% block content %}
<div class="boxReg">
<form method="post">
{% csrf_token %}
<h2>{{ form.name.errors.as_text }}</h2>
<p><label for="id_name">Name:</label> <input class="barraForm" type="text" name="name" maxlength="150" autofocus="" required="" id="id_name"></p>
<p><label for="id_description">Description:</label> <input class="barraForm" type="text" name="description" maxlength="150" id="id_description"></p>
<h2>{{ form.topic.errors.as_text }}</h2>
<p><label for="id_topic">Topic:</label> <input class="barraForm" type="text" name="topic" maxlength="254" id="id_topic"></p>
<div class="boxButtonReg">
<button class="buttonReg" type="submit">Save</button>
</div>
</form>
</div>
{% endblock %}
It shows nothing because you did not link you dht objects to that UserProfile, so if you later query for the dhts for that UserProfile, evidently the list is empty. You should add it to the dht relation, like:
#login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save()
request.user.userprofile.dht.add(post)
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Note that you first need to save the post, so you should omit the commit=False aprameter.
I created a model and respective ModelForm, view and Template for it, but ModelForm does not save data to the model even though .save() function is used.
I have tried reviewing forms and views but I do not know what is wrong.I have posted the respective models, forms, views and templates in the question.
models.py:
class Centre(models.Model):
Location = (
('rashmi_heights', 'Rashmi Heights Centre'),
('Levana', 'Levana Centre')
)
name= models.CharField(max_length=50, blank=False, choices=Location, unique=True)
address = models.CharField(max_length =250)
contact = models.CharField(max_length=100, blank=False)
phone = PhoneField(blank=True, help_text='Contact phone number')
def __str__(self):
return self.name
forms.py:
class CentreForm(forms.ModelForm):
class Meta():
model = Centre
fields = '__all__'
views.py:
def centre(request):
forms = CentreForm()
if request.method == 'POST':
forms = CentreForm(request.POST)
if forms.is_valid():
centre = forms.save(request.POST)
centre.save()
else:
forms = CentreForm()
return render(request,'NewApp/centreinfo.html',{'forms':forms})
template:
<!DOCTYPE html>
{% extends 'NewApp/base.html' %}
{% load staticfiles %}
{% block body_block %}
<div class="jumbotron">
<h2>Fill details about your centre.</h2><br>
<h3> </h3>
<form method="post" enctype="multipart/form-data">
{{forms.as_p}}
{% csrf_token %}
<a class="btn btn-primary" href="{% url 'NewApp:centreinfo' %}">Submit</a>
</form>
</div>
{% endblock %}
forms.py:
class CentreForm(forms.ModelForm):
class Meta: -> change here
model = Centre
fields = '__all__'
def centre(request):
forms = CentreForm()
if request.method == 'POST':
forms = CentreForm(request.POST)
if forms.is_valid():
forms.save(request.POST)
else:
forms = CentreForm()
return render(request,'NewApp/centreinfo.html',{'forms':forms})
html
<form method="post" enctype="multipart/form-data">
{{forms.as_p}}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I am new to django and I have the following problem. When I login and create a company using the createCompany.html, the company gets created in the database but its 'user' attribute stays empty. The user attribute is supposed to be the user who is logged in and creating the company. What do you think is wrong with my code?
models.py
from django.db import models
from django.contrib.auth.models import User
class Company(models.Model):
name = models.CharField(primary_key = True, max_length = 100)
city = models.CharField(max_length = 30, null = True)
user = models.OneToOneField(User, on_delete=models.SET_NULL, null = True)
yontemler =(('3CNC', '3 eksen CNC'),('5CNC', '5 eksen CNC'),)
imalatyontem = models.CharField(max_length=30, choices=yontemler, null=True, verbose_name = 'İmalat Yöntemleri')
industries =(('Imalat', 'İmalat'),('Kimya', 'Kimya'),('Hammadde', 'Hammadde'),)
industry = models.CharField(max_length=20, choices=industries, null=True, help_text='Sektörünüzü Seçin')
#classmethod
def create(cls, name, city, user, imalatyontem, industry):
company = cls(name=name, city=city, user=user, imalatyontem=imalatyontem, industry=industry)
return company
def get_absolute_url(self):
return models.reverse('company-detail', args=[str(self.id)])
def __str__(self):
return self.name
views.py
from .forms import CompanyCreationForm
def createCompany(request):
if request.method == 'POST':
form = CompanyCreationForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data.get('name')
city = form.cleaned_data.get('city')
user = request.user
imalatyontem = form.cleaned_data.get('imalatyontem')
industry = form.cleaned_data.get('industry')
Company.create(name, city, user, imalatyontem, industry)
return redirect('index')
else:
form = CompanyCreationForm()
return render(request, 'createCompany.html', {'form': form})
forms.py
from django import forms
from .models import Company
class CompanyCreationForm(forms.ModelForm):
class Meta:
model = Company
fields = ['name', 'city', 'imalatyontem', 'industry']
createCompany.html
{% extends "base_generic.html" %}
{% block content %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form action="/createCompany/" method="post">
{% csrf_token %}
{% for field in form %}
<fieldset class="control-group">
<label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label>
<div class="controls">
{{ field }}
<p class="help-text">{{ field.help_text }} </p>
</div>
</fieldset>
{% endfor %}
<input type="submit" value="Submit" />
</form>
{% endblock %}
Your create classmethod is pointless; you should remove it. It doesn't save the object, which is then just thrown away.
The work of creating the instance is actually done by form.save, before you add the user. So you should use the standard pattern for this:
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
return redirect('index')
I have created a Django form to get the data from user and search that given data in database models.
But i am not able to use the dropdown functionality correctly. I have used ModelChoiceField but I am getting it empty.
I have three fields(forms.py) which i am searching in the database.
models.py
class Release(models.Model):
number = models.CharField(max_length=50,unique=True)
notes = models.CharField(max_length=50)
changes = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.number)
class Metamodule(models.Model):
name = models.CharField(max_length=50,unique=True)
version = models.IntegerField(default=0)
release = models.ForeignKey(Release,related_name="num")
createdate = models.DateField(auto_now=True, null=True)
createdby = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.name)
class Module(models.Model):
name = models.CharField(max_length=50,unique=True)
version = models.IntegerField(default=0)
metamodule = models.ForeignKey(Metamodule,related_name="metaname")
createdate = models.DateField(auto_now=True, null=True)
changes = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.name)
forms.py
class ModuleForm(forms.Form):
release_num = forms.ModelChoiceField(queryset=Release.objects.all().values('number'),empty_label='Pick a Release')
metamodule_name = forms.CharField(max_length=50)
module_name = forms.CharField(max_length=50)
views.py
from django.shortcuts import render
from search.forms import ModuleForm
from django.http import HttpResponse
from search.models import Module,Metamodule,Release
def searchview(request):
if request.method == 'GET':
form = ModuleForm(request.GET)
if form.is_valid():
release_num = form.cleaned_data['release_num']
metamodule_name = form.cleaned_data['metamodule_name']
module_name = form.cleaned_data['module_name']
results = Module.objects.filter(metamodule__release__number=release_num).filter(metamodule__name=metamodule_name).filter(name=module_name)
return render(request,'search/search_result.html',{'form': form, 'results': results})
else:
form = ModuleForm()
return render(request, 'search/search_form.html',{'form': form})
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
{% if error %}
<p style="color: red;">Please submit a search term.</p>
{% endif %}
<form action="/search/" method="get">
<select name="release_num">
{% for release_num in release_num %}
<option value="{{ release_num.number }}">{{ release_num.number }}</option>
{% endfor %}
</select>
<p><label for="metamodule_name">Metamodule:</label>
<input type="text" name="metamodule_name">
<p><label for="module_name">Module:</label>
<input type="text" name="module_name">
<input type="submit" value="Search">
</form>
</body>
</html>
try in the search_form.html:
<form action="/search/" method="get">
{{ form.release_num }}
{{ form.metamodule_name }}
{{ form.module_name }}
I can't get my django app to post to the db. I'm trying to pass my foreign key so I can post it correctly.
Sorry if it's something basic I'm missing I'm just starting. I think it never gets to form = ResultForm(request.POST). And just gives me the form = ResultForm.
Here is my code:
Model:
class Result(models.Model):
category = models.ForeignKey(Category)
category_result = models.CharField(max_length=200)
rating = models.DecimalField('', '', 8, 3)
votes = models.IntegerField(default=0)
created_by = models.IntegerField(default=0, null=True, blank=True)
created_on = models.DateTimeField('created on')
def __unicode__(self):
return self.category_result
Form:
class ResultForm(forms.ModelForm):
category_result = forms.CharField(max_length=200,help_text="Your best line")
rating = forms.DecimalField(widget=forms.HiddenInput(), initial=0)
votes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
created_by = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
category = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = Result
fields = ('category_result', 'rating', 'votes')
view:
def help_out(request, category_id):
if request.method == 'POST':
form = ResultForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.category = category_id
form.save()
return index(request)
else:
print form.errors
else:
form = ResultForm
context = {'form': form, 'category_id': category_id}
return render(request,'pocketwingman/help_out.html', context)
template:
<!DOCTYPE html>
<html>
<head>
<title>Pocketwingman</title>
</head>
<body>
<h1>Add a Result</h1>
<form id="result_form" method="post" action="/pocketwingman/help_out/{{category_id}}/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text}}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Line" />
</form>
</body>
</html>
url config:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<category_id>\d+)/$', views.help_me, name='help_me'),
url(r'^help_out/(?P<category_id>\d+)/$', views.help_out, name='help_out'),
)
You should initiate your form if it's not a POST:
else:
form = ResultForm()
append () to form class.