Django comments framework, set default form values - django

I defined a custom comment form in forms.py as fallow
class CommentFormWithReply(CommentForm):
reply_to = forms.ModelChoiceField(queryset=CommentWithReply.objects.all(),
widget=forms.HiddenInput(), required=False)
def get_comment_model(self):
# Use our custom comment model instead of the built-in one.
return CommentWithReply
def get_comment_create_data(self):
# Use the data of the superclass, and add in the title field
data = super(CommentFormWithReply, self).get_comment_create_data()
return data
what should I do to render this form with the current user information as default values (name, email, webpage ).

may be this:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#initial
if request.method == 'POST':
form = CommentFormWithReply(request.POST)
.........................................
if request.method == 'GET':
default_data = {'name': 'Alexey', 'email': 'smt#email.smt', 'webpage': 'http://example.com'}
form = CommentFormWithReply(default_data)

Related

Pre-populating Model Form with object data - Django

I have tried various options for this but no luck so far. I am trying to get instance data to be pre-populated into my ModelField. Here is what I have:
forms.py
class edit_project_info(ModelForm):
project_name = forms.CharField(max_length=150)
class Meta:
model = Project
exclude = ['project_type', 'created_date', 'start_date', 'end_date', 'pm_scope', 'dev_scope', 'design_scope', 'testing_scope' ]
View.py
def edit_project (request, offset):
this_project = Project.objects.get(pk=offset)
data = {'project_name' : 'abc'}
if request.method == 'POST':
form = edit_project_info(request.POST, instance=this_project, initial=data)
if form.is_valid():
form.save()
return HttpResponseRedirect('/project_profile/%s/' % offset)
else:
form = edit_project_info()
All I get is an empty field. I can add the initial value to forms.py, but then it is static rather than populated based on the form instance. What I have done here with creating a dict and then passing it to initial in the form instance does not seem to do anything. I'm sure I am missing something basic. Any help would be great! Thanks ahead of time.
Two last lines recreate your form variable. Just remove else: form = edit_project_info():
def edit_project (request, offset):
this_project = Project.objects.get(pk=offset)
data = {'project_name' : 'abc'}
form = edit_project_info(request.POST, instance=this_project, initial=data)
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponseRedirect('/project_profile/%s/' % offset)
# else:
# form = edit_project_info()
# ...

Can't save a form in Django (object has no attribute 'save')

The following is my form:
class AdvancedSearchForm(forms.Form):
valueofres = forms.ChoiceField (label="res", choices = ((0, 0),(2.2, 2.2)), required= False)
The following is my view:
def advancedsearch(request):
if request.method == "POST":
search = AdvancedSearchForm(request.POST, request.FILES)
if search.is_valid():
new_search = search.save(commit=False)
Why I'm getting the error 'AdvancedSearchForm' object has no attribute 'save'?
save is available only for ModelForm by default, and not for forms.Form
What you need to do is this. Either use:
class AdvancedSearchForm(forms.ModelForm):
valueofres = forms.ChoiceField (label="res", choices = ((0, 0),(2.2, 2.2)), required= False)
class Meta:
model=Search #or whatever object
Or:
def advancedsearch(request):
if request.method == "POST":
search_form = AdvancedSearchForm(request.POST, request.FILES)
if search_form.is_valid():
cd = search_form.cleaned_data
search = #populate SearchObject()
search.save()
Forms don't have a save() method.
You need to use a ModelForm (docs) as that will then have a model associated with it and will know what to save where.
Alternatively you can keep your forms.Form but you'll want to then extract the valid data from the for and do as you will with eh data.
if request.method == "POST":
search_form = AdvancedSearchForm(request.POST, request.FILES)
if search_form.is_valid():
cd = search_form.cleaned_data
search = Search(
# Apply form data
)
search.save()

django prepopulate modelform - nothing happens

This must be a very simple thing however I can not seem to get through it..
I trying to build a form where the user can update a ModelForm. First he inserts a user id and afterwards I want to show him the form pre-populate with the original data so he can change only the fields that he wants.
After some the help of my friend google, stackoverflow and the django documentation, I've come to this:
views.py
user = User.objects.get(user_id=usr)
if request.method == 'POST':
form = TableForm(request.POST)
if form.is_valid():
#do something
else:
form = TableForm(instance=user)
return render_to_response('template.html',{'form':form})
forms.py
class TableForm(forms.ModelForm):
pres_clinic = forms.ModelChoiceField(queryset=PresClinic.objects.all(),
widget=SelectWithPop(), label=ugettext("Clinic presentation"),
required=False)
MAYBECHOICES = (
('', '---------'),
(ugettext('Yes'), ugettext('Yes')),
(ugettext('No'), ugettext('No')))
bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext(
"BCG scar"), required=False)
mantoux_register = forms.ChoiceField(choices=MAYBECHOICES,
label=ugettext("Mantoux register"), required=False)
date_diag = forms.DateField(widget=DateTimeWidget, label=ugettext(
"Diagnosis date"), required=False)
situation = forms.ModelChoiceField(queryset=Situation.objects.all(),
widget=SelectWithPop(), label=ugettext("Patient status"),
required=False)
date_situation = forms.DateField(widget=DateTimeWidget, label=ugettext(
"Date patient status"), required=False)
class Meta:
model = Table
fields = ('pres_clinic', 'bcg_scar', 'mantoux_register',
'date_diag', 'situation', 'date_situation')
def clean(self):
cleaned_data = self.cleaned_data
diag = cleaned_data.get('date_diag')
errors = []
now = datetime.date.today()
if diag is not None and diag != u'':
if diag > now:
errors.append(ugettext('The field "Diagnosis date" should be '
'smaller than the actual date'))
if errors:
raise ValidationError(errors)
return cleaned_data
template:
{{ form }} # presents the empty form and not the data from that user
The version of django is 1.4
Can anyone tell me what is wrong and why I'm not able to see the form populated?
Thank you very much
You need to define a dictionary to be used for the initial data and change from TableForm(instance=user) to TableForm(initial=dict), for example something like:
user = User.objects.get(user_id=usr)
if request.method == 'POST':
form = TableForm(request.POST)
if form.is_valid():
#do something
else:
data = {'pres_clinic' : 'value', 'bcg_scar' : 'value', 'mantoux_register' : 'value'}
form = TableForm(initial=data)
return render_to_response('template.html',{'form':form})
I would also put the render to response out of the if statement so if the form isn't valid the page should reload and show any errors.
More information on the django docs here
I hope this helps!
You can try 'model_to_dict'
from django.forms.models import model_to_dict
user = User.objects.get(user_id=usr)
if request.method == 'POST':
form = TableForm(request.POST)
if form.is_valid():
#do something
else:
form = TableForm(initial=model_to_dict(user))
return render_to_response('template.html',{'form':form})

Django form is_valid() fails

I am a real beginner in web development. The following code is failing at the is_valid() check. But I do not understand why: The form should get its data filled from the POST-data or not?
Model:
class Statement(models.Model):
text = models.CharField(max_length=255)
user = models.ForeignKey(User)
time = models.DateField()
views = models.IntegerField()
ModelForm:
class StatementForm(ModelForm):
class Meta:
model = Statement
widgets = {
'time':forms.HiddenInput(),
'user':forms.HiddenInput(),
'views':forms.HiddenInput(),
}
View function:
def new(request):
if request.method == 'POST': # If the form has been submitted...
form = StatementForm(request.POST) # A form bound to the POST data
if form.is_valid():
stmt = form.save()
path = 'stmt/' + stmt.id
return render_to_response(path, {'stmt': stmt})
else:
c = {}
c.update(csrf(request))
loggedin_user = request.user
d = datetime.now()
form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})
return render_to_response('new_stmt.html', {'form': form, },context_instance=RequestContext(request))
I found similar topics and tried a lot. This is how i think it should work. I really need advice.
All fields of your model are required. So, form.is_valid() will be True, if all fields are filled with correct values and are not blanked.
You have declared fields time, user, views as hidden fields. Are you sure, that you have filled them in your template form?
Also, you may want to auto stamp field time = models.DateField(). Modify your model field like
time = models.DateField(auto_now=True)`.
After this you don't have to fill it by yourself in template form.
Your view must return HttpResponse object in all cases. If your form is not valid, i.e. if form.is_valid() will return False, then no HttpResponse object will be returned by your view. This can be the source of your fail. Add else statement for if form.is_valid():
from django.http import Http404
def new(request):
if request.method == 'POST': # If the form has been submitted...
form = StatementForm(request.POST) # A form bound to the POST data
if form.is_valid():
stmt = form.save()
path = 'stmt/' + stmt.id
return render_to_response(path, {'stmt': stmt})
else:
# Do something in case if form is not valid
raise Http404
else:
# Your code without changes
Change this line:
form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})
For this:
form = StatementForm(initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})

Pre-Setting django form data before displaying the form

I am displaying a django form and I want to prepare some field data before it
is passed to to be rendered. In the django docs, I see plenty of places
where form data is accessed, but none where form data is set before display.
Any thoughts or suggestions on how to do this?
Here's an example similar to the django docs.
-----------forms.py--------------
class BookForm(ModelForm):
author = forms.CharField(max_length=100)
title = forms.CharField(max_length=3,
widget=forms.Select(choices=TITLE_CHOICES))
birth_date = forms.DateField(required=False)
-----------views.py--------------
def author_view(request):
if request.method == 'POST':
# DO My processing...
form = BookForm()
# How can I edit, or preset my form fields here?
c = Context({
'form': form,
})
return prepCxt(request, 'book.html', c) # Wrapper for easy display
In your views you have:
def author_view(request):
if request.method == 'POST':
# DO My processing...
form = BookForm()
# How can I edit, or preset my form fields here?
c = Context({
'form': form,
})
return prepCxt(request, 'book.html', c) # Wrapper for easy display
You should move your form=BookForm() before the if:
def author_view(request):
form = BookForm()
if request.method == 'POST':
# DO My processing...
What happens is that the if "POST" section adds a value in form and then it could get overriden.
Secondly if you are trying to change something in the way it display you are probably best adding default/initial values:
Django set default form values:
BookForm(initial={ 'myfield': 'myval'})
if you are tryiong to change values that you want to save to the DB then you:
if form.is_valid():
myobject = form.save(commit=false)
myobject.myfield = mval
myobj.save()
form = BookForm(instance = myobjext)
Something else? Please be more specific.