I need to use the object details of obj to save in a list or some sort to use as a parameter in my send_order_verification() function.
def order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
obj = form
obj.save()
send_order_verification(order_details, obj.email)
This is my send_order_verification() function:
def send_order_verification(order_details, email):
return send_mail(
('Thank you for your order #{0}', x),
('Name: {0}\nEmail: {1}\nTelephone: {2}', x, y, z),
[settings.EMAIL_SEND_TO],
['{0}' % email]
)
How could this be done? I tried with order_details = [obj.name, obj.email, obj.telephone] but can't access it with order_details[0] and so forth.
Send the object itself:
def order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
obj = form
obj.save()
send_order_verification(obj)
def send_order_verification(order_details):
return send_mail(
('Thank you for your order #{0}', order_details.name),
('Name: {0}\nEmail: {1}\nTelephone: {2}', order_details.name, order_details.email, order_details.telefone),
[settings.EMAIL_SEND_TO],
['{0}' % order_details.email]
)
Related
I just want to add something to mypath like: bla1/bla2/bla3/something
or whatever pass in member!
how can i do this?
def to(request):
if request.method == "POST":
x = request.POST['username']
member = whome(unique_user=x)
member.save()
links.objects.create(path=request.get_full_path())
links().save()
return render(request, "home.html")
I have the following view:
#login_required
def my_view(request):
instance = my_model(user=request.user)
form = my_model_form(request.POST,instance = instance)
if request.method == "POST":
if form.is_valid():
form.save(commit=False)
#Field1 and field2 is already in the form (its the input)
# Do some back-end operations to get values for the remaining fields
df = some_util_function()
form.field3 = df["field3"]
form.field4 = df["field4"]
form.field5= df["field5"]
form.save()
return redirect("my_html")
else:
form = my_model_form()
context = {
"form":form
}
return render(request, "discounttracker/my_html.html",context=context)
and the problem is that field3,field4,field5 are not changed. I have even tried to hard-code them to 1000, 2000,3000 (they are FloatField(default=0)) but they remain at their default value when written to the DB.
What am I doing wrong here?
You are setting the attributes of the form, not of the instance wrapped in the form. You should alter this to:
#login_required
def my_view(request):
instance = my_model(user=request.user)
if request.method == 'POST':
form = my_model_form(request.POST, instance = instance)
if form.is_valid():
# Field1 and field2 is already in the form (its the input)
# Do some back-end operations to get values for the remaining fields
df = some_util_function()
# ↓ the instance of the form
form.instance.field3 = df['field3']
form.instance.field4 = df['field4']
form.instance.field5 = df['field5']
form.save()
return redirect("my_html")
else:
form = my_model_form()
context = {
'form': form
}
return render(request, 'discounttracker/my_html.html', context=context)
I have the following:
desig = []
class New_user_form(UserCreationForm):
desig = forms.ChoiceField(choices=desig)
def acquire_groups(self):
g = Group.objects.all()
for k in g:
desig.append((k.name, k.name))
print(desig)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
designation = self.cleaned_data["desig"]
print("New_user_form save : Designation :", designation)
if commit:
user.save()
g = Groups.objects.filter(name=designation)
print("acquired group", g[0].name)
user.groups.add(g)
return user
The following is my view:
def register_user(request):
if request.method == 'POST':
form = New_user_form(request.POST)
if form.is_valid():
print("Form Validated")
new_user = form.save()
HttpResponse("Success")
else:
HttpResponse("Invalid Form")
else:
form = New_user_form()
form.acquire_groups()
g = Group.objects.all()
desig = []
for k in g:
desig.append(k.name)
args = {}
args.update({'user':request.user.username,
'form':form,
'STATIC_URL':settings.STATIC_URL,
'desig': desig,})
return render_to_response('register.html', args)
I have tried to save the form many times and it always does not validate. I dont understand why the choice field fails. I am able to use the form without the choice field. But I want to use the choice field to add new users to an existing group.
I dont understand why the form is getting invalid.
EDIT: I have changed my form as follows:
class New_user_form(UserCreationForm):
email = forms.EmailField(required=True)
desig = []
def __init__(self, **kwargs):
u = UserCreationForm.__init__(self, kwargs)
try:
if kwargs['desig_group']:
print("desig_group instantiated. Found kwargs = ", kwargs['desig_group'])
else:
print("desig_group not instantiated")
except (AttributeError, KeyError) as ex:
for g in Group.objects.all():
self.desig.append((g.name, g.name))
print("desig : ", self.desig)
desig_group = forms.ModelChoiceField(queryset=Group.objects.all())
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
designation = self.cleaned_data["desig_group"]
print("New_user_form save : Designation :", designation)
if commit:
user.save()
g = Groups.objects.filter(name=designation)
print("acquired group", g[0].name)
user.groups.add(g)
return user
I have changed my view now as :
def register_user(request):
if request.method == 'POST':
print("request.POST = ", request.POST)
form = New_user_form(**request.POST)
print("form bound: ", form.is_bound)
print("Form bool: ", bool(form.errors))
if form.is_valid():
print("Form Validated")
new_user = form.save()
return HttpResponse("Added new user")
else:
print("Form is invalid")
HttpResponse("Invalid form submission.")
else:
form = New_user_form()
g = Group.objects.all()
desig = []
for k in g:
desig.append(k.name)
args = {}
args.update(csrf(request))
args.update({'user':request.user.username,
'form':form,
'STATIC_URL':settings.STATIC_URL,
'desig': desig,})
return render_to_response('emp_users/register.html', args)
With this, my form is not passing validation but all the required data is arriving in POST.
I just need to know how to validate it now.
form.cleaned_data['desig_group']
returns KeyError but the POST has that value in its query dictionary
The following is my POST:
You can't set the choices after the form is initialized. Instead, just set the choices as such:
# forms.py
class New_user_form(UserCreationForm):
desig = forms.ModelChoiceField(queryset=Group.objects.all())
...
# views.py
def register_user(request):
form = New_user_form(request.POST or None)
if request.method == 'POST':
if form.is_valid():
print("Form Validated")
new_user = form.save()
args = {}
args.update({'user':request.user.username,
'form':form, 'STATIC_URL':settings.STATIC_URL,
'desig': desig,})
return render_to_response('register.html', args)
Why my code does not show validation form error message?
I try something like this:
def index(request):
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
form = AngebotForm()
else:
form = MessageForm(request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
else:
form = MessageForm()
return render_to_response('index.html',{'a_form':AngebotForm(), 'm_form':MessageForm()},context_instance=RequestContext(request))
What am I doing wrong?
Because in else part you are re-initializing the form which will loose the current state of form.
Just remove these lines:
else:
form = MessageForm()
In the end your view should look like this:
def index(request):
form = AngebotForm()
m_form = MessageForm()
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
m_form = MessageForm(request.POST)
if m_form.is_valid():
m_form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
return render_to_response('index.html',{'a_form':form, 'm_form':m_form},context_instance=RequestContext(request))
How can I update an object from a formset using request.POST?
Here is my code and my problem is that this always creates a new PhoneNumber object. But I want to update the old PhoneNumber object.
def contact_detail(request, contact_id):
contact = get_object_or_404(Contact, pk=contact_id)
phone_number_list = PhoneNumber.objects.filter(contact=contact_id)
if request.method == 'POST':
cform = ContactForm(request.POST, instance=contact)
#the next line is probably wrong!
phonenumberformset = PhoneNumberFormSet(request.POST, queryset=phone_number_list)
if cform.is_valid() and phonenumberformset.is_valid():
phonenumber_instances = phonenumberformset.save(commit=False)
for phonenumber in phonenumber_instances:
phonenumber.contact = contact
phonenumber.save()
request.user.message_set.create(message='The contact "%s" was chanced successfully.' % contact.__str__())
return HttpResponseRedirect("/crm/contacts/?oby=1")
else:
cform = ContactForm(instance=contact)
phonenumberformset = PhoneNumberFormSet(queryset=phone_number_list)
return render_to_response(
'crm/contact_detail.html',
{'cform': cform, 'phonenumberformset': phonenumberformset,},
context_instance = RequestContext(request),
)
Edit: I create three PhoneNumberForms:
PhoneNumberFormSet = modelformset_factory(PhoneNumber, max_num=3, extra=3, exclude=('contact',))
Edit: The solution using inlineformset_factory:
#login_required
def contact_detail(request, contact_id):
contact = get_object_or_404(Contact, pk=contact_id)
PhoneNumberInlineFormSet = inlineformset_factory(Contact, PhoneNumber, max_num=3)
if request.method == 'POST':
cform = ContactForm(request.POST, instance=contact)
classificationformset = ClassificationInlineFormSet(request.POST, request.FILES, instance=contact)
addressformset = AddressInlineFormSet(request.POST, request.FILES, instance=contact)
phonenumberformset = PhoneNumberInlineFormSet(request.POST, request.FILES, instance=contact)
if cform.is_valid() and phonenumberformset.is_valid():
contact = cform.save()
phonenumberformset.save()
request.user.message_set.create(message='The contact "%s" was chanced successfully.' % contact.__str__())
return HttpResponseRedirect("/crm/contacts/?oby=1")
else:
cform = ContactForm(instance=contact)
phonenumberformset = PhoneNumberInlineFormSet(instance=contact)
return render_to_response(
'crm/contact_detail.html',
{'cform': cform, 'phonenumberformset': phonenumberformset,},
context_instance = RequestContext(request),)
This approach even adds a delete checkbox to each inline form. Easy and great.
Rather than use modelformset_factory, use inlineformset_factory - see the documentation here - sorry, should have pointed you to that initially.
Then you can drop the queryset stuff, since inlineformset_factory takes care of that, and just pass the instance argument (which here refers to the parent model, ie the Contact object). You also won't need to iterate through explicitly setting the contact attribute on save, as again that's taken care of.