I want to when i click on the user discharge button it will go to the page and the all user information take automatically. But i cannot get this value. Here is the image in the discharge button i click but its shows like this.
Here is my code : views.py
def discharge_view(request, pk):
form = DischargForm()
if request.method == 'POST':
form = DischargForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Successfull')
return redirect('discharge-patient')
context = {
'form': form,
}
return render(request, 'hospital/discharge.html', context)
forms.py :
class DischargForm(forms.ModelForm):
class Meta:
model = PatientDischarge
fields = ('assign_doctor', 'admitted', 'release_date', 'medicine_cost', 'other_charge')
widgets = {
'assign_doctor': forms.Select(attrs={'class': 'form-control'}),
'admitted': forms.Select(attrs={'class': 'form-control'}),
'release_date': forms.TextInput(attrs={'class': 'form-control'}),
'medicine_cost': forms.TextInput(attrs={'class': 'form-control'}),
'other_charge': forms.TextInput(attrs={'class': 'form-control'}),
}
models.py
class PatientDischarge(models.Model):
assign_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
admitted = models.ForeignKey(Admitted, on_delete=models.CASCADE)
release_date = models.DateField(auto_now_add=False)
medicine_cost = models.IntegerField(null=True)
other_charge = models.IntegerField()
def __str__(self):
return self.admitted.patient_name if all([self.admitted, self.admitted.patient_name]) else 0
def days_count(self):
return self.release_date - self.admitted.admited_date if all([self.admitted, self.admitted.admited_date]) else 0
def room_bill(self):
return self.days_count() * self.admitted.room_service if all([self.admitted, self.admitted.room_service]) else 0
def total_bill(self):
return self.room_bill().days + self.medicine_cost + self.other_charge
discharge.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for fields in form %}
<div class="form-group"></div>
{{ fields.label_tag }}
{{ fields }}
{% endfor %}
<br>
<input type="submit" value="Submit">
To pass an instance to the form you can do this form = DischargForm(instance=<DischargeInstance>) and the template will have pre-filled values in the form as per the instance.
Can you provide your models.py.
Related
I have a Django view that shows two create forms.
Whenever the page loads all of the input fields display - 'This field is required".
enter image description here
Template code
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ listing_create_form.as_p }}
{{ listing_media_form.as_p }}
<button type="submit">Submit Form</button>
</form>
{% endblock %}
views.py
#login_required
def createListing(request):
listing_create_form = ListingCreateForm(request.POST or None, request.FILES)
listing_media_form = ListingMediaForm(request.POST or None, request.FILES)
if request.method == 'POST':
if listing_create_form.is_valid() and listing_media_form.is_valid():
listing_create_form.instance.created_by = request.user
form = listing_create_form.save()
form.save()
new_listing_id = form.pk
# loop over images to upload multiple
for image_uploaded in request.FILES.getlist('image'):
image_instance = ListingMedia.objects.create(listing=form, image=image_uploaded)
image_instance.save()
return redirect('boat_listings')
context = {'listing_create_form': listing_create_form, 'listing_media_form': listing_media_form}
return render(request, 'listings/listing_create_form.html', context)
forms.py
class ListingCreateForm(forms.ModelForm):
class Meta:
model = Listings
widgets = {
"featured_image": forms.FileInput(
attrs={
"enctype": "multipart/form-data"
}
),
}
fields = "__all__"
exclude = ("created_by", "created_on", "last_modified",)
class ListingMediaForm(forms.ModelForm):
class Meta:
# image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
widgets = {
"image": forms.ClearableFileInput(
attrs={
"multiple": True
}
),
}
model = ListingMedia
fields = ['image']
Django template should render without field required message before user has inputted invalid inputs.
it looks like when you initialise form instances, it gets data and tries to validate so that's what you are receiving error messages.
change your view:
#login_required
def createListing(request):
if request.method == 'POST':
listing_create_form = ListingCreateForm(request.POST, request.FILES)
listing_media_form = ListingMediaForm(request.POST, request.FILES)
if listing_create_form.is_valid() and listing_media_form.is_valid():
listing_create_form.instance.created_by = request.user
form = listing_create_form.save()
form.save()
new_listing_id = form.pk
# loop over images to upload multiple
for image_uploaded in request.FILES.getlist('image'):
image_instance = ListingMedia.objects.create(listing=form, image=image_uploaded)
image_instance.save()
return redirect('boat_listings')
else:
listing_create_form = ListingCreateForm()
listing_media_form = ListingMediaForm()
context = {'listing_create_form': listing_create_form, 'listing_media_form': listing_media_form}
return render(request, 'listings/listing_create_form.html', context)
The form I made on Django doesn't save any data, I think it's a validation issue but I can't find where the problem is - whenever I click on the "submit" button the page is refreshed but no new entries are created - when I do that from Django Admin it works fine.
I'm a complete beginner and this is my very first Django project.
models.py
class Utente(models.Model):
id_utente = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
gen_utente = models.CharField(max_length=7, choices=GEN_CHOICES)
age_utente = models.CharField(max_length=2)
con_utente = CountryField()
per_utente = models.CharField(max_length=18, choices=PER_CHOICES)
pres_utente = models.CharField(max_length=11, choices=PRES_CHOICES)
doc_utente = models.CharField(max_length=29, choices=DOC_CHOICES)
vis_utente = models.CharField(max_length=10, choices=VIS_CHOICES)
san_utente = models.CharField(max_length=17, choices=SAN_CHOICES)
nnb_utente = models.CharField(max_length=5, choices=NNB_CHOICES)
unnb_utente = models.CharField(max_length=8, choices=UNNB_CHOICES)
va_utente = models.CharField(max_length=12, choices=VA_CHOICES)
tem_utente = models.DateField()
res_utente = models.CharField(max_length=5000)
def __str__(self):
return f'Utente n: {self.id_utente} del {self.tem_utente}'
forms.py (I've removed the labels)
class UtenteForm(forms.ModelForm):
class Meta:
model = Utente
fields = ['id_utente', 'gen_utente', 'age_utente', 'con_utente', 'per_utente', 'pres_utente', 'doc_utente', 'vis_utente', 'san_utente', 'nnb_utente', 'unnb_utente', 'vac_utente', 'tem_utente', 'res_utente']
labels = {
'id_utente': '.......',
'gen_utente': '.......',
'age_utente': '.......',
'con_utente': '.......',
'per_utente': '.......',
'pres_utente': '.......',
'doc_utente': '.......',
'vis_utente': '.......',
'san_utente': '.......',
'nnb_utente': '.......',
'unnb_utente': '.......',
'vac_utente': '.......',
'tem_utente': '.......',
'res_utente': '.......'
}
widgets = {
'id_utente': forms.TextInput(attrs={'class': 'form-control', 'disabled': True}),
'gen_utente': forms.Select(choices=SESSO_CHOICES, attrs={'class': 'form-control'}),
'age_utente': forms.TextInput(attrs={'class': 'form-control', 'pattern': '([0-9]{2})'}),
'con_utente': CountrySelectWidget(attrs={'class': 'form-control'}),
'per_utente': forms.Select(choices=PERMANENZA_CHOICES, attrs={'class': 'form-control'}),
'pres_utente': forms.Select(choices=PRESENZA_CHOICES, attrs={'class': 'form-control'}),
'doc_utente': forms.Select(choices=DOCUMENTI_CHOICES, attrs={'class': 'form-control'}),
'vis_utente': forms.Select(choices=VISITEPREG_CHOICES, attrs={'class': 'form-control'}),
'san_utente': forms.Select(choices=DOCSANITARI_CHOICES, attrs={'class': 'form-control'}),
'nnb_utente': forms.Select(choices=MMG_CHOICES, attrs={'class': 'form-control'}),
'unnb_utente': forms.Select(choices=USOMMG_CHOICES, attrs={'class': 'form-control'}),
'vac_utente': forms.Select(choices=VACCINOCOVID_CHOICES, attrs={'class': 'form-control'}),
'vis_utente': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
'res_utente': forms.Textarea(attrs={'class': 'form-control', 'rows':'3'})
}
views.py
# Add new utente
def aggiungi_utente(request):
if request.method == 'POST':
form = UtenteForm(request.POST)
if form.is_valid():
new_id_utente = form.cleaned_data ['id_utente']
new_gen_utente = form.cleaned_data ['gen_utente']
new_age_utente = form.cleaned_data ['age_utente']
new_con_utente = form.cleaned_data ['con_utente']
new_per_utente = form.cleaned_data ['per_utente']
new_pres_utente = form.cleaned_data ['pres_utente']
new_doc_utente = form.cleaned_data ['doc_utente']
new_vis_utente = form.cleaned_data ['vis_utente']
new_san_utente = form.cleaned_data ['san_utente']
new_nnb_utente = form.cleaned_data ['nnb_utente']
new_usnnb_utente = form.cleaned_data ['unnb_utente']
new_vac_utente = form.cleaned_data ['vac_utente']
new_tem_utente = form.cleaned_data ['tem_utente']
new_res_utente = form.cleaned_data ['res_utente']
new_utente = Utente(
id_utente = new_id_utente,
gen_utente = new_gen_utente,
age_utente = new_age_utente,
con_utente = new_con_utente,
per_utente = new_per_utente,
pres_utente = new_pres_utente,
doc_utente = new_doc_utente,
vis_utente = new_vis_utente,
san_utente = new_san_utente,
nnb_utente = new_nnb_utente,
unnb_utente = new_unnb_utente,
vac_utente = new_vac_utente,
tem_utente = new_tem_utente,
res_utente = new_res_utente
)
new_utente.save()
return render(request, 'utenti/add-utenti.html', {
'form': UtenteForm(),
'success': True
})
else:
form = UtenteForm()
return render(request, 'utenti/add-utenti.html', {
'form': UtenteForm()
})
# Modify and edit utente
def modifica_utenti(request, pk):
if request.method == 'POST':
utente= Utente.objects.get(pk=pk)
form = UtenteForm(request.POST, instance=utente)
if form.is_valid():
form.save()
return render(request, 'utenti/mod-utenti.html',{
'form': form,
'success': True
})
else:
utente = Utente.objects.get(pk=pk)
form = UtenteForm(instance=utente)
return render(request, 'utenti/mod-utenti.html', {
'form': form
})
# To delete utente
def delete_utente(request, pk):
if request.method == 'POST':
utente = Utente.objects.get(pk=pk)
utente.delete()
return HttpResponseRedirect(reverse('utenti'))
# View utente
def view_utente(request, pk):
utente = Utente.objects.get(pk=pk)
return HttpResponseRedirect(reverse('index'))
template file
{% extends "utenti/base.html" %}
{% block body %}
<h3 class="text-center m-4">Add new utente</h3>
{% if success %}
<div class="alert alert-success" role="alert">
Added successfully.
Go to the list.
</div>
{% else %}
<div class="row justify-content-center">
<div class="col-6">
<div class="card bg-light mb-3">
<div class="card-header">
<i class="fa-solid fa-address-card fa-lg"></i> Create utente
</div>
<div class="card-body">
<form action="{% url 'aggiungi-utenti' %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Add</button>
Cancel
</form>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
Try changing your view to output the validation errors if is_valid() is false. This will help you narrow it down.
error outputs raw HTML
errors.as_data() outputs a dictonary (might be easier to read)
# Add new utente
def aggiungi_utente(request):
if request.method == 'POST':
form = UtenteForm(request.POST)
if form.is_valid():
new_id_utente = form.cleaned_data ['id_utente']
new_gen_utente = form.cleaned_data ['gen_utente']
new_age_utente = form.cleaned_data ['age_utente']
new_con_utente = form.cleaned_data ['con_utente']
new_per_utente = form.cleaned_data ['per_utente']
new_pres_utente = form.cleaned_data ['pres_utente']
new_doc_utente = form.cleaned_data ['doc_utente']
new_vis_utente = form.cleaned_data ['vis_utente']
new_san_utente = form.cleaned_data ['san_utente']
new_nnb_utente = form.cleaned_data ['nnb_utente']
new_usnnb_utente = form.cleaned_data ['unnb_utente']
new_vac_utente = form.cleaned_data ['vac_utente']
new_tem_utente = form.cleaned_data ['tem_utente']
new_res_utente = form.cleaned_data ['res_utente']
new_utente = Utente(
id_utente = new_id_utente,
gen_utente = new_gen_utente,
age_utente = new_age_utente,
con_utente = new_con_utente,
per_utente = new_per_utente,
pres_utente = new_pres_utente,
doc_utente = new_doc_utente,
vis_utente = new_vis_utente,
san_utente = new_san_utente,
nnb_utente = new_nnb_utente,
unnb_utente = new_unnb_utente,
vac_utente = new_vac_utente,
tem_utente = new_tem_utente,
res_utente = new_res_utente
)
new_utente.save()
return render(request, 'utenti/add-utenti.html', {
'form': UtenteForm(),
'success': True
})
else:
print(form.error)
print(form.errors.as_data())
else:
form = UtenteForm()
return render(request, 'utenti/add-utenti.html', {
'form': UtenteForm()
})
Also if you just do form.save() it'll do all that cleaned_data stuff for you:
# Add new utente
def aggiungi_utente(request):
if request.method == 'POST':
form = UtenteForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'utenti/add-utenti.html', {
'form': UtenteForm(),
'success': True
})
else:
print(form.error)
print(form.errors.as_data())
else:
form = UtenteForm()
return render(request, 'utenti/add-utenti.html', {
'form': UtenteForm()
})
Your view is doing too much work: a Django form can perfectly handle creating an object itself:
from django.shortcuts import redirect
def aggiungi_utente(request):
if request.method == 'POST':
form = UtenteForm(request.POST)
if form.is_valid():
form.save()
return redirect('utenti')
else:
form = UtenteForm()
return render(request, 'utenti/add-utenti.html', {'form': form})
By passing the invalid form to the rendering function again, it will render the problem with the form.
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
in my form i want to select department from 2 options: some object(every time only one) and None.
my form.py
class TeamGoalForm(ModelForm):
def __init__(self, *args, **kwargs):
employees = kwargs.pop('employees')
department = kwargs.pop('department')
super().__init__(*args, **kwargs)
self.fields['employees'].queryset = employees
self.fields['department'].choices = [(1, department), (2, None)]
self.fields['department'].initial = [1]
class Meta:
model = TeamGoal
fields = ('team_goal_title','department','employees', 'team_goal_description', 'gpd_year','team_factor_0','team_factor_1','team_factor_2','team_factor_3','team_factor_weight')
widgets = {
'team_goal_title': forms.TextInput (attrs={'class':'form-control', 'placeholder':'Enter the title of goal'}),
'department': forms.Select (attrs={'class': 'form-control', 'placeholder':'Select department'}), }
in my view.py I have had:
if request.method == 'POST':
form = TeamGoalForm(request.POST, employees=employees, department=department)
if form.is_valid():
form.save()
Here my department is an object.
How to implement something like this, 'cos my solution does't work?
You are not showing much of the code, but here is more or less how the different files should look like, hope this helps:
**#models.py**
from django.db import models
class department(models.Model):
# department fields
pass
class TeamGoal(models.Models):
...
deparment = models.ForeignKey(department, on_delete=models.CASCADE)
...
**#forms.py**
from django.forms import ModelForm
from django import forms
class TeamGoalForm(ModelForm):
class Meta:
model = TeamGoal
fields = (
'team_goal_title',
'department',
'employees',
'team_goal_description',
'gpd_year',
'team_factor_0',
'team_factor_1',
'team_factor_2',
'team_factor_3',
'team_factor_weight'
)
deparments = deparment.objects.all()
widgets = {
'deparments': forms.Select(choices=deparments,
attrs={
'class': 'form-control',
'placeholder':'Select department'
})
**#views.py**
from .forms import TeamGoalForm
def AddTeamGoalForm(request):
context = {
'TeamGoalForm': TeamGoalForm,
}
if request.method == 'POST':
addTeamGoalForm = TeamGoalForm(request.POST)
if addTeamGoalForm.is_valid():
newTeamGoalForm = addTeamGoalForm.save()
return redirect('/')
else:
return render(request, '/TeamGoalForm.html', context)
**# TeamGoalForm.html**
<form method="POST">
{% csrf_token %}
{{ TeamGoalForm}}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
NOTE: you may need to adjust it based on the code you've already writen, but hopefully this leads close to a solution.
I have created a form and a view in Django and I'm trying to display it in the HTML but it isn't loading anything and I don't know why.
alumno2.html
{% block header %}
<header class="masthead bg-white text-dark text-uppercase">
<div class="container">
<h3 class="text-center">Añadir alumno</h3>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-secondary" type="submit">Guardar</button>
</form>
</div>
</header>
{% endblock %}
form.py
class AlumnoForm2(forms.ModelForm):
class Meta:
model = Alumno
#fields = ['dni', 'nombre', 'apellido1', 'apellido2','email','repetidor']
fields = ['dni', 'nombre', 'apellido1', 'apellido2','email','repetidor','curs']
labels = {
'dni': 'dni',
'nombre': 'nombre',
'apellido1': 'Primer Apellido',
'apellido2': 'Segundo Apellido',
'email': 'Email',
'repetidor': 'repetidor',
'curs': 'curs'
}
widgets = {
'dni': forms.TextInput(attrs={'class': 'form-control'}),
'nombre': forms.TextInput(attrs={'class': 'form-control'}),
'apellido1': forms.TextInput(attrs={'class': 'form-control'}),
'apellido2': forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.TextInput(attrs={'class': 'form-control'}),
'repetidor': forms.CheckboxInput(attrs={'class':'form-control-checkbox','id': 'repetidor'}),
'curs':forms.Select(attrs={'class': 'form-control'}),
}
view.py
class crea_alumno(CreateView):
model = Alumno
form_class = AlumnoForm2
template_name = '/alumno2.html'
success_url = reverse_lazy('mostrar_alumnos')
url.py
url(r'^alumno2/$', crea_alumno.as_view(),name='alumno2'),
models.py
class Alumno(models.Model):
dni = models.CharField(max_length=9,primary_key=True)
nombre = models.CharField(max_length=100)
apellido1 = models.CharField('Primer apellido',max_length=50)
apellido2 = models.CharField('Segundo apellido',max_length=50)
email = models.EmailField("Correo electronico",null=True)
repetidor = models.BooleanField()
curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos")
Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel'))
Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica'))
Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso'))
def __str__(self):
return self.dni
the html only display the save button, is not loading the create form. The html is inside the template folders thats why I have this urls.
EDIT:
I have removed the template I had also
url(r'^alumno2/$', TemplateView.as_view(template_name='alumno2.html'),name='alumno2'),
and I'm not sure if i need to put this in the url.py so now I only have the view and is unable to find my template withouth that
Remove the line
url(r'^alumno2/$', TemplateView.as_view(template_name='alumno2.html'),name='alumno2'),
from your urls.py and only keep this one:
url(r'^alumno2/$', crea_alumno.as_view(),name='alumno2'),
And inside your view, remove the / in the template name: instead of
template_name = '/alumno2.html'
Use
template_name = 'alumno2.html'
And replace CreateView with FormView as per the documentation
I have formset and form in one page, both are saved at the same time. But new records for event time are not saved, only old records are updated. Where is the problem?
formset:
class EventTimeForm(forms.ModelForm):
class Meta:
model = EventTime
fields = ['start_time']
widgets = {
'start_time': DateTimeWidget(usel10n=True, bootstrap_version=3)
}
EventTimeFormSet = modelformset_factory(EventTime, form=EventTimeForm, max_num=3, extra=3)
form:
class CreateEventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'description', 'location', 'duaration', 'private']
view:
def create_event(request):
event_form = CreateEventForm(request.POST or None, prefix='event')
event_time_form = EventTimeFormSet(request.POST or None, prefix='eventtime')
context = {
'event_form': event_form,
'event_time_form': event_time_form,
}
if event_form.is_valid() and event_time_form.is_valid():
event = event_form.save()
event_time = event_time_form.save()
for obj in event_time:
obj.event.add(event)
return HttpResponseRedirect('/event-%s' %event.id)
return render(request, 'create_event.html', context)
template:
<form method='POST' action=''>{%csrf_token%}
{{ event_time_form|crispy }}
{{ event_form|crispy}}
<input class="btn btn-primary" type="submit" value="Create" />
</form>