I'm trying to update the user profile using the model form by passing the already stored user details with the initial keyword. I don't know what is wrong in my code. When i click the submit button it just reloading the same page instead of updating/saving the details. Please i need some help to fix this issue.
## views.py ##
def personal_details_update(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
else:
user = request.user
data = {
'username': user.username,
'email': user.email,
'first_name': user.first_name,
'last_name': user.last_name,
'address': user.address,
'city': user.city,
'state': user.state,
'country': user.country,
'mobile': user.mobile,
}
form = PersonalDetailsForm(request.POST or None, initial=data)
if request.method == 'POST':
if form.is_valid():
user.username = request.POST['username']
user.email = request.POST['email']
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.address = request.POST['address']
user.city = request.POST['city']
user.state = request.POST['state']
user.country = request.POST['country']
user.mobile = request.POST['mobile']
user.save()
return HttpResponseRedirect('/personal_details/')
# return HttpResponseRedirect('%s' % (reverse('personal_details')))
context = {
'form': form,
}
return render(request, 'login/personal_details_update.html', context)
def personal_details(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
else:
return render(request, 'login/personal_details.html')
## urls.py ##
from django.conf.urls import url
from . import views
app_name = 'login'
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about us/$', views.about_us, name='about_us'),
url(r'^services/$', views.services, name='services'),
url(r'^registration/$', views.registration, name='registration'),
url(r'^login/$', views.login_user, name='login'),
url(r'^admin/$', views.admin_login, name='admin_login'),
url(r'^logout/$', views.logout_user, name='logout'),
url(r'^personal_details/$', views.personal_details, name='personal_details'),
url(r'^personal_details/update/$', views.personal_details_update, name='personal_details_update'),
]
## forms.py ##
from django import forms
from .models import User
from django.contrib.admin.widgets import AdminDateWidget
class UserForm(forms.ModelForm):
date_of_birth = forms.DateField(widget=AdminDateWidget)
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'date_of_birth', 'address', 'city', 'state',
'country', 'mobile', 'avatar', 'password', 'confirm_password']
class PersonalDetailsForm(forms.ModelForm):
date_of_birth = forms.DateField(widget=AdminDateWidget)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'address', 'city', 'state',
'country', 'mobile']
exclude = ['date_of_birth', 'avatar', 'password', 'confirm_password']
## personal_details.html ##
{% extends 'upload/base.html' %}
{% block title %}Cloud | Personal Details{% endblock %}
{% block folders_active %}active{% endblock %}
{% load staticfiles %}
{% block navigation%}
<div class="container-fluid files-container">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="panel panel-default" style="background: transparent">
<div class="panel-body">
<div class="page-header">
{% if msg %}
<p><strong><font color="#dc143c">{{ msg }}</font></strong></p>
{% endif %}
</div>
<div class="row">
<h4>Personal Details <span class="glyphicon glyphicon-edit"></span></h4><br>
</div>
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="id_username">
Username:
</label>
{{ user.username }}
</div>
<div class="form-group">
<label class="control-label" for="id_email">
Email:
</label>
{{ user.email }}
</div>
<div class="form-group">
<label class="control-label" for="id_first_name">
First Name:
</label>
{{ user.first_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_last_name">
Last Name:
</label>
{{ user.last_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_date_of_birth">
Date Of Birth:
</label>
{{ user.date_of_birth }}
</div>
<div class="form-group">
<label class="control-label" for="id_address">
Address:
</label>
{{ user.address }}
</div>
<div class="form-group">
<label class="control-label" for="id_city">
City:
</label>
{{ user.city }}
</div>
<div class="form-group">
<label class="control-label" for="id_state">
State:
</label>
{{ user.state }}
</div>
<div class="form-group">
<label class="control-label" for="id_country">
Country:
</label>
{{ user.country }}
</div>
<div class="form-group">
<label class="control-label" for="id_mobile">
Mobile:
</label>
{{ user.mobile }}
</div>
<div class="form-group">
<label class="control-label" for="id_avatar">
Avatar:
</label>
{{ user.avatar }}
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
## personal_details_update.html ##
{% extends 'upload/base.html' %}
{% block title %}Cloud | Personal Details Update{% endblock %}
{% block folders_active %}active{% endblock %}
{% load staticfiles %}
{% block navigation%}
<div class="container-fluid files-container">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="panel panel-default" style="background: transparent">
<div class="panel-body">
<div class="page-header">
{% if msg %}
<p><strong><font color="#dc143c">{{ msg }}</font></strong></p>
{% endif %}
</div>
<div class="row">
<h4>Personal Details Update Form</h4><br>
</div>
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label" for="id_username">
Username:
</label>
{{ form.username }}
</div>
<div class="form-group">
<label class="control-label" for="id_email">
Email:
</label>
{{ form.email }}
</div>
<div class="form-group">
<label class="control-label" for="id_first_name">
First Name:
</label>
{{ form.first_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_last_name">
Last Name:
</label>
{{ form.last_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_address">
Address:
</label>
{{ form.address }}
</div>
<div class="form-group">
<label class="control-label" for="id_city">
City:
</label>
{{ form.city }}
</div>
<div class="form-group">
<label class="control-label" for="id_state">
State:
</label>
{{ form.state }}
</div>
<div class="form-group">
<label class="control-label" for="id_country">
Country:
</label>
{{ form.country }}
</div>
<div class="form-group">
<label class="control-label" for="id_mobile">
Mobile:
</label>
{{ form.mobile }}
</div>
<div class="form-group">
<div class="col-sm-offset-5">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
This is the error message i'm getting when i try to update my personal_details form. Please someone help me fix it
I think error is, where you assign the "user" variable.
user = request.user
Instead of this you need to do this ,
user = User.objects.get(username=request.user.username)
In the case of latter, you are referring to the user object, on which you can update or change the data.
While in the former case, django is trying to create a new user which already exists in the database.That's why it gives the error you got. You just have to grab the one from the database and do manipulation on it.
I'm too a novice in django, hope you got what you where looking for.
Related
Trying to change password using PasswordChangeView, but cannot get it working.
urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('profiles/settings/', update_profile, name='update_profile'),
path('profiles/settings/', auth_views.PasswordChangeView.as_view(template_name='accounts/settings.html'),
name='password_change'),
]
And i am trying to get the input fields correct in my html
<div class="tab-pane fade" role="tabpanel" id="password">
<form id="id_password_change_form" method="POST" class="form-signin">{% csrf_token %}
<div class="form-group row align-items-center">
<label class="col-3">Current Password</label>
<div class="col">
<input
type="password"
placeholder="Enter your current password"
name="old_password"
class="form-control"
id="id_old_password"
required="true" />
</div>
</div>
<div class="form-group row align-items-center">
<label class="col-3">New Password</label>
<div class="col">
<input
type="password"
placeholder="Enter a new password"
name="new_password1"
class="form-control"
id="id_new_password1"
required="true" />
<small>Password must be at least 8 characters long</small>
</div>
</div>
<div class="form-group row align-items-center">
<label class="col-3">Confirm Password</label>
<div class="col">
<input
type="password"
placeholder="Confirm your new password"
name="new_password2"
class="form-control"
id="id_new_password2"
required="true" />
</div>
</div>
{% for field in form %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% endfor %}
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary">Change Password</button>
</div>
</form>
There is no error, and it do not update the password as supposed to. according to PasswordChangeView, I should not need to alter anything.
I think you have a problem because of the wrong URLs definition, take a look at you urls.py:
from django.contrib.auth import views as auth_views
urlpatterns = [
path('profiles/settings/', update_profile, name='update_profile'),
path('profiles/settings/', auth_views.PasswordChangeView.as_view(template_name='accounts/settings.html'),
name='password_change'),
]
You always hit update_profile view instead of PasswordChangeView. I think this is typo.
Using django for rendering user uploaded data from a "/blogs/createblog" form web page to "/blogs" webpage, but the image file uploaded by the user is not getting displayed in his/her blogpost ("/blogs") page. My settings.py, base level/urls.py, app/models.py, app/views.py and the html templates are something like this:
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
baseproject/urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.urls import re_path
from django.views.static import serve
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('home.urls')),
path('blogs/',include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
app/models.py
from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User
# Create your models here.
class BlogPost(models.Model):
blog_id=models.AutoField(primary_key=True)
author=models.CharField(max_length=200)
title=models.CharField(max_length=300)
pub_date=models.DateField()
category=models.CharField(max_length=200,default="Promotional Blogs")
heading1=models.CharField(max_length=300,blank=True)
content1=models.TextField(blank=True)
heading2=models.CharField(max_length=300)
content2=models.TextField()
about=models.TextField()
likes=models.ManyToManyField(User, related_name="blogpost_like")
image=models.ImageField(upload_to="blog/images")
def number_of_likes(self):
return self.likes.count()
def __str__(self):
return self.title + " by " + self.author
app/views.py
def createblog(request):
if request.method=="POST":
author=request.POST.get("author")
title=request.POST.get("title")
today=date.today()
category=request.POST.get("category")
heading=request.POST.get("heading")
body=request.POST.get("body")
about=request.POST.get("about")
pic=request.POST.get("pic")
new_post=BlogPost(author=author,title=title,pub_date=today,category=category,heading2=heading,content2=body,about=about,image=pic)
new_post.save()
messages.success(request,"Your blog is published successfully.")
return redirect("/blogs")
return render(request,"blog/editor.html")
app/editor.html
{% extends 'blog/basic.html' %}
{% block title %}Editor - BlogLikho{% endblock %}
{% block body %}
<div class="container my-4">
<h1 class="mb-4" style="text-align:center;">Blog Editor</h1>
<form method="POST" action="/blogs/createblog">{% csrf_token %}
<div class="row">
<div class="mb-3 col-md-6">
<label for="author" class="form-label" style="font-weight: bold;">Author</label>
<input type="text" class="form-control" id="author" name="author" placeholder="" required>
</div>
<div class="mb-3 col-md-6">
<label for="title" class="form-label" style="font-weight: bold;">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Blog title" required>
</div>
</div>
<div class="mb-3">
<label for="category" class="form-label" style="font-weight: bold;">Category</label>
<select class="form-select" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="Coding Blogs">Coding Blogs</option>
<option value="Sports Blogs">Sports Blogs</option>
<option value="Traveling Blogs">Traveling Blogs</option>
<option value="Educational Blogs">Educational Blogs</option>
<option value="Business Blogs">Business Blogs</option>
<option value="Marketing Blogs">Marketing Blogs</option>
<option value="Technology Blogs">Technology Blogs</option>
<option value="Sales Blogs">Sales Blogs</option>
</select>
<input type="hidden" name="category" value="Coding Blogs">
</div>
<div class="mb-3">
<label for="heading" class="form-label" style="font-weight: bold;">Heading</label>
<input type="text" class="form-control" id="heading" name="heading" placeholder="" required>
</div>
<div class="mb-3">
<label for="body" class="form-label" style="font-weight: bold;">Body</label>
<textarea class="form-control" id="body" name="body" rows="4" required></textarea>
</div>
<div class="mb-3">
<label for="about" class="form-label" style="font-weight: bold;">About you</label>
<textarea class="form-control" id="about" rows="3" name="about" placeholder="Write a bit about yourself" required></textarea>
</div>
<div class="mb-3">
<label for="pic" class="form-label" style="font-weight: bold;">Blog display image</label>
<input class="form-control" type="file" id="pic" name="pic">
</div>
<button type="submit" class="publish btn btn-success">Publish</button>
</form>
</div>
{% endblock %}
app/yourblogs.html
{% extends "blog/basic.html" %}
{% block activeblogs %}active{% endblock %}
{% block title %}Blogs - BlogLikho{% endblock %}
{% load static %}
{% block body %}
<div class="container my-4">
<div class="row mb-2">
{% for blog_item in myblogs %}
<div class="col-md-6">
<div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-success">{{blog_item.author}}</strong>
<h4 class="mb-0">{{blog_item.title | truncatechars:25 }}</h4>
<div class="mb-1 text-muted">{{blog_item.pub_date}}</div>
<p class="card-text mb-auto" style="margin-bottom: revert!important;">{{blog_item.content1 | truncatewords:10}}</p>
<button type="button" class="btn btn-primary" style="width: fit-content;">Continue reading</button>
</div>
<div class="col-auto d-none d-lg-block">
<img src="/media/{{blog_item.image}}" class="bd-placeholder-img" width="250" height="250" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
What might be the problem?? The error which i am getting by clicking on the image url inside the specific BlogPost ImageField is..
404:Page not found
Please suggest me the solution.
I've a strange bug with my forms.
In a page I must hande 2 separate forms,
the 1st one have no problem at all and I can add the record in DB ,
the 2nd one raise me an error asking to fill a required data of 1st form.
The POST dictionary looks ok
Here the log:
<QueryDict: {'csrfmiddlewaretoken': ['lvt5Ph2SA1xxFK4LMotdHOWk2JuZzYDo0OKWc77rKICYKYmemy3gl0dBphnRNcFb'], 'pk_atto': ['1.1'], 'pk_persona': ['1'], 'capacita': ['11'], 'Aggiungi_persona': ['persona'], 'tipo': ['fondo']}>
<ul class="errorlist"><li>pk_particella<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
the views:
if request.method == 'POST':
if("Aggiungi_particella" in request.POST):
save_atto = AttiPartenzeParticelleForm(request.POST)
else:
save_atto = AttiPartenzePersoneForm(request.POST)
print(request.POST)
print(save_atto.errors)
if save_atto.is_valid():
save_atto.save()
return redirect('/aggiungi_atto_partenza' + '/' + str(save_atto['pk_atto'].value()))
the forms:
class AttiPartenzeParticelleForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_particella = forms.ModelChoiceField(queryset=Particelle.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
class AttiPartenzePersoneForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_persona = forms.ModelChoiceField(queryset=Persone.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
and the HTML
<div id="particella" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="particella_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ form.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ form.pk_particella|as_crispy_field }}
</div>
<div class="col-2">
{{ form.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button form="particella_f" class="btn btn-outline-primary btn-lg mt-5" type="submit" name="Aggiungi_particella" value="particella">
AGGIUNGI PARTICELLA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
<div id="persona" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="persona_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ persona.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ persona.pk_persona|as_crispy_field }}
</div>
<div class="col-2">
{{ persona.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button class="btn btn-outline-primary btn-lg mt-5" form="persona_f" type="submit" name="Aggiungi_persona" value="persona">
AGGIUNGI PERSONA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
soneone have any idea?
thx
I am working on a project for a Django web-based application. In this project, there is a section in which I take info from the user through an HTML form. I added a section "image upload " but it gives a MultiValueDictKeyError error when the user does not upload any file. I tried this but not working for me.
This is error section : error image
This is my addpost.html section. It consists of a form through which, I am taking info.
<form action="{% url 'addpost' %}" method='POST' enctype="multipart/form-data" novalidate>
{% include 'includes/messages.html' %}
{% csrf_token %}
{% if user.is_authenticated %}
<input type="hidden" name="user_id" value="{{user.id}}">
{% else %}
<input type="hidden" name="user_id" value="0">
{% endif %}
<div class="row ">
<div class="tex-center">
<div class="row">
<div class="col-md-6 text-left">
<div class="form-group name">
<input type="text" name="author" class="form-control" placeholder="Author"
{% if user.is_authenticated %} value="{{user.first_name}}" {% endif %} readonly>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="title" class="form-control" placeholder="title" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="location" class="form-control" placeholder="location" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="short_desc" class="form-control"
placeholder="Write short description" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group message">
<textarea class="form-control" name="full_desc"
placeholder="Write full description"></textarea>
</div>
</div>
<input type="file" id="myFile" name="place_photo" required/>
<div class="col-md-12">
<div class="send-btn text-center">
<input type="submit" class="btn btn-outline-success mr-1" value="Send Post">
Cancel
</div>
</div>
</div>
</div>
</div>
</form>
This is the views.py file where I receive POST data
def add_post(request):
if request.method == "POST":
try:
is_private = request.POST['is_private']
except MultiValueDictKeyError:
is_private = False
author = request.POST['author']
title = request.POST['title']
user_id = request.POST.get('user_id')
location = request.POST['location']
short_desc = request.POST['short_desc']
full_desc = request.POST['full_desc']
place_photo = request.FILES['place_photo']
post = Post(author=author, user_id=user_id, title=title, location=location,
short_desc=short_desc,full_desc=full_desc, place_photo=place_photo)
post.save()
messages.success(request,"Your post uploaded successfully")
return render(request,'community/addpost.html')
This is my models.py file
class Post(models.Model):
author = models.CharField(max_length=100, default=' ')
title = models.CharField(max_length=150)
user_id = models.IntegerField(blank=True)
location = models.CharField(max_length=100, default=' ')
short_desc = models.CharField(max_length=255, default='In less than 250 words')
full_desc = models.TextField()
place_photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
added_date = models.DateTimeField(default=datetime.now,blank=True)
I want to set initial data in my ModelForm for a datefield but it is not working. Below is my code.
def get_date():
return timezone.localtime(timezone.now()).date()
ModelForm:
class TransferPacketForm(forms.ModelForm):
party = forms.ModelChoiceField(
required=True, queryset=Party.objects.all(),
widget=forms.Select(
attrs={
'class': 'form-control'
}
)
)
transferred_on = forms.DateField(
required=True, initial=get_date, input_formats=['%d-%m-%Y'],
validators=[validators.get('min_value')(date(2000, 01, 01))],
widget=forms.DateInput(
format='%d-%m-%Y',
attrs={
'autofocus': 'true', 'class': 'form-control'
}
)
)
transferred_roi = forms.DecimalField(
required=True, max_digits=3, decimal_places=2,
min_value=1.00, max_value=5.00,
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
transferred_amount = forms.IntegerField(
required=True, min_value=1, widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
class Meta:
model = Packet
fields = (
'transferred_on', 'transferred_amount',
'transferred_remark', 'transferred_roi',
'party'
)
widgets = {
'transferred_remark': forms.Textarea(
attrs={
'class': 'form-control'
}
)
}
View:
class TransferPacketView(LoginRequiredMixin, UpdateView):
model = Packet
form_class = TransferPacketForm
http_method_names = ['get', 'post']
template_name = 'update_templates/transfer_packet.html'
def get_success_url(self):
return reverse(
'girvi:transferred_packet',
kwargs={
'pk': self.get_object()
}
)
def get(self, request, *args, **kwargs):
return super(TransferPacketView, self).get(request, *args, **kwargs)
def form_valid(self, form):
pkt_obj = self.get_object()
pkt_obj.is_transferred = True
pkt_obj.save()
return redirect(
self.get_success_url()
)
Form:
<tr><th><label for="id_transferred_on">Transferred on:</label></th><td><input autofocus="true" class="form-control" id="id_transferred_on" name="transferred_on" type="text" value="15-02-2015" /></td></tr>
<tr><th><label for="id_transferred_amount">Transferred amount:</label></th><td><input class="form-control" id="id_transferred_amount" name="transferred_amount" type="text" /></td></tr>
<tr><th><label for="id_transferred_remark">Transferred remark:</label></th><td><textarea class="form-control" cols="40" id="id_transferred_remark" maxlength="150" name="transferred_remark" rows="10">
</textarea></td></tr>
<tr><th><label for="id_transferred_roi">Transferred roi:</label></th><td><input class="form-control" id="id_transferred_roi" name="transferred_roi" type="text" /></td></tr>
<tr><th><label for="id_party">Party:</label></th><td><select class="form-control" id="id_party" name="party">
<option value="" selected="selected">---------</option>
<option value="2">ram pal</option>
<option value="1">shyam pal</option>
</select></td></tr>
But html form is rendered without any initial data.
Html form field:
<div class="form-group form-group-sm clearfix">
<label class="control-label col-xs-2 col-xs-offset-6" for="id_transferred_on">Dated</label>
<div class="col-xs-4 pull-right">
<div id="datepicker" class="input-group date">
<input id="id_transferred_on" class="form-control" type="text" name="transferred_on" autofocus="true">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
Can someone tell me what is wrong??? Why value is not set to initial data.
Template:
<form id="transferPacketForm" class="form form-horizontal width-500 center-block theme-font" role="form" action="." method="post">{% csrf_token %}
<!-- DIV -->
{% if form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{% for field in form %}
{% if field.errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>{{ field.label }}: {{ field.errors|striptags }}</span><br>
{% endif %}
{% endfor %}
{% for error in form.non_field_errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>Error: {{ error|striptags }}</span>
{% endfor %}
</div>
{% endif %}
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm clearfix">
<label for="id_{{ form.transferred_on.name }}" class="control-label col-xs-2 col-xs-offset-6">Dated</label>
<div class="col-xs-4 pull-right">
<div class="input-group date" id='datepicker'>
{{ form.transferred_on }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.party.name }}" class="control-label col-xs-4">{{ form.party.label }}</label>
<div class="col-xs-8">
{{ form.party }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_amount.name }}" class="control-label col-xs-4">Amount</label>
<div class="col-xs-8">
{{ form.transferred_amount }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_roi.name }}" class="control-label col-xs-4">Interest</label>
<div class="col-xs-8">
{{ form.transferred_roi }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_remark.name }}" class="control-label col-xs-4">Remark</label>
<div class="col-xs-8">
{{ form.transferred_remark }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="btn-toolbar" align="middle">
<button type="submit" class="btn btn-primary btn-color btn-bg-color">Submit</button>
<button type="button" class="btn btn-danger btn-color btn-bg-color" onclick="window.close()">Close</button>
</div>
<!-- /DIV -->
</form>
It will only render initial value if you have no model instance passed to the form. Try this:
p = Packet.objects.filter(transferred_on__isnull=True)[0]
# or simply
p = Packet()
f = TransferPacketForm(instance=p)
print(f['transferred_on'])
which will not have initial value for that field, but if you do:
f = TransferPacketForm()
print(f['transferred_on'])
it will. Check it out.
Edit
It doesn't apply when you pass initial dictionary to the form, it will actually check if the model's field is empty and use the value from the dictionary. So workaround for you is not to use field's initial, but forms' initial instead, namely through view's get_initial() it is.