Django data save model without form in template - python

I want to save a value in the database when the button is clicked without using a form.
I want to save the value in h2 to another model when the button is clicked.
What can i do?
TEMPLATE
<div class="widget-main">
<center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center>
</a>
<input type="submit" onclick="location.href='{% url 'sepete_ekle' %}'" value = "sepete ekle" class="btn btn-sm btn-default pull-right">
Sepete Ekle
</input>
{{urun.fiyat}} TL
</div>
VIEWS
def sepete_ekle(request):
if request.method == 'POST':
urun = request.POST["urun"]
status = 0
urunler = Siparis.objects.create(urun,status)
urunler.save()
messages.success(request, " Sepete Eklendi")
return redirect('/bayi/profil_duzenle')
else:
return HttpResponseRedirect("/")
MODEL
class Siparis(models.Model):
bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"})
urun = models.ForeignKey(Urun, on_delete=models.CASCADE)
adet = models.IntegerField()
tarih = models.DateTimeField()
status = models.BooleanField()
class Meta:
verbose_name = 'Bayi Sipariş'
verbose_name_plural = 'Bayi Siparişleri'

Replace the html posted by you in problem statement with the below one.
<div class="widget-main">
<center>
<h2>{{ urun.urun_adi }}</h2>
</center>
<form method="POST" action="{% url 'sepete_ekle' %}">
<input type="hidden" value="{{ urun.urun_adi }}" name="urun" />
<input
type="submit"
value="sepete ekle"
class="btn btn-sm btn-default pull-right"
/>
</form>
{{urun.fiyat}} TL
</div>
to know more about form hidden fields, here is a simple explaination for reference check this out

Once try this, I hope it works.
Change view.py to this. Add an arguement to your function sepete_ekle.
def sepete_ekle(request,urun):
if request.method == 'POST':
status = 0
urunler = Siparis.objects.create(urun,status)
urunler.save()
messages.success(request, " Sepete Eklendi")
return redirect('/bayi/profil_duzenle')
else:
return HttpResponseRedirect("/")
And urls.py to this:
path('/path/to/function/<urun>',views.sepete_ekle,name='sepete')
And in your html file:
<div class="widget-main">
<center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center>
</a>
<input type="submit" onclick="location.href='{% url 'sepete_ekle' %}'" value = "sepete ekle" class="btn btn-sm btn-default pull-right">
Sepete Ekle
</input>
{{urun.fiyat}} TL
</div>
So, when you click the button the h2 value will be sent in the url and in the view it will be taken from the arguement.

Related

Django form errors are not showing in template

no form errors are showing up in my HTML template when the form is invalid. The form is placed within a carousel incase that's relevant.
I'm calling out individual form elements instead of rendering as {{form.as_p}}, errors where showing when this was the case.
The last item in the carousel is the password and if I leave this blank it will show a pop out that says "please fill in this field" but nothing more than that and only for that one field.
Views.py
def collapsecard(request):
if request.method == 'POST':
create_user_form = CreateUserForm(request.POST)
safezone_form = SafezoneForm(request.POST)
if create_user_form.is_valid() and safezone_form.is_valid():
user = create_user_form.save()
safezone = safezone_form.save(commit=False)
safezone.userid = user
safezone.useremail = user.email
safezone.save()
user = authenticate(username=create_user_form.cleaned_data['username'],
password=create_user_form.cleaned_data['password1'],
)
login(request,user)
api_key = 'XYZ'
api_secret = 'XYZ'
id = 'XYZ'
mailjet = Client(auth=(api_key, api_secret))
data = {
'Email': safezone.useremail,
'Action': "addnoforce"
}
result = mailjet.contactslist_managecontact.create(id=id, data=data)
print
result.status_code
print
result.json()
return redirect('safezoneaddedpage')
return render(request, 'V2maparonno_create_safe_zoneV2.html',
{'create_user_form': create_user_form, 'safezone_form': safezone_form})
else:
create_user_form = CreateUserForm()
safezone_form = SafezoneForm()
print(create_user_form.errors)
print(safezone_form.errors)
return render(request, 'V2maparonno_create_safe_zoneV2.html',
{'create_user_form': create_user_form, 'safezone_form': safezone_form})
Extract from HTML
<form action="" method="POST" class="form-control">
{% csrf_token %}
<div id="carouselExampleIndicators" class="carousel slide" data-interval="false" style="width: 100%">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="4"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="carousel-caption">
<h5>Drag the marker over your home</h5>
<div class="longlatinput">
{{ safezone_form.latitudecentre }}{{ safezone_form.longitudecentre }}
</div>
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="1" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h5>Give your safezone a name</h5>
<div class="form-inputs">
{{ safezone_form.name }}
</div>
<div class="name_space">
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="2" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h5>What email address should we send an alert to?</h5>
<div class="form-inputs">
{{create_user_form.email}}
</div>
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="3" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
<div class="carousel-item">
<img src="https://pupaprojectawsbucket.s3.eu-west-2.amazonaws.com/Screenshot+2021-05-04+at+20.36.09.png" alt="..." style="width: 100%; height: 200px;">
<div class="carousel-caption">
<h5>Create your username</h5>
<div class="form-inputs">
{{create_user_form.username}}
</div>
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="4" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h5>Finally, set a password</h5>
<div class="form-inputs">
{{create_user_form.password1}}
</div>
<input class="btn btn-success" type="submit" name="Submit" id="reset-btn">
<div class="disclaimer"><p>By clicking submit you agree to receiving email alerts.</p></div>
</div>
</div>
</div>
</div>
</form>
**<div class = card>
Errors
{{safezone_form.errors.name}}
{{create_user_form.errors.email}}
{{create_user_form.errors.username}}
{{create_user_form.errors.password1}}
</div>**
Forms.py
password2 = None
email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "michael#gmail.com"}))
username = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "JohnSmith078"}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={"placeholder": "8+ characters"}))
class Meta:
model = User
fields = ['username', 'email', 'password1']
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
self.add_error('password1', error)
return password1
class SafezoneForm(forms.ModelForm, admin.ModelAdmin):
name = forms.CharField(label='Safezone name',widget=forms.TextInput
(attrs={'id': 'name', 'label': 'Name of Safezone', 'class': 'form-inputs',"placeholder": "Mum's house"}))
latitudecentre = forms.FloatField(label='Safezone Latitude',widget=forms.TextInput
(attrs={'id': 'latitudecentre','class': 'form-inputs',"placeholder": "Latitude"}))
longitudecentre = forms.FloatField(label='Safezone Longitude',widget=forms.TextInput
(attrs={'id': 'longitudecentre','class': 'form-inputs',"placeholder": "Longitude"}))
class Meta:
model = Safezone
fields = ['name', 'longitudecentre', 'latitudecentre']
Your errors don't show because you're redirecting to another page if your forms are not valid.
if create_user_form.is_valid() and safezone_form.is_valid():
...
return redirect('safezoneaddedpage')
return redirect('safezoneaddedpage') # detelete this, here you must not redirect to another page, but render the same template.
and add this:
return render(request, 'V2maparonno_create_safe_zoneV2.html',
{'create_user_form': create_user_form, 'safezone_form': safezone_form})

How to make time slots(for a particular date and time) not appear after a person has booked it in Django?

I am creating a website in which there is a form where you can book appointments(for doctors)..The issue I am facing is that, if a particular timeslot(for the particular date and time) has been selected it should not appear anymore on the form, but I have no clue on how to do it
The form looks like this(This is returned from the index function in views.py)
<section id="appointment" data-stellar-background-ratio="3">
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt="">
</div>
<div class="col-md-6 col-sm-6">
<!-- CONTACT FORM HERE -->
<form id="appointment-form" role="form" method="post" action="{% url 'test' %}">
{% csrf_token %}
<!-- SECTION TITLE -->
<div class="section-title wow fadeInUp" data-wow-delay="0.4s">
<h2>Make an appointment</h2>
</div>
<div class="wow fadeInUp" data-wow-delay="0.8s">
<div class="col-md-6 col-sm-6">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name">
</div>
<div class="col-md-6 col-sm-6">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email">
</div>
<div class="col-md-6 col-sm-6">
<label for="date">Select Date</label>
<input type="date" name="date" value="" class="form-control">
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Select Department</label>
<select class="form-control" name="drop">
{% for entry in items %}
<option>{{ entry.category }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Select Time</label>
<select class="form-control" name="drop1">
{% for entry in times %}
<option>{{ entry.time }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-12 col-sm-12">
<label for="telephone">Phone Number</label>
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Phone">
<label for="Message">Additional Message</label>
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Message"></textarea>
<button type="submit" class="form-control" id="cf-submit" name="submit">Submit Button</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
The views.py, the test function saves the form(into database) and sends the email:
from django.shortcuts import render, get_object_or_404
from django.core.mail import send_mail
from .models import Form, categories, Doctors, News, timeslot
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import authenticate
def index(request):
time = timeslot.objects.all()
item = categories.objects.all() # use filter() when you have sth to filter ;)
if request.method == 'POST':
selected_item = get_object_or_404(Item, pk=request.POST.get('item_id'))
selected_item2 = get_object_or_404(time, pk=request.POST.get('time_id'))
# get the user you want (connect for example) in the var "user"
categories.item = selected_item
categories.save()
timeslot.time = selected_item2
timeslot.save()
# Then, do a redirect for example
return render(request, 'website/index.html', {'items':item, 'times':time })
def test(request):
if request.method == "POST":
name=request.POST['name']
email=request.POST['email']
date=request.POST['date']
drop=request.POST.get('drop', False)
time=request.POST.get('drop1', False)
phone=request.POST['phone']
message1=request.POST['message']
message = "Name: "+ name + "\n" + "email: "+ email + "\n" + "Date of appointment: " + date + "\n" + "Time: " + time + "\n" "Service: " + drop + "\n" + "Number: " + phone + "\n" + "Special Message: "+ message1
#send an email
send_mail(
'Make appointment for ' + name, #subject
message, #the msg
email, #from email
['madhavm2002#gmail.com'] #to email
)
#this is used to get the class from the models and then uses the variables assigned here to give value to the variables in models
form=Form(name = name, email = email, date = date, time= time, drop = drop, phone = phone, msg1= message1)
#this used the save method to save the object into the database
form.save()
return render(request, 'website/test.html', {'name':name})
else:
return render(request, 'website/index.html')
The models.py:
from django.db import models
class Form(models.Model):
msg_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=80)
email = models.CharField(max_length=80)
date = models.DateField()
drop = models.CharField(max_length=80)
time = models.TimeField()
phone = models.CharField(max_length=80)
msg1 = models.CharField(max_length=500)
status = models.IntegerField(default = 0)
class categories(models.Model):
category = models.CharField(max_length=80)
class timeslot(models.Model):
time = models.TimeField(max_length=80)
PS: the timeslots looke like 9am,10am,11am...1pm,2pm etc.
The categories give objects like "dental","physio" etc
Do tell how to solve this issue thanks
Essentially you'll need to have something to indicate available timeslots, then with a query joined to your appointments you'd have a condition in your template that that checks if the timeslot already has an appointment (or not) and act accordingly. This is a fairly broad question - see Brian's note.

Django Forms posting not working - Django simply renders the page again

Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working.
See my code below:
models.py
from django.db import models
from accounts.models import User
from datetime import datetime, date
#// ------------ FUNCTIONS -------------//
# Generate Organisation IDs for each organisation
def org_id_generate():
last_org = Organization.objects.all().order_by('org_id').last()
if not last_org:
return 'ORG_001'
else:
last_org_id = last_org.org_id
number_in_id = int(last_org_id[4:7])
new_number_in_id = number_in_id + 1
new_org_id = 'ORG_' + str(new_number_in_id).zfill(3)
return new_org_id
#// ------------ MODELS -------------//
class Organization(models.Model):
org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False)
organization_code = models.CharField(max_length=20)
company_name = models.CharField(verbose_name="Company Name", max_length=60)
legal_name = models.CharField(verbose_name="Legal Name", max_length=100)
industry_distribution = models.BooleanField(verbose_name="Distribution", default=False)
industry_education = models.BooleanField(verbose_name="Education", default=False)
industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False)
industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False)
industry_retail = models.BooleanField(verbose_name="Retail", default=False)
industry_services = models.BooleanField(verbose_name="Services", default=False)
business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True)
vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True)
created_date = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By")
effective_start_date = models.DateField(auto_now_add=False)
effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True)
update_date = models.DateTimeField(default=datetime.now)
last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By")
def __str__(self):
return self.company_name
forms.py
from django import forms
from organizations.models import Organization
class OrganizationAddForm(forms.ModelForm):
class Meta:
model = Organization
exclude = ['created_date', 'update_date', ]
views.py
from django.shortcuts import get_object_or_404, render, redirect
from organizations.models import Organization
from forms import OrganizationAddForm
from accounts.models import User
from django.contrib.auth.decorators import login_required
#login_required()
def settings(request):
return render(request, 'settings/settings.html')
#login_required()
def organizations_settings(request):
orgs = Organization.objects.all()
context = {
'orgs': orgs,
}
return render(request, 'settings/settings_organizations.html', context)
#login_required
def organization_add(request):
if request.method == 'POST':
user_email = request.user.email
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['brn']
form.vat_registration_no = form.cleaned_data['vat']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = forms.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
form.created_by = form.cleaned_data[user_email]
form.last_updated_by = form.cleaned_data[user_email]
form.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.settings, name="settings"),
path('organizations/', views.organizations_settings, name='organizations_settings'),
path('organization_create', views.organization_create, name="organization_create"),
path('organizations/add/', views.organization_add, name="organization_add"),
]
Page Source Code
<!-- Add Organization Form -->
<div class="container form-style">
<i class="fas fa-arrow-left"></i> Back
<div class="form-header">
<h3>Add Organization</h3>
</div>
<form action="{% url 'organization_add' %}" method="POST">
{% csrf_token %}
<div class="container">
<!-- Row 1 -->
<div class="row">
<div class="col-md-4">
<label for="organization_code">Organization Code<span class="star-red">*</span></label>
<input type="text" name="organization_code" class="form-control" required>
</div>
<div class="col-md-4">
<label for="company_name">Organization Name<span class="star-red">*</span></label>
<input type="text" name="company_name" class="form-control" required>
</div>
<div class="col-md-4">
<label for="legal_name">Legal Name<span class="star-red">*</span></label>
<input type="text" name="legal_name" class="form-control" required>
</div>
</div>
<!-- Row 2 -->
<div class="row mt-4">
<!-- <div class="col-md-4">
<label for="industry">Industry<span class="star-red">*</span></label>
<select name="industry" class="selectpicker">
<option value="distribution">Distribution</option>
<option value="education">Education</option>
<option value="healthcare">Healthcare</option>
<option value="manufacturing">Manufacturing</option>
<option value="retail">Retail</option>
<option value="services">Services</option>
</select>
</div> -->
<div class="col-md-6">
<label for="brn">Business Registration No.</label>
<input type="text" name="brn" class="form-control">
</div>
<div class="col-md-6">
<label for="vat">VAT Registration No.</label>
<input type="text" name="vat" class="form-control">
</div>
</div>
<!-- Row 3 -->
<h5 class="mt-4">Industry</h5>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_distribution" class="form-check-input">
<label for="industry_distribution" class="form-check-label">Distribution</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_education" class="form-check-input">
<label for="industry_education" class="form-check-label">Education</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_healthcare" class="form-check-input">
<label for="industry_healthcare" class="form-check-label">Healthcare</label>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_manufacturing" class="form-check-input">
<label for="industry_manufacturing" class="form-check-label">Manufacturing</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_retail" class="form-check-input">
<label for="industry_retail" class="form-check-label">Retail</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_services" class="form-check-input">
<label for="industry_services" class="form-check-label">Services</label>
</div>
</div>
</div>
<!-- Row 4 -->
<div class="row mt-4">
<div class="col-md-6">
<label for="effective_start_date">Effective Start Date<span class="star-red">*</span></label>
<input type="date" name="effective_start_date" class="form-control" required>
</div>
<div class="col-md-6">
<label for="effective_end_date">Effective End Date:</label>
<input type="date" name="effective_end_date" class="form-control">
</div>
</div>
<!-- Hidden Input - User -->
<input type="hidden" name="user_email" />
<div class="float-right mt-3">
<button type="submit" class="btn btn-custom save">Save and Close</button>
</div>
</div>
</form>
</div>
Any help would be greatly appreciated. If you need any additional info, let me know and I will edit the post.
I did not find any code to show the errors in html.
According to the function in views, if the form is not valid, then it renders the page with the form.
Try to add {{form.errors}} to you the html file to see if it has errors?
I managed to solve it.
views.py
#login_required
def organization_add(request):
if request.method == 'POST':
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['business_registration_no']
form.vat_registration_no = form.cleaned_data['vat_registration_no']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = form.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
org.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
The issue was that it was not able to capture the user email for the Created By and Last Updated By fields.
This is resolved by using:
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
Note that the following two posts helped me:
Using request.user with Django ModelForm
Cannot assign "42": "Event.user_id" must be a "User" instance

Trying to pass url in form action

I'm new in django and i'm stuck now.
I'm trying to pass the url in form [action] attribute that would go to my edit function defined in [views.py] file and do it's job but whenever I try to pass the url [NoReverseMatch] is shown.
This is what i tried to do:
<div class="modal fade" id="editform" role="dialog">
<div class="modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<b>Edit Information</b>
</h3>
</div>
<div class = "modal-body">
<form action="{% url 'studentapp:editrow' rowid=id %}" id="editform" method="POST">
{% csrf_token %}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ student_detail.name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ student_detail.course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ student_detail.roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<input id="new_address" type = "text" name="address" class = 'form-control' value="{{ student_detail.address }}" placeholder="Enter your address"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
In my urls.py I've used the following url:
url(r'^editrow/(?P<rowid>[0-9]+)/$', views.editrow, name='editrow'),
My [editrow] view looks something like this:
def editrow(request, rowid):
item = get_object_or_404(Studentapp, rowid=id)
print item
if request.method=="POST":
form = EntryForm(request.POST, instance=item)
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('studentapp:index'),rowid.id)
else:
form=EntryForm(instance=item)
return render(request, 'index.html',{'form':form})
else:
form=EntryForm(instance=item)
return render(request, 'index.html',{'form':form})
View that render's the template:
def index(request):
context = {}
latest_student = Studentapp.objects.order_by('pub_date')
context.update({
'latest_student': latest_student
})
response = {"status": False, "errors": []}
if request.is_ajax():
id = request.POST['id']
response = {}
response['status'] = False
student_detail = Studentapp.objects.filter(id=id).first()
context = {
"student_detail": student_detail
}
template = render_to_string("studentapp/_edit_student.html", context)
response['template'] = template
response['status'] = True
return HttpResponse(json.dumps(response), content_type="applicaton/json")
return render(request, "studentapp/index.html", context)
What i'm doing in crud is:
1) make an [edit] button in table through for loop.
2) when i click [edit] button a pre-populated form shows up(which i'm getting).
3) After i click the pre-populated form i want to edit that form and save it and updated data is reflected in my django db.
Thanks to #Alasdair, I looked in my code what he was trying to tell me and i got the answer.
The url that i was trying to pass through my action attribute was wrong. Here's what i did.
<form action="{% url 'studentapp:editrow' rowid=student_detail.id %}" id="editform" method="POST">
Through "student_detail" i'm able to get pre-populated form as i mentioned above. i used the same to get the id and pass it to my "editrow" view.
It's working for me now.
It seems like you never add id to your context in your view index. So the template does not have that variable available.
You need to add that id to your context.
Just like #Alasdair pointed out in the comments.

Implement search in django

I have this html search form and I want to link it to my search view to make it work.
<form class="navbar-form navbar-left" role="search" >
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" action = "/search/">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the views.
def searchResults(request, drname):
# drname = request.GET.get('drname')
doctors = Doctor.objects.filter(name__contains=drname)
clinic = Doctor.objects.filter(clinic__name__contains=drname)
d = getVariables(request)
d['doctors'] = doctors
d['doctors_by_clinic'] = doctors
return render_to_response('meddy1/doclistings.html',d)
urls.py
url(r'^search/(?P<drname>\w+)/$', views.searchResults, name='searchResults'),
Html. <form> must have action attribute, not <input>. Also, send search string as get parameter, don't include it in url (add name attribute to <input>):
<form class="navbar-form navbar-left" role="search" action="/search/">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="drname">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
urls.py. Drop this part (?P<drname>\w+)/:
url(r'^search/$', views.searchResults, name='searchResults'),
views.py. Get search string from GET parameter:
def searchResults(request):
drname = request.GET.get('drname')
doctors = Doctor.objects.filter(name__contains=drname)
clinic = Doctor.objects.filter(clinic__name__contains=drname)
d = getVariables(request)
d['doctors'] = doctors
d['doctors_by_clinic'] = doctors
return render_to_response('meddy1/doclistings.html',d)
action goes in the form element, not the input.

Categories