Here I am using Django 3.0 and Python 3.7
In my Django template When using forms my submit is not triggering and no action is not performing
Here is my views.py
def sendmail(request):
company={}
form = JobEmailDataForm()
client = request.user.client
client_id = request.user.client.id
email_data = JobEmailData.objects.filter(client_id=client)
for i in email_data:
reminderstatus = i.reminder_status
bookingstatus = i.booking_today_status
purchasing_officer = i.purchasing_officer
bookedby = request.user
client_data = Client.objects.filter(id=client_id)
for val in client_data:
company['name']=val.name
company['phone']=val.phone
company['email']=val.email
company['replay_to_email']=val.replay_to_email or ''
company['website']=val.website
company['logo'] = val.logo_url
company['address'] = get_client_address(client)
return render(request, 'core/job_email_form_1.html', locals())
Here is my forms.py
class JobEmailDataForm(forms.Form):
name = forms.CharField(max_length=100, label='Company Name', widget=forms.TextInput(attrs={'class':'input-xlarge'}))
address = forms.CharField(max_length=256, label='Company Address', widget=forms.TextInput(attrs={'class':'input-xlarge'}))
phone = forms.CharField(max_length=100, label='Company Phone', widget=Html5TelephoneInput(attrs={'class':'input-xlarge'}))
website = forms.URLField(max_length=100, label='Company Website', required=False, widget=forms.TextInput(attrs={'class':'input-xlarge'}))
email = forms.EmailField(label='Company Email', widget=Html5EmailInput(attrs={'class':'input-xlarge'}))
replay_to_email = forms.EmailField(label='Send from Email (Optional)', required=False, widget=Html5EmailInput(attrs={'class':'input-xlarge'}))
purchasing_officer = forms.EmailField(label='Purchasing Officer Email', required=False, widget=Html5EmailInput(attrs={'class':'input-xlarge'}))
logo = forms.ImageField(label='Image', required=False)
confirmation = forms.CharField(max_length=256, label='Additional Booking Confirmation Message', widget=forms.Textarea)
amendments = forms.CharField(max_length=256, label='Additional Booking Amendments Message', widget=forms.Textarea)
cancellation = forms.CharField(max_length=256, label='Additional Booking Cancellation Message', widget=forms.Textarea)
booking_today = forms.CharField(max_length=256, label='Additional Booking today Message', widget=forms.Textarea)
reminder = forms.CharField(max_length=256, label='Additional Booking Reminders Message', widget=forms.Textarea)
reminder_status = forms.ChoiceField(choices=REMINDER_CHOICES,label='Reminders Message Settings',)
booking_today_status = forms.ChoiceField(choices=REMINDER_CHOICES,label='Booking Today Message Settings',)
class Meta:
widgets = {
"confirmation": forms.TextInput,
}
fields = ['name', 'address', 'phone', 'website','email', 'replay_to_email' , 'logo','confirmation','amendments','cancellation','reminder','is_email_customer','is_email_user','reminder_status']
Here is my job_email.html
<div class="row">
<div class="span6 offset1">
<!-- START non-filtered -->
<form method="post" enctype="multipart/form-data" action="/saveemaildata/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<fieldset class="add">
<br><br>
{% for field in form.visible_fields %}
<div class="control-group">
<label class="control-label pull-left" for="{{ field.auto_id }}">{{ field.label }}</label>
<div class="controls" style="margin-left: 0px;">
{{ field }} {% if field.label == 'Send from Email (Optional)' %}{% if client.email_validated_status == 'processed' or client.email_validated_status == 'Approved by client' %} Processed Check now {% elif client.email_validated_status == 'Validated' %} ValidatedCheck now {% elif client.email_validated_status == 'Pending' %} Validate - Check how {% endif %}{% endif %}
</div>
<p>{{ field.help_text }}</p>
</div>
{% endfor %}
</fieldset>
<div id="form-buttons-container" class="form-actions">
<div class="controls">
<input type="submit" class="btn btn-inverse" value="Update JobEmails">
<a class="btn btn-default" href="{% url "roles_list" %}">Cancel</a>
{% if role %}
<a class="btn btn-danger" href="{% url "roles_delete" role.pk %}">Delete role</a>
{% endif %}
</div> <!--/form-actions-->
</div>
</form>
.....
.....
.....
</div> <!-- /row -->
Here my submit button is not working I couldn't understand where I am wrong
Here is my urls.py
re_path(r'^saveemaildata/$',savejob,name='save_email_data'),
Here is my saveemail view.py
def savejob(request):
messages = []
client = request.user.client
if request.POST:
companyName = request.POST['name']
companyAddress = request.POST['address']
companyPhone = request.POST['phone']
companyWebsite = request.POST['website']
companyEmail = request.POST['email']
replay_to_email = request.POST['replay_to_email']
purchasing_officer = request.POST['purchasing_officer']
Confirmation = request.POST['confirmation']
Amendments = request.POST['amendments']
Cancellation = request.POST['cancellation']
Reminder = request.POST['reminder']
Bookingtoday = request.POST['booking_today']
reminder_status = request.POST['reminder_status']
booking_today_status = request.POST['booking_today_status']
client_id = ClientUser.objects.filter(id=request.user.id)[0].client_id
doc = Client.objects.get(id=client_id)
errors = []
import sys, traceback
if replay_to_email:
if doc.replay_to_email != replay_to_email:
doc.email_validated_status = 'Pending'
send_email_validate.delay(request.user, 1)
doc.name = companyName
doc.replay_to_email = replay_to_email
doc.email = companyEmail
doc.phone = companyPhone
doc.website = companyWebsite
if 'logo' in request.FILES:
doc.logo_url = request.FILES['logo']
print("DOC LOGO URL IS",doc.logo_url)
doc.logo_url.storage = S3Boto3Storage(bucket_name='lightdegree')
print("DOC LOGO URLLL",doc.logo_url.storage)
else:
errors.append("There is no document specified")
doc.save()
template = 'core/savejob.html'
objclient = Client.objects.get(name=companyName,email=companyEmail)
clientid = objclient.id
email_data = JobEmailData.objects.filter(client_id=clientid)
if not email_data:
objemail = JobEmailData(name = companyName,phone=companyPhone,
website=companyWebsite,client_id=clientid,
address=companyAddress,
confirmation=Confirmation,amendments=Amendments,
cancellation=Cancellation,reminder=Reminder,booking_today=Bookingtoday,
purchasing_officer=purchasing_officer,reminder_status=reminder_status,booking_today_status=booking_today_status)
objemail.save()
else:
objemail = JobEmailData.objects.filter(client_id=clientid).update(name = companyName,phone=companyPhone,
website=companyWebsite,
address=companyAddress,
confirmation=Confirmation,amendments=Amendments,
cancellation=Cancellation,reminder=Reminder,booking_today=Bookingtoday,
purchasing_officer=purchasing_officer,reminder_status=reminder_status,booking_today_status=booking_today_status)
messages.append('Job emails successfully updated')
return HttpResponseRedirect('/admin/job_emails/')
How can i make my submit button to work and where i am wrong
Sorry for the late reply. I think you're missing the form tag.
Template of a minimal HTML form (django):
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
Let me know if it worked out! It does for me :)
Related
I am trying to create django commerce app I am little bit stuck on a thing
When I post comment via form I created
<form action="{% url 'comment' list_id.id %}" method="POST">
{% csrf_token %}
<textarea name="comment" class="inp-cmt" rows="3"></textarea>
<input type="submit">
</form>
the comment is posted but it post on all of my list page I wanted only on the page where comment is posted
my comment section
{% if allcomments %}
<h1>Comments</h1>
<div class="card-cmt">
{%for com in allcomments%}
<li style="list-style: none;">
<footer class="post-info">
<span>{{com.user}}</span>
<p>{{com.text}}</p>
</footer>
</li>
{% endfor %}
</div>
{% endif %}
my urls
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("newlist", views.create_listing, name="new_list"),
path("item", views.add_item, name="new_item"),
path("listing/<int:list_id>", views.listing, name="listing"),
path("delete/<int:item_id>", views.delete_list, name="delete"),
path("comment/<int:list_id>", views.comments, name="comment")
]
my views for comment and listing
def comments(request, list_id):
coms = Comments()
if request.method == 'POST':
coms.user = request.user.username
coms.text = request.POST.get('comment')
coms.listid = list_id
coms.save()
return redirect('listing', list_id)
else :
return redirect('index')
def listing(request, list_id):
list_item = Listing.objects.get(id=list_id)
return render(request, "auctions/listing.html",{
"list_id" : list_item,
"allcomments" : Comments.objects.all()
})
models
class Listing(models.Model):
owner = models.CharField(max_length =64,default="N/A")
productname = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.CharField(max_length=999, default="test")
date = models.DateField(auto_now_add=True)
link = models.CharField(max_length=200, default="test1")
def __str__(self):
return f"{self.owner} {self.productname} {self.price} {self.date} {self.description} {self.link}"
class Comments(models.Model):
user = models.CharField(max_length=64)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
listid = models.IntegerField(default=0)
def __str__(self):
return f"{self.user} {self.text} {self.date} {self.listid}"
You're returning all comments on every listing when you do "allcomments" : Comments.objects.all()
The problem is in your listing function. Try this instead:
def listing(request, list_id):
list_item = Listing.objects.get(id=list_id)
return render(request, "auctions/listing.html",{
"list_id" : list_item,
"allcomments" : Comments.objects.filter(listid=list_id)
})
Notice the change - from "allcomments" : Comments.objects.all() to "allcomments" : Comments.objects.filter(listid=list_id)
Also, your implementation for class Comments and class Listing could be a bit better. Have you ever come across something called a ForeignKey? It will be a lot more efficient to use that. https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ForeignKey
So I'm loading my registration form into my html and then using a for loop to iterate over those fields. I am wondering where I can add form control to show a green box around my username field so that a user knows if a username is taken before hitting the submit button. I tried adding it to the form tag and setting a div tag around {{field}} but neither of those work. Furthermore, how can I make it ONLY for Username?
registration.html
{% block content %}
<br>
<h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1>
<form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" >
{% bootstrap_form registration_form%}
{% csrf_token %}
{% for field in bootstrap_form %}
<p>
<div class="form-control is-valid">
{{field.label_tag}}
{{field}}
</div>
{% if field.help_text %}
<small style="color:grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red;">{{error}}"</p>
{% endfor %}
</p>
{% endfor %}
<div class="form-check">
<input type="checkbox" id="accept-terms" class="form-check-input">
<label for="accept-terms" class="form-check-label">Accept Terms & Conditions</label>
</div>
<div>
<br>
<button type="submit">Register</button>
</div>
</form>
{% endblock content %}
reg_form
class RegistrationForm(UserCreationForm):
class Meta:
model = Profile
fields = ("username","email","description","photo","password1","password2")
models.py
class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
class Conversation(models.Model):
members = models.ManyToManyField(settings.AUTH_USER_MODEL)
class UserVote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)
class Meta:
unique_together = (('user', 'voter'))
class InstantMessage(models.Model):
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'receiver',on_delete=models.CASCADE )
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
message = models.TextField()
date = models.DateTimeField(verbose_name="Data creation",default=timezone.now, null=False)
viewed = models.BooleanField(default=False, db_index=True)
def __unicode__(self):
return self.message
#tests to see if messages are exclusive between sender, receiver (won't work with new model)
#classmethod
def find_messages_exclusive_to_profile(cls,sender,receiver):
#members = receiver AND sender, not receiver or sender
exclusive_conversations = Conversation.objects.filter(members= receiver ).filter(members= sender)
exclusive_messages = InstantMessage.objects.filter(conversation__in=exclusive_conversations)
return exclusive_messages
You will need to setup a view which, given a string can check to see if that object exists in the database:
# views.py
from django.contrib.auth.models import User
from django.http import JsonResponse
def check_if_username_exists_view(request, username):
name_taken = User.objects.filter(username=username).exists()
data = {
'name_taken ': name_taken
}
return JsonResponse(data)
Then within your login page you will need some javascript similar to the below:
$("#username").change(function(val){
$.get( {% url 'user_exists_view' %} + val, function( data ) {
alert( "username taken: " data.name_taken );
});
})
I have a list of entries which are displayed in a webpage. Each entry has the same input form. But my problem arises when data is put into the input form, it appears on every single one of them. How do I change this.
Each input form is treated as a single cloned entity distributed over many entries.
views.py
def topic(request, topic_id, type): #
topic = Topic.objects.get(id = topic_id, type = 't_topic')
entries = topic.entry_set.order_by('-date_added')
images = Image.objects.filter(imgtopic__in = entries)
ArticleFormSet = formset_factory(CheckAnswer, extra = 2)
if request.method == 'POST':
formset = ArticleFormSet(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('learning_logs:index'))
else:
formset = ArticleFormSet()
context = {'topic': topic, 'entries': entries, 'images': images, 'formset': formset}
return render(request, 'learning_logs/topic.html', context)
topic.html template
{%load staticfiles %}
{% block content %}
{% for entry in entries(n) %}
<div class = 'secondary-container'>
<li>
<div class = 'date'>
<p >{{ entry.date_added|date:'M d, Y H:i'}}</p>
</div>
{%include 'learning_logs/view_files.html'%}
<div class = 'video-container'>
{%include 'learning_logs/video.html' %}
</div>
<div class = 'entry-text'>
<p>{{ entry.text|linebreaks }}</p>
<p>$ {{entry.price_set.get.ptext}}</p>
</div>
</li>
<li>
<p> Enter Answer: </p>
<form action = "{%url 'learning_logs:topic' topic.id topic.type%}" method = 'post'>
{{formset.management_form}}
<table>
{% for form in formset%}
{{form.as_p}}
{% csrf_token %}
<button name = "submit">Submit answer</button>
{% endfor %}
</table>
</form>
</div>
forms.py
class CheckAnswer(forms.Form):
your_answer = forms.CharField(label = "Enter Your Key", max_length = 100)
def clean(self):
cleaned_data=super(CheckAnswer, self).clean()
your_answer = cleaned_data.get("your_answer")
try:
p = Keys.objects.get(key = your_answer)
except Keys.DoesNotExist:
raise forms.ValidationError("Incorrect code.")
My new problem is that I can't separate the forms into the different lists. Since extra = 2, I get 2 instances of forms on the same entry list.
I tried using the {%for form in formset%} command in the topic.html template to give each entry a form, but I get an of ['ManagementForm data is missing or has been tampered with'] when I click submit.
Image of the problem
This is my template which I am using in the login page but the problem is fields are not showing up .I want to use mdbootstrap on the page.i have searched it on many websites but did't got a solution and every one was using the same thing to use the form is the something I am missing in my code?
<form action="{% url 'log_in' %}" method="POST">
{% csrf_token %}
<div class="md-form">
<i class="fa fa-envelope prefix"></i>
{{ form.username }}
{{ form.username.label_tag }}
</div>
<div style="padding:5px"></div>
<div class="md-form" >
<i class="fa fa-lock prefix"></i>
{{ form.password.label_tag }}
{{ form.password }}
</div>
{% if requset.GET.next %}
<input type="hidden" name="next" value="{{ request.GET.next }}">
{% endif %}
<button type='submit' class="btn info-color ">log in</button>
</form>
and forms.py
from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
password = forms.CharField(label="Password", max_length=30,
widget=forms.PasswordInput(attrs={'class': 'form-control', 'name': 'password'}))
my view function is
def log_in(request):
if request.user.is_authenticated:
return render(request,'registration/userhome.html')
elif request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user.is_active:
login(request, user)
return render(request,"registration/userhome.html")
else :
return HttpResponse("Invalid login details supplied.")
views login_view()
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = LoginForm()
return render(request,"registration/login.html",{'form':form})
I have not even rendered the login page but still they are working and the part of form feilds are missing in it
my urls.py file
from django.urls import path
from . import views
from django.contrib.auth.views import LoginView
urlpatterns =[
path("",views.index,name='index'),
path("userhome/",views.userhome,name='userhome'),
path("quiz/", views.quiz, name='quiz'),
path("signup/", views.sign_up,name='sign_up'),
path("login/", views.login_view, name='login'),
path("login/", views.log_in, name='log_in'),
path("index", views.log_out,name='log_out'),
path("rules/",views.rules,name='rules'),
]
You must have a view like this :
def myView(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = LoginForm()
return render(request, 'myTemplate.html', {'form': form})
I've been able to use a django form and template to insert data to the database. I can also display the data in a very basic HTML page. However, am completely unable to figure out how I go about editing the data. Am assuming that I can at least reuse the django template I used to create a new database entry to also edit the entries thus eliminating the need to create an "edit" template.
Mind you I can edit the entry in console but in the browser I just can't seem to get my head around to how to load the data, which variables carry my primary key when I click on a link of a displayed vehicle and how to pass the fetched data from the database to the form to allow for editing etc. I've checked the admin site for guidance on how it does it on that end but still.... no luck.
Here is my insert code: How do I modify this to allow me to edit the data displayed by the vehicle.html further below?
views.py
vehicle_add - inserts to database
def vehicle_add(request):
if request.method == 'POST':
form = VehicleForm(request.POST)
if form.is_valid():
newvehicle = Vehicle()
vdetails = form.cleaned_data
newvehicle.reg_number= vdetails['regnumber']
newvehicle.model= vdetails['model']
newvehicle.manufacturer= vdetails['manufacturer']
newvehicle.year= vdetails['year']
newvehicle.chassis_number= vdetails['chasisnumber']
Vehicle.save(newvehicle)
return HttpResponseRedirect('/vehicle')
else:
form = VehicleForm()
return render_to_response('vehicle_add.html', {'form': form}, context_instance=RequestContext(request))
The vehicle.html loads the data in a simple HTML format as below:
{% for v in obj %}
<tr><td>{{ v }}</td></tr>
{% endfor %}
The link is displayed like this: http://localhost:8000/vehicle_add/2/
More Info:
vehicle_add.html
{% extends "base.html" %}
{% block title %}Add Vehicle{% endblock %}
{% block page %}Add Vehicle{% endblock %}
{% block content %}
<html>
<head>
<style type="text/css">
ul.errorlist {
margin: 0;
padding: 0;}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;}
</style>
</head>
<body>
<section id = "mainform">
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">{% csrf_token %}
<div class="field">
{{ form.regnumber.errors }}
<label for="id_regnumber">Reg #:</label>
{{ form.regnumber }}</div>
<div class="field">
{{ form.model.errors }}
<label for="id_model">Model:</label>
{{ form.model }}</div>
<div class="field">
{{ form.manufacturer.errors }}
<label for="id_manufacturer">Manufacturer:</label>
{{ form.manufacturer }}</div>
<div class="field">
{{ form.year.errors }}
<label for="id_year">Year:</label>
{{ form.year }}</div>
<div class="field">
{{ form.chasisnumber.errors }}
<label for="id_chasisnumber">Chasis #:</label>
{{ form.chasisnumber }}</div>
<div class="field">
<input type="submit" value="Submit">
<input type="submit" value="Clear">
</div></form></section>
</body>
</html>
{% endblock %}
Trial and Error:
This is what I've tried to do with my view but with no luck:
def vehicle_add(request):
if request.method == 'POST':
form = VehicleForm(request.POST)
if form.is_valid():
newvehicle = Vehicle()
vdetails = form.cleaned_data
newvehicle.reg_number= vdetails['regnumber']
newvehicle.model= vdetails['model']
newvehicle.manufacturer= vdetails['manufacturer']
newvehicle.year= vdetails['year']
newvehicle.chassis_number= vdetails['chasisnumber']
Vehicle.save(newvehicle)
return HttpResponseRedirect('/vehicle')
else:
#WORKING ON THIS
form = VehicleForm
newvehicle = Vehicle.objects.get(pk=9)
form = VehicleForm(newvehicle)
return render_to_response('vehicle_add.html', {'form': form}, context_instance=RequestContext(request))
But on doing so I get different type of errors. Am not even sure if that is how to do it. Can somebody point me in the right direction?
EDIT
Here is the current error:
Caught AttributeError while rendering: 'Vehicle' object has no attribute 'get'
In template d:\dev\workspace\vehicle_request\vehicle_request\mvmanager\templates\vehicle_add.html, error at line 31
It then highligths this part of the template: {{ form.regnumber }}
forms.py
class VehicleForm(forms.Form):
regnumber = forms.CharField(
max_length=7,
label='Reg #:',
widget = forms.TextInput(attrs={'size':7}) )
model = forms.CharField(
label='Model',
widget = forms.TextInput(attrs={'size':25}) )
manufacturer = forms.CharField(
max_length=25,
label='Manufacturer',
widget = forms.TextInput(attrs={'size':25}) )
year = forms.IntegerField(
label='Year',
widget = forms.TextInput(attrs={'size':4}) )
chasisnumber = forms.CharField(
required=False, label='Chasis #',
widget = forms.TextInput(attrs={'size':25}) )
Modify url conf line to use parameters in url,
e.g.:
(r'^vehicle_add/(\d+)/$','app.views.vehicle_add')
In vehicle_add first parameter (second after self parameter) will be vehicle_id taken from url.
You can name it as you wish,
e.g. vehicle_id.
Use it :
newvehicle= Vehicle.objects.get(pk=vehicle_id)
Pass the form a dict:
#WORKING ON THIS
# form = VehicleForm <<< THIS LINE IS UNNECESSARY
newvehicle = Vehicle.objects.get(pk=9)
form = VehicleForm(newvehicle.__dict__)