Not saving data to Database from Form - python

When i have this view, It only change username a password from first Form, but it would save any data from second form. Why?
if request.method == 'POST': # If the form has been submitted...
username_a_heslo = UserCreationForm(request.POST, prefix = "začátek")
přidat_údaje = UcitelZmenaForm(request.POST, prefix = "konec")
if username_a_heslo.is_valid() and přidat_údaje.is_valid(): # All validation rules pass
změnajména = request.user
změnajména.username = username_a_heslo.cleaned_data["username"]
změnajména.save()
zmenahesla=request.user.set_password(username_a_heslo.cleaned_data["password1"])
# primary = username_a_heslo.save()
cast_form = Ucitel.objects.all().filter(user=request.user)
form = UcitelZmenaForm(přidat_údaje.cleaned_data, instance=cast_form[0])
form.save
#b = přidat_údaje.save()
return HttpResponseRedirect('/hlavni_stranka/')
else:
username_a_heslo = UserCreationForm(prefix = "začátek")
přidat_údaje = UcitelZmenaForm(prefix = "konec")
return render(request, 'registration/prihlasen.html', {'prvni_prihlaseni':prvni_prihlaseni,'první_form': username_a_heslo,'druhý_form':přidat_údaje})

You did not call the function on the second one, you only have form.save when you need form.save().

Related

NOT NULL constraint failed: mainsite_customer.user_id

I just wanna get profile with full form or empty form.
def local_cabinet(request):
user_id = request.user.id
caruser = Checkout.objects.filter(user=request.user)
# form = CheckoutForms()
orders = request.user.orderitem_set.all()
total_orders = orders.count()
ready_order = request.user.order_set.all()
customer = Customer.objects.filter(user=request.user)
customer_form = CustomerForm()
Maybe here's problem I don't know:
if request.method == 'POST':
if customer.exists():
form = CustomerForm(request.POST, request.FILES, instance=customer)
else:
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
context = {
'caruser': caruser,
'orders': orders,
'total_orders': total_orders,
'ready_order': ready_order,
'cat_selected': 0,
'customer_form': customer_form,
'customer': customer,
}
return render(request, 'localcabinet.html', context=context)
I don't know why I get this, maybe because I'm not right at saving the form.
You are missing User instance in form, that you probably need to pass it after form creation and before saving it.
You didn't provide model nor forms, but I guess it will look like this:
if request.method == 'POST':
...
else:
form = CustomerForm(request.POST)
form.user = request.user
if form.is_valid():
form.save()
...
Another thing is that you assign queryset instead of single object with filter method:
customer = Customer.objects.filter(user=request.user) # gives queryset with probably one object
customer = Customer.objects.get(user=request.user) # gives an object - but gives Error if there is None or more than one
Probably the best approach to get single object is with try and except:
try:
customer = Customer.objects.get(user=request.user)
except Customer.DoesNotExists:
customer = None
then later instead of if customer.exists() you can use simple if customer.

form initials do not show

i am trying to set the form initials for the sender field as the logged in user, and it does not show. i removed the if request method statement and adjusted the indentaion and the initials showed. I am stuck, i believe the form is supposed to have that request method statement. i've gone through the documentation and it says the post method binds the data and submits, but there isn't any data when the page is refreshed or newly loaded. what could be wrong?
views.py
def transfer(request):
profile = Profile.objects.get(user=request.user)
if request.method == "POST":
form = TransferForm(request.POST,initial={"sender": profile})
if form.is_valid():
print(form)
form.save()
sender = models.sendcoins.objects.get(sender=request.user.profile)
profile2 = Profile.objects.get(username=receiver)
user_wallet = wallet.objects.get(owner=profile)
print(receiver)
temp = sender # NOTE: Delete this instance once money transfer is done
receiver = models.wallet.objects.get(owner=profile2) # FIELD 1
transfer_amount = sender.amount # FIELD 2
sender = models.wallet.objects.get(owner=profile) # FIELD 3
# Now transfer the money!
sender.balance = sender.balance - transfer_amount
receiver.balance = receiver.balance + transfer_amount
# Save the changes before redirecting
sender.save()
receiver.save()
temp.delete() # NOTE: Now deleting the instance for future money transactions
else:
return(HttpResponse("form is not valid"))
else:
form = TransferForm()
return render(request, "sendcoins.html", {"form": form})

Lines before form.save() are not saving the right values

I have a view with model form, the ModelForm doesn't really contain all fields in the model. other fields I've used the methods of form.field = value before form.save(), but all of this fields being saved as default. none take the value am trying to give. here are the code :
def PostAd(request):
ad_post_form = AdPostForm()
if request.user.is_authenticated:
obj = Account.objects.get(user=request.user)
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
ad_post_form.created_by = request.user
if obj.role == 'admin':
ad_post_form.is_active = True
ad_post_form.save()
return redirect('home')
else:
ad_post_form = AdPostForm(request.POST, request.FILES)
else:
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
otp_number = random.randint(100000, 999999)
ad_post_form.otp = otp_number
ad_post_form.is_activated = False
ad_post_form.save()
current_id = ad_post_form.id
current_contact_email = request.POST.get('contact_email')
email_url_active = str(settings.URL_LOCAL) + 'new_ad/adidnumberis' + str(
current_id) + '/needactivate/activate/' + str(otp_number) + '/'
email_msg = "Please Confirm adding the Ad to Jehlum. Click link " + email_url_active
email = EmailMessage('Active Email', email_msg, to=[current_contact_email])
email.send()
return redirect('home')
else:
ad_post_form = AdPostForm()
context = {
'ad_post_form': ad_post_form,
}
return render(request, 'pages/post-ad.html', context)
the problem is ad_post_form.is_active = True is being saved as False(default)
also ad_post_form.otp = otp_number is being saved as 0 (default) and i need to give the spicific values i assigned here .
You need to get the model instance and set the attributes there. You so this by calling save with commit=False.
if ad_post_form.is_valid():
ad_post = ad_post_form.save(commit=False)
ad_post.created_by = request.user
...
ad_post.save()

How to work with context in Django

I'm trying to create a confirmation page. User can create orders on one page, then the create_order view validates the forms and send a request with context to another view which is called confirm_order. I think that I would work correct but there is one problem. The first time confirm_order gets request and context which contains data from forms. But when User clicks on confirm in this page, the confirm_view is called without this context so I'm getting error:
> ValidationError at /create-job/ [u'ManagementForm data is missing or
> has been tampered with']
Do you guys know how to send the context second time?
Here are those two views:
def create_order(request):
LanguageLevelFormSet = formset_factory(LanguageLevelForm, extra=5, max_num=5)
language_level_formset = LanguageLevelFormSet(request.POST or None)
job_creation_form = JobCreationForm(request.POST or None, request.FILES or None)
context = {'job_creation_form': job_creation_form,
'formset': language_level_formset}
if request.method == 'POST':
if job_creation_form.is_valid() and language_level_formset.is_valid():
cleaned_data_job_creation_form = job_creation_form.cleaned_data
cleaned_data_language_level_formset = language_level_formset.cleaned_data
context = {
'cleaned_data_job_creation_form': cleaned_data_job_creation_form,
"cleaned_data_language_level_formset": cleaned_data_language_level_formset,
}
mutable = request.POST._mutable # I'm adding parameter 'review' to be able to differ between two different posts in confirm_order view
request.POST._mutable = True
request.POST['review'] = True
request.POST._mutable = mutable
return confirm_order(request, context)
else:
return render(request, 'auth/jobs/create-job.html', context=context)
return render(request, 'auth/jobs/create-job.html', context=context)
def confirm_order(request, context):
print context
cleaned_data_job_creation_form = context['cleaned_data_job_creation_form']
cleaned_data_language_level_formset = context['cleaned_data_language_level_formset']
print request.POST['review']
if request.method == 'POST' and request.POST['review'] == True:
file = cleaned_data_job_creation_form['file']
count = 5 #simplified multiple rows
jobs = []
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
d = {}
d['language_from'] = cleaned_data_job_creation_form['language_from'].name
d['language_to'] = language
d['number_of_characters'] = count
d['price_per_sign'] = 1
d['estimated_price'] = count * d['price_per_sign']
jobs.append(d)
table = CreatedOrdersTable(jobs)
context = {'table': table,
'cleaned_data_job_creation_form': cleaned_data_job_creation_form,
'cleaned_data_language_level_formset': cleaned_data_language_level_formset}
return render(request, 'auth/jobs/confirm-order.html', context=context)
else:
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
Job.objects.create(
customer=request.user,
text_to_translate=cleaned_data_job_creation_form['text_to_translate'],
file=cleaned_data_job_creation_form['file'],
short_description=cleaned_data_job_creation_form['short_description'],
notes=cleaned_data_job_creation_form['notes'],
language_from=cleaned_data_job_creation_form['language_from'],
language_to=language,
level=level,
)
return HttpResponseRedirect('/order-success')
You are returning a template render on your first view. So, the request doesn't end on your confirm_order view.
If you want, you can redirect to reverse('confirm_order') and add the data on session.
In your confirm_order view you will pop the data from session and continue with your flow.

Django populating initial data in formset

This may be a rather simple problem. But I am trying to populate my form with initial data taken from a database. I don't really know where to start. Any advice would help.
Some background: I have a disease with multiple indicators. In my form I am pulling disease_id = 2 then wanting to populate the indicators currently in the database, so they may be edited.
views.py
def drui(request):
disease_id = request.GET.get('disease_id', '2')
if request.method == "POST":
disease = get_object_or_404(Disease, pk=disease_id)
diseaseForm = DiseaseForm(request.POST, instance=disease)
if diseaseForm.is_valid():
new_disease = diseaseForm.save(commit=False)
indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=new_disease)
if indicatorInlineFormSet.is_valid():
new_disease.save()
indicatorInlineFormSet.save()
return HttpResponseRedirect(reverse(somewhere))
else:
diseaseForm = DiseaseForm()
indicatorInlineFormSet = IndicatorFormSet(instance=Disease())
return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet},context_instance=RequestContext(request))
Just put disease object out in the request POST
def drui(request):
disease_id = request.GET.get('disease_id', '2')
disease = get_object_or_404(Disease, pk=disease_id)
if request.method == "POST":
diseaseForm = DiseaseForm(request.POST, instance=disease)
if diseaseForm.is_valid():
new_disease = diseaseForm.save(commit=False)
indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES,
instance=new_disease)
if indicatorInlineFormSet.is_valid():
new_disease.save()
indicatorInlineFormSet.save()
return HttpResponseRedirect(reverse(somewhere))
else:
diseaseForm = DiseaseForm(instance=disease)
indicatorInlineFormSet = IndicatorFormSet(instance=disease)
return render_to_response("drui.html", {
'diseaseForm': diseaseForm,
'indicatorInlineFormSet': indicatorInlineFormSet
},context_instance=RequestContext(request))

Categories

Resources