Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
Basically I have this screen and according to the value selected in “metodo_pagamento” I want to display the amount of inline form, example if I select “2 Parcelas”, it shows 2 forms inline, but I wanted to do this dynamically how do I do that too to update and delete?formlike this:
models.py
class Despesas(models.Model):
METODO = (
("1", "1 Parcela"),
("2", "2 Parcelas"),
("3", "3 Parcelas"),
("4", "4 Parcelas"),
)
descricao = models.CharField(max_length=100)
metodo_pagamento = models.CharField(max_length=50, choices=METODO, default="A vista")
def __str__(self):
return self.descricao
class Parcelas(models.Model):
despesa = models.ForeignKey(Despesas, on_delete=models.CASCADE)
data_pagamento = models.DateField(null=True)
valor = models.FloatField(null=True)
def __str__(self):
return str(self.despesa.id)
forms.py
class DespesasForm(forms.ModelForm):
METODO = (
("1", "1 Parcela"),
("2", "2 Parcelas"),
("3", "3 Parcelas"),
("4", "4 Parcelas"),
)
metodo_pagamento = forms.CharField(max_length=50, widget= forms.Select(choices=METODO, attrs = {'onchange': "updateInlineForm();", 'default':""}))
views.py
class CadastrarDespesa(LoginRequiredMixin, GroupRequiredMixin, CreateView):
group_required = u"Admin"
login_url = 'login'
template_name = "formularios/form_cadastro_despesa.html"
def get(self, *args, **kwargs):
form = DespesasForm()
context = {
'form': form,
'titulo':"Cadastrar despesa"
}
return self.render_to_response(context)
form_cadastro_despesa.html
<div class="row">
<div class="col-lg-3">
<div class="container text-center" style="margin-top: 70px; margin-left:650px; text-align:center">
<form method="POST" action="">
{% csrf_token %}
{{form|crispy}}
<div id="inline-form-section">
<!-- Inline form fields will be added here dynamically -->
</div>
<button type="submit" class="btn btn-success" style="margin-top:20px;margin-bottom: 20px;">{{titulo}}</button>
</form>
</div>
</div>
</div>
function updateInlineForm() {
var method = document.getElementById("id_metodo_pagamento").value;
var inlineFormSection = document.getElementById("inline-form-section");
inlineFormSection.innerHTML = ""; // Clear the existing fields
for (var i = 1; i <= method ; i++) {
if (method == 1){
inlineFormSection.innerHTML +=
`
<br>
<label for="parcela1">Data pagamento:</label>
<input class="form-control" type="date" id="parcela1" name="parcela1" required="true">
<br>
<label for="valor1">Status do pagamento</label>
<select class="form-control" id="status" name="status1">
<option value="Pendente">Pendente</option>
<option value="Pago">Pago</option>
</select>
<br>
<label for="parcela1">Valor do pagamento:</label>
<input type="number" class="form-control" id="valorparcela1" value="${total}" name="valorparcela1" required="true" onchange="validacao_parcela(this.id,${valor_parcela});">
`;
} else {
inlineFormSection.innerHTML +=
`
<br>
<label for="parcela${i}">Data ${i}° parcela:</label>
<input class="form-control" type="date" id="parcela${i}" name="parcela${i}" required="true">
<br>
<label for="valor${i}">Status ${i}° parcela</label>
<select class="form-control" id="status" name="status${i}">
<option value="Pendente">Pendente</option>
<option value="Pago">Pago</option>
</select>
<br>
<label for="parcela${i}">Valor da ${i}° parcela:</label>
<input class="form-control" type="number" value="${valor_parcela}" id="valorparcela${i}" name="valorparcela${i}" required="true" onchange="validacao_parcela(this.id,${valor_parcela});">
<br>
`;
}
}
}
In this way that i did in using javascript onchange, but its dificult make update when user select other “Metodo pagamento”, anyone can help me?
To dynamically display the number of inline forms based on the selected value in the "metodo_pagamento" field, you can use JavaScript and update the HTML dynamically based on the selected value
Related
Django form is saved but "result" field is showing empty in database.
Even after populating the filed from admin panel, it is saved but it still shows empty.
Models.py
class Result(models.Model):
class Choises(models.TextChoices):
POSITIVE = "POSITIVE", "Positive"
NEGATIVE = "NEGATIVE", "Negative"
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50, default=None)
result = models.CharField(max_length = 100, choices=Choises.choices, blank=False
)
resultDoc = models.ImageField(upload_to='testResults', height_field=None, width_field=None,)
def __str__(self):
return self.user.username
Forms.py
class resultForm(forms.ModelForm):
class Meta:
model = Result
fields = ['name', 'result', 'resultDoc']
views.py
def inputResult(request, pk):
user = User.objects.filter(id=pk).first()
profile = newProfile.objects.filter(user=user).first()
if profile == None:
profile = oldProfile.objects.filter(user=user).first()
rForm = resultForm(request.POST, request.FILES)
if request.method == 'POST':
rForm = resultForm(request.POST, request.FILES)
if rForm.is_valid():
order = rForm.save(commit=False)
order.user_id = pk
order.save()
return redirect('stored_records')
else:
rForm = resultForm()
context = {'user' : user, 'profile':profile, 'rForm': rForm}
return render(request, 'Testing booth End/input-result-customer-info.html', context)
input-result-customer-info.html
<form action="" method = "POST" enctype= "multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Uploaded By/Doctor Name">
</div>
<div class="mb-3">
<label for="result" class="form-label">Result</label>
<select class="form-select" id="result" name="result" class="form-control">
<option value="POSITIVE">Positive</option>
<option value="NEGATIVE">Negative</option>
</select>
</div>
<div class="mb-3">
<label>Upload Scan File</label>
<div class="upload d-flex justify-content-between">
<div class="file-placeholder">Upload Scan File</div>
<input type="file" class="form-control d-none" id="resultDoc" name="resultDoc" >
<label for="resultDoc" class="form-label cam-img"> <img src="{% static 'user/images/Camera.png' %}"> </label>
</div>
</div>
<button class="btn btn-primary w-50 ms-auto d-block h-100" type="submit">Upload</button>
</form>
enter image description here
I think that the reason this doesnt work is that you created a form (rForm) in the backend but then you don't use it in the frontend.
This is how you should render your form in the the frontend:
<form method="post">
{{ rForm.as_p }} # This is the easiest possible implementation
<button type="submit">Submit</button>
</form>
If you want to take control of how the form is rendered, then you have to make sure that the input fields are named in the way that your backend expects. You can do it entirely manually or semi-manually, but your field names have to be set correctly or nothing will work.
Example of typical approach, say in case you have several similar text inputs
{% for field in rForm %}
<label for="{{ field.auto_id }}">{{ field.name }}</label>
<input type="text" name="{{ field.html_name }}" id="{{ field.auto_id }}" />
{% endfor %}
Example of fully hands-on approach
<select class="form-select" id="{{ rForm.result.auto_id }}" name="{{ rForm.result.html_name }}" class="form-control">
<option value="POSITIVE">Positive</option>
<option value="NEGATIVE">Negative</option>
</select>
In order to make sure that the inputs are being parsed correctly, add a print statement in your view to print the POST request:
print("Post Request : ", request.POST)
From there you will be able to see if the result field is being picked up correctly or if it's being ignored. Usually when fields get ignored is because they are not named correctly or sometimes it's because they fail validation.
If the rest of the data is saved correctly and just result is being left out then it's almost for sure an issue with the field name because if the form failed validation it would have aborted the entire operation.
P.S. I just noticed that you select input has the class attribute declared twice
When I submitting the form in django it is giving error ''TypeError at /user expected string or bytes-like object''.
This is my staff models
class staff(models.Model):
id = models.AutoField
name = models.CharField(max_length=250)
role = models.CharField(max_length=250)
salary = models.CharField(max_length=250)
address = models.CharField(max_length=250)
number = models.CharField(max_length=250)
date = models.DateField()
This is my user views.
def user(request):
if request.method == "POST" :
name = request.POST['name']
role = request.POST['role']
salary = request.POST['salary']
address = request.POST['address']
number = request.POST['number']
date = DateTimeField()
ins = staff(name=name, role=role, salary=salary, address=address, date=date, number=number)
ins.save()
staffs = staff.objects.all()
return render(request, "salary/user.html", {'staff': staffs})
and this is form of template user.html
<form class="forms-sample" action="/user" method="post">
{% csrf_token %}
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="name" id="name" class="form-control" id="exampleInputUsername2" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Role:</label>
<div class="col-sm-9">
<input type="text" name="role" id="role" class="form-control" id="exampleInputUsername2" placeholder="Role">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Salary:</label>
<div class="col-sm-9">
<input type="text" name="salary" id="salary" class="form-control" id="exampleInputUsername2" placeholder="Salary">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Address:</label>
<div class="col-sm-9">
<input type="text" name="address" id="address" class="form-control" id="exampleInputUsername2" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Mobile no.:</label>
<div class="col-sm-9">
<input type="text" name="number" id="number" class="form-control" id="exampleInputUsername2" placeholder="Mobile no.">
</div>
</div>
<button type="submit" class="btn btn-primary mr-2">Submit</button>
<button class="btn btn-dark">Cancel</button>
</form>
I am new in django and i not know what the problem is.
Thanks for helping in advance.
It makes no sense to pass a reference to the AutoField model field in your model, you should construct a field, so:
class staff(models.Model):
id = models.AutoField()
# ⋮
as for the date field, you can work with auto_now_add=True [Django-doc] to automatically fill in the current day:
class staff(models.Model):
# ⋮
date = models.DateField(auto_now_add=True)
then this can be omitted while constructing a staff object:
def user(request):
if request.method == "POST" :
name = request.POST['name']
role = request.POST['role']
salary = request.POST['salary']
address = request.POST['address']
number = request.POST['number']
# no date=… ↓
ins = staff.objects.create(name=name, role=role, salary=salary, address=address, number=number)
ins.save()
staffs = staff.objects.all()
return render(request, "salary/user.html", {'staff': staffs})
It might however be better to work with Django forms to validate, clean and fill in data from a POST request.
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.
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from staff to Staff.
My django cabin form is not submitting. I have applied foreign key and slug in my cabin's model and after that my form stopped getting submitted. whenever I enter all the fields and hit submit button,the form page is getting reloaded and no data is getting submitted.Most Importantly it is not showing any error so that I can fix it.I have tried and searched a lot about it and tried different things but still it didn't work. I am stuck to it. Please help!!
class Centre(models.Model):
name= models.CharField(max_length=50, blank=False, unique=True)
address = models.CharField(max_length =250)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.")
contact = models.CharField(max_length=100, blank=False)
phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list
slug = models.SlugField(unique=False)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Centre, self).save(*args, **kwargs)
class Cabin(models.Model):
random_string = str(random.randint(100000, 999999))
centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE,blank=True,null=True)
code = models.CharField(max_length=6, blank=False, unique=True, default=random_string)
total_seats = models.IntegerField(blank='False')
category=models.CharField(max_length=100, default=False)
booked_date=models.DateField(blank='False')
released_date=models.DateField(blank='False')
price=models.IntegerField(blank=False, default=None)
slug = models.SlugField(unique=False,default=None)
def save(self, *args, **kwargs):
self.slug = slugify(self.category)
super(Cabin, self).save(*args, **kwargs)
In views.py file
class CabinCreateView(CreateView):
fields = '__all__'
model = Cabin
success_url = reverse_lazy("NewApp:logindex")
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.cabin = Cabin.objects.filter(slug=self.kwargs['slug'])[0]
self.object.save()
return HttpResponseRedirect(self.get_success_url())
In my cabin template,
<div class="row">
<div class="col-md-6">
<form method="POST">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="col col-md-12">
<div class="fieldWrapper" >
{{ form.centre_name.errors }}
<div class="form-group col col-md-3">
<label>Centre Name</label>
{{form.centre_name}}
</div>
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%">
<label for="{{form.code.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Code</label>
<input type="text" placeholder="Code" value="{{form.code.value}}" name="code" maxlength="6" id="id_code" style="width:500px; margin-left:200px;">
</div>
</div>
<div class="col col-md-12">
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
<label for="{{form.total_seats.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">seats</label>
<input type="text" placeholder="seats" name="total_seats" id="id_total_seats" style="width:500px; margin-left:200px;">
</div>
<div class="fieldWrapper" >
{{ form.category.errors }}
<div class="form-group col col-md-3" >
<label for="{{form.category.id_for_label}" style="margin-top:-40px">Category</label>
<input type="text" name="category" maxlength="100" id="id_category" placeholder="Category" style="width:500px";>
</div></div></div>
<div class="col col-md-12">
<div class="fieldWrapper" >
{{ form.released_date.errors }}
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
<label for="{{form.released_date.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">released date</label>
<input type="text" placeholder="%yyyy-mm-dd" name="released_date" id="id_released_date" style="width:500px; margin-left:200px;">
</div>
</div>
<div class="fieldWrapper" >
{{ form.booked_date.errors }}
<div class="form-group col col-md-3" >
<label for="{{form.booked_date.id_for_label}" style="margin-top:-40px">booked date</label>
<input type="text" name="booked_date" id="id_booked_date" placeholder="%yyyy-mm-dd" style="width:500px";>
</div>
</div>
</div>
<div class="col col-md-12">
<div class="form-group col col-md-3" >
<label for="{{form.price.id_for_label}" style="margin-top:-40px">price</label>
<input type="text" name="price" maxlength="10" id="id_price" placeholder="in rupees" style="width:500px";>
</div>
</div>
<div class="form-group col col-md-3" >
<input type="submit" onclick="comparedate()" value="Save" class="btn btn-primary" style=" height:30px;width:80px;padding-bottom:2em;"/>
</div></div>
</form>
</div></div></div></div></div></div></div></div></div></div>
It looks like your problem is in your views.py file. You are telling the view that it should build a form including __all__ of the fields on the model, but in your template you don't include the slug field. Since you have overridden the save method on the Cabin model to populate the slug field, I guess you don't want that displayed in the template.
You have two options for fixing this. You could add a hidden field to the template containing the slug field. Or, what I think is a better option, you can change the fields attribute on your view to exclude the slug field.
class CabinCreateView(CreateView):
fields = ('centre_name', 'code', 'total_seats', 'category', 'booked_date', 'released_date', 'price',)
model = Cabin
success_url = reverse_lazy("NewApp:logindex")
P.S. This isn't a problem you are asking about, but I couldn't help noticing that you have what looks like multiple broken variables in your template. You might want to check if your label for="" attributes are working as expected.
I have a booking system in which i enter dates and timeslots available to book.
the form gets the timeslots from the date and converts it to the user timezone time.
i want the client to select a date and an available timeslot before continuing the form but even with required it doesnt work.
i have a model for timeslots and one for event, date+timeslot
then a form to make client select available date+timeslot, with a html to find timeslot available for each day
html
<option value="">{% if time_slots %}Available Slots{% else %}No Slot Available{% endif %}</option>
{% for time_set in time_slots %}
<option value="{{ time_set.pk }}">{{ time_set.start }} - {{ time_set.end }}</option>
{% endfor %}
models
class TimeSlots(models.Model):
start = models.TimeField(null=True, blank=True)
end = models.TimeField(null=True, blank=True)
class Meta:
ordering = ['start']
def __str__(self):
return '%s - %s' % (self.start.strftime("%I:%M %p"), self.end.strftime("%I:%M %p"))
class Event(models.Model):
event_date = models.DateField()
start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True)
available = models.BooleanField(default=True)
class Meta:
verbose_name = u'Event'
verbose_name_plural = u'Event'
def __str__(self):
return str(self.event_date)
def get_absolute_url(self):
url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk])
return u'%s' % (url, str(self.start))
form
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
def __init__(self, *args, **kwargs):
super(PatientForm, self).__init__(*args, **kwargs)
self.fields['start'].queryset = TimeSlots.objects.none()
if 'event_date' in self.data:
try:
event_id = self.data.get('event_date')
# event = Event.objects.get(pk=event_id)
self.fields['start'].queryset = TimeSlots.objects.filter(event__event_date=event_id, event__available=True)
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['start'].queryset = self.instance.timeslot_set
views
class PatientCreate(CreateView):#was CreateView
form_class = PatientForm
template_name = 'appointment/index.html'
def get_context_data(self, **kwargs): # new
context = super(PatientCreate, self).get_context_data(**kwargs)
context['key'] = settings.STRIPE_PUBLISHABLE_KEY
return context
def load_time_slots(request):
event_date = request.GET.get('event_date')
client_timezone = request.GET.get('timezone')
client_timezone = pytz.timezone(client_timezone)
event_date, original_date = get_original_event_date_by_timezone(client_timezone, event_date)
time_slots = TimeSlots.objects.filter(event__event_date= event_date, event__available=True)
final_time_slots = []
for time_slot in time_slots:
start_time = time_slot.start
original_start_date_time = original_date.replace(hour=start_time.hour, minute=start_time.minute,
second=start_time.second,
tzinfo=original_time_zone)
timezone_start_date_time = original_start_date_time.astimezone(client_timezone)
end_time = time_slot.end
original_end_date_time = original_date.replace(hour=end_time.hour, minute=end_time.minute,
second=end_time.second,
tzinfo=original_time_zone)
timezone_end_date_time = original_end_date_time.astimezone(client_timezone)
final_time_slots.append({'pk': time_slot.pk, 'start': timezone_start_date_time.time,
'end': timezone_end_date_time.time})
return render(request, 'appointment/dropdown_list_options.html', {'time_slots': final_time_slots})
def get_original_event_date_by_timezone(client_timezone, event_date):
client_date = datetime.datetime.strptime(event_date, '%Y-%m-%d')
client_date = client_date.replace(tzinfo=client_timezone)
original_date = client_date.astimezone(original_time_zone)
original_date = original_date.replace(hour=0, minute=0, second=0, microsecond=0)
event_date = original_date.strftime('%Y-%m-%d')
return event_date, original_date
def create_event(request, start_time, day_date):
time_slot = TimeSlots.objects.get(start=start_time)
Event.objects.create(event_date=day_date, start=time_slot)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
form page html
<div class="container" style="margin-top:50px;margin-bottom:50px;">
<div class="stepwizard col-md-offset-3">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Date & Time</p>
</div>
<div class="stepwizard-step">
2
<p>Information</p>
</div>
<div class="stepwizard-step">
3
<p>Calling Method</p>
</div>
<div class="stepwizard-step">
4
<p>Payment Method</p>
</div>
</div>
</div>
<form role="form" action="{% url 'charge' %}" method="POST" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' %}">
<div class="row setup-content" id="step-1">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Appointments date and time</h3>
<div class="form-group">
<label class="control-label" for="id_event_date">Event Date:</label>
<input class="form-control" type="date" name="event_date" id="id_event_date" required="required" />
</div>
<div class="form-group">
<label class="control-label" for="id_start">{% trans "Time:"%}</label>
<p><select required="required" class="form-control" name="start" style="display:inline;" id="id_start">
<option value="">---------</option></select></p><input type="hidden" name="timezone">
<script>$("#patientForm input[name='timezone']").val(Intl.DateTimeFormat().resolvedOptions().timeZone);</script>
</select></p>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label for="id_patient_fname" class="control-label">First Name:</label>
<input name="patient_name" id="id_patient_name" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<input required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="id_phone_number" class="control-label">Phone Number:</label>
<input name="phone_number" id="id_phone_number" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Phone Number" />
</div>
<div class="form-group">
<label for="id_emal" class="control-label">Email:</label>
<input name="email" id="id_email" maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Email" />
</div>
<div class="form-group">
<label class="control-label">City</label>
<textarea required="required" class="form-control" placeholder="Enter your address"></textarea>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Choose The Way You Want to Receive The Video Call:</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio" checked>Skype</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio">Whatsapp</label>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-4">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_KPSQTmUOl1DLP2eMc7zlvcnS"
data-description="Buying a 30mn Skype Session" data-amount="3000" data-locale="auto"></script>
</div>
</div>
</div>
</form>
</div>
in the html of the form page, i add required to select but it doesnt work
i need client to select lets say 29/01/2019, then if there is availability choose a timeslote lets say 5.30pm-6.00pm, and then only the next arrow will appear
With CreateView it's a little bit tricky when you want to initialize your ModelForm data. So, instead of doing initialization under your ModelForm, do it under the CreateView class like this example:
Your form:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
Your view:
class PatientCreate(CreateView):
form_class = PatientForm
template_name = 'appointment/index.html'
initial = {}
def get_initial(self):
base_initial = super().get_initial() # it's a simple dict
# initialize your form's data here
# Your logic ...
return base_initial
# The rest of your logic
...
And, in order to know why you need to do this. CreateView inherits from FormMixin which has initial and get_initial() thus will initialize your form's data instead of doing it under your form.
See this links for more details: CreateView MRO and FormMixin
what I am trying to do:
I am trying to get data from Django frontend table, and post it back to frontend.
I am not using modelForm, I thought I don't need save the data to database.
My code:
in views.py:
def panelThree(request):
startDate = ''
endDate = ''
byOtherField = ''
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
startDate = request.POST.get('date')
endDate = request.POST.get('date1')
byOtherField = request.POST.get('date2')
else:
form = QueryForm()
# if not byOtherField:
dataTable = Production.objects.order_by('-id')
return render(request, 'frontend/panelThree.html', {
'form': form, 'dataTable': dataTable, 'startDate':startDate
})
frontend_form:
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-8">
<div class="row">
<div class="col-md-4">
<label >
TextField1
</label>
<input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text"/>
<p> >> Start Date </p>
</div>
<div class="col-md-4">
<label class="control-label " for="date1">
TextField2
</label>
<input class="form-control" id="date1" name="date1" placeholder="MM/DD/YYYY" type="text"/>
<p> >> End Date </p>
</div>
<div class="col-md-4">
<label class="control-label " >
Or
</label>
<label class="control-label " for="date2">
TextField3
</label>
<input class="form-control" id="date2" name="date2" placeholder="MM/DD/YYYY" type="text"/>
<p> >> By Other Field </p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="button-box">
<button class="btn btn-primary " name="submit" type="submit"> Search </button>
</div>
</div>
</div>
</form>
My error:
there is no error, but I just cannot get value from the form post to 'startDate'. It always shows blank value.
I appreciate the help to address this issue, or any ways to work around. Thanks in advance.
2 problems here.
1) The fields in the html are named incorrectly.
<input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text"/>
The name field here should be set to startDate, and so should the id field.
2) You're grabbing data directly from POST.
After verifying the form is_valid, you should get data from it like this:
startDate = form.cleaned_data['startDate']
By removing the "if form.is_valid()" statement, and changing back to request.POST.get method, it's working
def panelThree(request):
startDate = ''
endDate = ''
byOtherField = ''
if request.method == 'POST':
form = QueryForm(request.POST)
startDate = request.POST.get('startDate')
endDate = request.POST.get('endDate')
byOtherField = request.POST.get('byOtherField')
else:
form = QueryForm()
# if not byOtherField:
dataTable = Production.objects.order_by('-id')
return render(request, 'frontend/panelThree.html', {
'form': form, 'dataTable': dataTable, 'startDate':startDate
})