I am trying to save po_id as a unique key of the "Order table". So I am generating a random number in the Order Form. But the issue is that somehow I can not save the form, even though all the fields are filled up.
models.py
def random_string():
return str(random.randint(10000, 99999))
class Order(models.Model):
po_id = models.CharField(max_length=4, default = random_string)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['supplier', 'product', 'po_id']
widgets = {
'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}),
'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}),
}
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
Order.html
<form action="#" method="post" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="po_id" class="control-label mb-1">ID</label>
{{ form.po_id }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div>
<button id="payment-button" type="submit" class="btn btn-lg btn-success btn-block">
<span id="payment-button-amount">Save</span>
</button>
</div>
Can help me with how I can solve the issue?
Related
I want to make an input that uploads multiple images. I have been reviewing some tutorials and my experience makes me not understand many things.
I placed a view but in the template, where the input should appear, this appears:
<QuerySet []>
Obviously that should not be there, the input should appear that uploads the images when clicked. Can you see my code? can you give me a hint?
html
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
<div class="col-md-4">
<div class="mb-3">
<label class="form-label">Insurance company</label>
{{ form.compañia_seguros }}
<div class="invalid-feedback">
Please provide a website.
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-4">
<div class="mb-3">
<label>Cliente</label>
{{ form.cliente }}
</div>
</div>
</div>
<div class="tab-pane" id="pictures" role="tabpanel">
<div>
{{ images }}
<label for="file-input" class="btn btn-outline-success">Upload images</label>
<p id="num-of-files">No files chosen</p>
<div id="images"></div>
</div>
</div>
<div class="tab-pane" id="warranty" role="tabpanel">
<div>
{{ garantias }}
<label for="file-inputz" class="btn btn-outline-success">Upload images</label>
<p id="num-of-filez">No files chosen</p>
<div id="imagez"></div>
</div>
<br>
<button class="btn btn-primary mb-3" type="submit" value="Post">Save</button>
</div>
</form>
views.py
def create_carros(request):
if request.method == "POST":
form = CarroForm(request.POST)
images = request.FILES.getlist('fotosCarro')
garantias = request.FILES.getlist('garantia')
for image in images:
Carro.objects.create(fotosCarro=image)
for garantia in garantias:
Carro.objects.create(garantias=garantia)
form = CarroForm(request.POST)
images = FotosCarro.objects.all()
garantias = Garantia.objects.all()
return render(request, 'carros/carros-form-add.html', {'images': images,'garantias': garantias,'form':form})
models.py
class Carro(models.Model):
compañia_seguros=models.CharField(max_length=255, null=True)
cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
fecha_registros = models.DateTimeField(default=datetime.now, null=True)
def __str__(self):
return f'{self.compañia_seguros}{self.cliente}' \
f'{self.fecha_registros}'
class FotosCarro(models.Model):
carro = models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
fotosCarro=models.ImageField(null=True, upload_to="images/")
class Garantia(models.Model):
carro = models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
garantia=models.ImageField(null=True, upload_to="images/")
forms.py
class CarroForm(forms.ModelForm):
class Meta:
model=Carro
fields = ['compañia_seguros','cliente']
exclude = ['fecha_registros']
widgets = {
'compañia_seguros': forms.TextInput(
attrs={
'class': 'form-control'
}
),
'cliente': forms.Select(
attrs={
'class': 'form-select'
}
),
'fecha_registros': forms.DateInput(
attrs={
'class': 'form-control',
}
),
}
class FotosForm(forms.ModelForm):
model = FotosCarro
widgets = {
'fotosCarro':forms.FileInput(
attrs={
'class': 'type-file',
'multiple': True,
'id': 'file-input',
'onchange':'preview()',
}
),
}
class GarantiaForm(forms.ModelForm):
model = Garantia
widgets = {
'garantia':forms.FileInput(
attrs={
'class': 'type-file',
'multiple': True,
'id': 'file-inputz',
'onchange': 'previewz()',
}
),
}
Now that you have separated out FotosCarro and Garantia as their own models, I assume that Carro can have more than one of each of these. This means your form needs to be a bit more complex. To include "subforms" for related models in the parent form, you can to use inline formsets. This will allow you to upload images for multiple FotosCarros and Grantias for a single Carro.
I am trying not to use formset in my form. Instead of that, I trying to create form dynamically and save all forms data in DB. Currently, I can create a dynamic form, but the thing is I fail to save all data from the form even though I create multiple forms. Now my code only can save only one form. But I want to save the whole form (with multiple form data) in DB.
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
part=part,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['supplier', 'product', 'part','po_id']
widgets = {
'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}),
'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}),
'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}),
}
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form">
<div class="form-group">
<label for="po_id" class="control-label mb-1">ID</label>
{{ form.po_id }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</div>
<button id="add-form" type="button">Add Another Order</button>
<div>
<button id="payment-button" type="submit" class="btn btn-lg btn-success btn-block">
<span id="payment-button-amount">Save</span>
</button>
</div>
</form>
<script>
let poForm = document.querySelectorAll(".form")
let container = document.querySelector("#form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = poForm.length-1
addButton.addEventListener('click', addForm)
function addForm(e){
e.preventDefault()
let newForm = poForm[0].cloneNode(true)
let formRegex = RegExp(`form-(\\d){1}-`,'g')
formNum++
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
container.insertBefore(newForm, addButton)
totalForms.setAttribute('value', `${formNum+1}`)
}
</script>
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
forms.save() # add save here
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
part=part,
)
return redirect('order-list')
I am working with two different forms that loads info from two different models. One form is disabled to edit and the second form is enabled.
Everything is right until I use UpdateView, when I try to make changes on the enable to edit form nothing happens. I am new in Django and found the code on a tutorial and adapted it to my project.
Why UpdateView is not saving changes?
models.py:
class Sitioproyecto(models.Model):
.
.
def __str__(self):
return self.nombre_del_sitio
class Sitiocontratado(models.Model):
sitioproyecto = models.ForeignKey(Sitioproyecto, on_delete=models.CASCADE)
.
.
def __str__(self):
return self.sitioproyecto.nombre_del_sitio
forms.py:
class SitioContratadoForm(forms.ModelForm):
class Meta:
model = Sitiocontratado
exclude = ['slug',]
widgets = {
'fecha_de_contratacion' : forms.DateInput(attrs={
'type' : 'date',
'class' : "form-control pull-right",
'id' : "fechadecon",
}),
'sitioproyecto' : forms.Select(attrs={
'type' : 'text',
'class' : "form-control",
'id' : 'nombresitio',
}),
.
.
}
views.py:
class CrearSitiosContratadosView(CreateView):
model = Sitiocontratado
template_name = 'sitios/contratados/editar_contratado.html'
form_class = SitioContratadoForm
success_url = reverse_lazy('pagina:tabla_contratados')
class UpdateSitiosContratadosView(UpdateView):
model = Sitiocontratado
second_model = Sitioproyecto
template_name = 'sitios/contratados/editar_contratado.html'
form_class = SitioContratadoForm
second_form_class = SitioProyectoForm
success_url = reverse_lazy('pagina:tabla_contratados')
def get_context_data(self, **kwargs):
context = super(UpdateSitiosContratadosView, self).get_context_data(**kwargs)
pk = self.kwargs.get('pk', 0)
sitiocontratado = self.model.objects.get(id=pk)
sitioproyecto = self.second_model.objects.get(id=sitiocontratado.sitioproyecto_id)
if 'form' not in context:
context['form'] = self.form_class()
if 'form2' not in context:
context['form2'] = self.second_form_class(instance=sitioproyecto)
context['id'] = pk
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object
id_sitiocontratado = kwargs['pk']
sitiocontratado = self.model.objects.get(id=id_sitiocontratado)
sitioproyecto = self.second_model.objects.get(id=sitiocontratado.sitioproyecto_id)
form = self.form_class(request.POST, instance=sitiocontratado)
form2 = self.second_form_class(request.POST, instance=sitioproyecto)
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form, form2=form2))
template:
{% block content %}
<form class="form-vertical" method="POST">
{% csrf_token %}
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Agregar Sitio</h3>
</div>
<div class="box-body">
<div class="row justify-content-start">
<fieldset class="col-md-3 form-group" disabled>
<label for="fechadeval" class="control-label">Fecha de Validación</label>
{{ form2.fecha_de_validacion }}
</fieldset>
<div class="col-md-3 form-group">
<label for="fechadecon" class="control-label">Fecha de Contratación</label>
{{ form.fecha_de_contratacion }}
</div>
</div>
<div class="row justify-content-start">
<fieldset class="col-md-8 form-group" disabled>
<label for="fechadecon" class="control-label">Nombre del Sitio</label>
{{ form.sitioproyecto }}
</fieldset>
<fieldset class="col-md-2 form-group" disabled>
<label for="estatus" class="control-label">ID del Sitio</label>
{{ form2.id_sitio }}
</fieldset>
<fieldset class="col-md-1 form-group" disabled>
<label for="estatus" class="control-label">Candidato</label>
{{ form2.candidato }}
</fieldset>
.
.
</div>
<div class="box-footer">
<a class="btn btn-default" href="{% url 'pagina:tabla_contratados' %}">Regresar</a>
<button type="submit" value="Update" class="btn btn-primary">Guardar</button>
</div>
</div>
</form>
{% endblock %}
In get_context() and post() replace-
context['form2'] = self.second_form_class(instance=sitioproyecto)
with
context['form2'] = self.second_form_class(instance=request.Sitiocontratado.sitioproyecto)
and simply save it!! that's it
you don't need to deal with pk
I had a form with some fields and it was working fine. But when adding new field in the Model django raise an error
when I run the server and click on submit then it shows error for the new field This field is required although I am providing data for this field in the form.
Model.py
class UserInformation(models.Model):
firstName = models.CharField(max_length=128)
lastName = models.CharField(max_length=128)
userName = models.CharField(max_length=128)
institution = models.CharField(choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")], max_length=128)
userEmail = models.CharField(default="N/A", max_length=128)
phoneNumber = models.CharField(max_length=128)
orchidNumber = models.CharField(max_length=128)
PI = models.CharField(max_length=128)
PIUsername = models.CharField(max_length=128)
PIInstitution = models.CharField(default="N/A",choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")], max_length=128)
PIEmail = models.CharField(default="N/A", max_length=128)
PIPhoneNumber = models.CharField(max_length=128)
In this model
PIEmail is the field which I have added.
forms.py
class UserInformationForm(ModelForm):
firstName = forms.CharField(max_length=254,
widget=forms.TextInput({
'class': 'form-control',
}))
lastName = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
userName = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
institution = forms.ChoiceField( choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")]
,widget=forms.Select({
'class': 'form-control',
}))
phoneNumber = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
orchidNumber = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
PI = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
PIUsername = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
ctsaPIInstitution = forms.ChoiceField( choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")]
,widget=forms.Select({
'class': 'form-control',
}))
PIPhoneNumber = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
userEmail = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
PIEmail = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
class Meta:
model = UserInformation
exclude = ()
and here is my register.html
<div class="row">
<section id="registerForm">
<div style="font-size:15px; color:red;">
The fields marked with an asterisk (*) are mandatory.
</div><br/>
<form method="post" action=".">{% csrf_token %}
<div class="form-group">
<label for="id_firstName" >First Name (*)</label>
{{ form.firstName }}
</div>
<div class="form-group">
<label for="id_lastName" >Last Name (*)</label>
{{ form.lastName }}
</div>
<div class="form-group">
<label for="id_email">Username (*)</label>
{{ form.userName }}
</div>
<div class="form-group">
<label for="id_intitution">Institution (*)</label>
{{ form.institution }}
</div>
<div class="form-group">
<label for="id_phone" >Contact Number</label>
{{ form.phoneNumber }}
</div>
<div class="form-group">
<label for="id_orcid">Orcid ID (Get Orcid ID)</label>
{{ form.orchidNumber }}
</div>
<div class="form-group">
<label for="id_ctsaPI">Prinicipal Investigator (*)</label>
{{ form.PI }}
</div>
<div class="form-group">
<label for="id_PI">CTSA Prinicipal Investigator Username (*)</label>
{{ form.PIUsername }}
</div>
<div class="form-group">
<label for="id_ctsaPI">Prinicipal Investigator Institute (*)</label>
{{ form.PIInstitution }}
</div>
<div class="form-group">
<label for="id_PIName"> Prinicipal Investigator Phone Number (*)</label>
{{ form.PIPhoneNumber }}
</div>
<div class="form-group">
<label for="id_UserEmail">User Email (*)</label>
{{ form.userEmail }}
</div>
<div class="form-group">
<label for="id_PI">PI Email (*)</label>
{{ form.PIEmail }}
</div>
<div class="form-group" >
<br/>
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</section>
view.py
#csrf_protect
def register(request):
if request.method == 'POST':
form = UserInformationForm(request.POST)
if form.is_valid(): //// here it is breaking
form.save()
else:
form = UserInformationForm()
variables = { 'form': form }
return render(request, 'registration/register.html',variables)
I am not sure what is wrong in this code
I'm not sure if this helps but sometimes I find the errors returned look like a bit of a red herring and end up driving me mad for hours on end. I am no expert and from where I am sitting the code for your form looks fine to me which is probably why it was working before. However in your html file you have two labels specified with the same id, the second one just happens to be on the PIEmail field that you have recently added. Coincidence? Maybe! It's a long shot but perhaps change that initially and see if it makes any difference.
Change:
<div class="form-group">
<label for="id_PI">PI Email (*)</label>
{{ form.PIEmail }}
</div>
to:
<div class="form-group">
<label for="id_PIEmail">PI Email (*)</label>
{{ form.PIEmail }}
</div>
Note: The other instance is on the PIUsername field.
I am trying to create a ModelForm that links to an external database, and when you submit the form the external database gets updated. The problem comes when I check the validity of the form, it is invalid.
I have done some researching into this and found the most common problem was that the form is not bound, but when I use print(form.non_field_errors) I get:
<bound method BaseForm.non_field_errors of <EmailForm bound=True, valid=False, fields=(subject;body;name;altsubject;utm_source;utm_content;utm_campaign)>
models.py:
class MarketingEmails(models.Model):
messageid = models.AutoField(db_column='column1', primary_key=True)
subject = models.CharField(db_column='column2', max_length=2000)
body = models.TextField(db_column='column3') #using a text field as there is no maximum length
name = models.CharField(db_column='column4', max_length=25)
altsubject = models.CharField(db_column='column5', max_length=2000)
utm_source = models.CharField(db_column='column6', max_length=25)
utm_content = models.CharField(db_column='column7', max_length=25)
utm_campaign = models.CharField(db_column='column8', max_length=25)
class Meta:
managed = False
db_table = ''
forms.py:
class EmailForm(forms.ModelForm):
class Meta:
model = MarketingEmails
fields = ['messageid','subject','body','name','altsubject','utm_source','utm_content','utm_campaign']
views.py:
def emailinfo(request, pk):
if request.session.has_key('shortname'):
shortname = request.session['shortname']
rows = get_object_or_404(MarketingEmails, pk=pk)
if request.method == 'POST':
form = EmailForm(request.POST)
print(form.errors)
print(form.non_field_errors)
if form.is_valid():
form.save()
print("form is valid")
return redirect('marketingemails:emailinfo', pk = rows.messageid)
return render(request, 'marketingemails/emailinfo.html',{'shortname': shortname, 'rows': rows})
else:
return HttpResponseRedirect(reverse('common:login'))
urls.py:
app_name = 'marketingemails'
urlpatterns = [
url(r'^marketing/emails/(?P<pk>[0-9]+)/$', marketingviews.emailinfo, name='emailinfo'),
]
html:
<form method="POST" class="post-form" action ="">
{% csrf_token %}
<label for="exampleTextarea">Name</label>
<textarea class="form-control" id="exampleTextarea" rows="1">{{ rows.name }}</textarea>
<label for="exampleTextarea">Subject</label>
<textarea class="form-control" id="exampleTextarea" rows="1">{{ rows.subject }}</textarea>
<label for="exampleTextarea">Alternative Subject</label>
<textarea class="form-control" id="exampleTextarea" rows="1">{{ rows.altsubject }}</textarea>
<label for="exampleTextarea">Body</label>
<div class="ibox-content no-padding">
<div class="summernote">
{{ rows.body }}
</div>
</div>
<label for="exampleTextarea">utm_source</label>
<textarea class="form-control" id="exampleTextarea" rows="1">{{ rows.utm_source }}</textarea>
<label for="exampleTextarea">utm_content</label>
<textarea class="form-control" id="exampleTextarea" rows="1">{{ rows.utm_content }}</textarea>
<label for="exampleTextarea">utm_campaign</label>
<textarea class="form-control" id="exampleTextarea" rows="1">{{ rows.utm_campaign }}</textarea>
<button type="submit" class="save btn btn-default">Save</button>
</form>
Your HTML form doesn't name the fields so the form can't get them. You want to use the form for rendering too : https://docs.djangoproject.com/en/1.11/topics/forms/#working-with-form-templates