I'm trying to submit two forms with one submit button. First I want to check if form 1 already exists in the db, if id does then just post the second form using the "ticker" from first form as Foreginkey. But seem to get an error:
'UserTickerForm' object has no attribute 'get'
My code:
if request.method == 'POST':
request_form_user_ticker = UserTickerForm(request.POST)
request_form_trade = TradesForm(request.POST)
if request_form_user_ticker.is_valid() and request_form_trade.is_valid():
if not User_Ticker.objects.filter(portfolio=select_portfolio, ticker=request_form_user_ticker.get('ticker')).exists():
user_ticker_instace = request_form_user_ticker.save(commit=False)
user_ticker_instace.portfolio = select_portfolio
user_ticker_instace.save()
trade_instance = request_form_trade.save(commit=False)
trade_instance.ticker = request_form_user_ticker.get('ticker')
trade_instance.save()
else:
trade_instance = request_form_trade.save(commit=False)
trade_instance.ticker = request_form_user_ticker.get('ticker')
trade_instance.save()
Does anyone know who this is happening and what I can do to fix this?
instead of request_form_user_ticker.get('ticker') you should call .get('ticker') on cleaned data so request_form_user_ticker.cleaned_data.get('ticker')
Related
I am facing the issue I can't find the solution yet. It's working so far. but now showing an error. don't know how to fix this. please need help.
views.py
def add_product(request):
product_form = ProductForm()
product_variant_images_form = ProductVariantsImagesForm()
if request.method == 'POST':
product_form = ProductForm(request.POST)
product_variant_images_form = ProductVariantsImagesForm(request.POST,request.FILES)
if product_form.is_valid():
print(request.POST)
product = product_form.save(commit=False)
vendor = CustomUser.objects.filter(id=request.user.id)
product.vendoruser = vendor[0]
product.save()
vendor = CustomUser.objects.get(id=request.user.id)
product_variant = ProductVariants()
product_variant.product_id = product ###ERROR SHOWING IN THIS LINE
product_variant.vendoruser = vendor
product_variant.price = request.POST.get('price')
product_variant.initial_stock = request.POST.get('initial_stock')
product_variant.weight_of_product = request.POST.get('weight_of_product')
product_variant.save()
return redirect('vendor:inventory_display')
else:
productform = ProductForm()
productvariantsform = ProductVariantsForm()
product_variant_images_form = ProductVariantsImagesForm()
return render(request, 'vendor/add_product.html',
{'productform': productform,'product_variant_images_form':product_variant_images_form,
'productvariantsform': productvariantsform})
It's working fine.After product added multiple time the error occurred. how can I get rid of this error.please some help much appreciated.
Its because your product variable isn't set if you don't go inside if product_form.is_valid():,
you could just set a default value before this if statement in order to fix your error.
I hope this helped.
The product variable is only defined if the form is valid. Either you can set a default value for product outside of the if statement or you could move all of the code involving data from the form inside of the if statement.
So I'm expanding on the official tutorial, and I'm trying to let a user create their own poll. I'm having trouble assigning the correct question_id to the choice, so the choice aligns in the database with the question and both can be read off. Here is my view:
def poll_create(request):
if request.method == "POST":
Qform = QuestionForm(request.POST)
Cform = ChoiceForm(request.POST)
if Qform.is_valid():
poll = Qform.save(commit=False)
poll.author = request.user
poll.pub_date = timezone.now()
poll.save()
if Cform.is_valid():
poll = Cform.save(commit=False)
poll.author = request.user
findid = Question.objects.all().order_by("-id")[0] ##Finds the id of the last question in database
poll.question_id = findid.id + 1
poll.save()
return redirect('polls:detail', pk=poll.pk)
else:
Qform = QuestionForm()
Cform = ChoiceForm()
return render(request, 'polls/create.html', {'Qform': Qform, 'Cform': Cform})
So the idea is to have a question form (Qform) which writes the question to the database, and then below on the webpage a choice form (Cform), which writes the answer to the database. I'm really confused about applying a question_id to the Cform. At the moment, I have this line:
findid = Question.objects.all().order_by("-id")[0] ##Finds the id of the last question in database
poll.question_id = findid.id + 1
Which seems like a very hacky attempt to find the last id and assign it to the next one. It doesnt line up because the poll.pk has a different value. I'm at a loss here and don't really understand what's going on. Any help would be appreciated.
Your code is a bit confusing because you are using the variable poll for questions and choices. It would be better to use question and choice instead.
You should check that both forms are valid before you start saving, otherwise you can end up with a question without a choice if the question form is valid but the choice form is invalid.
After you have saved the question, you can get the id with question.id, and you can assign the question to the choice object. There is no need to do a query to find the latest question id.
Putting that together, you have something like:
if Qform.is_valid() and Cform.is_valid():
question = Qform.save(commit=False)
question.author = request.user
question.pub_date = timezone.now()
question.save()
choice = Cform.save(commit=False)
choice.author = request.user
choice.question = question
choice.save()
return redirect('polls:detail', pk=question.pk)
Note also that it's recommended to use lowercase question_form and choice_form, for the form instances, and uppercase QuestionForm and ChoiceForm for the classes.
i'm new to django so i'm sorry for my newbie question
i have a model and i need to let user edit data inside it using django forms or any other way.
look at the image above , i want to show this form ready populated with the data and let user update it.
what is the best way to do this ?
EDIT : here is my views.py code
def exam_Edit(request,examName,number=0):
numner = int(number)
number = int(number)
questionNo = int(numner)
Myexam = models.Exam.objects.get(name = examName)
QuestionsAll = models.Question.objects.filter(exam = Myexam)
myQeustion = Question.objects.filter(exam = Myexam)[nextQuestion]
answer1 = models.Asnwers.objects.filter(question=myQeustion)[0]
answer2 = models.Asnwers.objects.filter(question=myQeustion)[1]
answer3 = models.Asnwers.objects.filter(question=myQeustion)[2]
answer4 = models.Asnwers.objects.filter(question=myQeustion)[3]
# HERE IS MY PROBLEM : the line below creates a form with a data but it doesn't save it to the save object
form = QuestionsEditForm(initial = {'questionText':myQeustion.__unicode__() , 'firstChoiceText':answer1.__unicode__(),'secondChoiceText':answer2.__unicode__(),'thirdChoiceText':answer3.__unicode__(),'forthChoiceText':answer4.__unicode__()})
if request.method =='POST':
#if post
if form.is_valid():
questionText = form.cleaned_data['questionText']
Myexam = Exam.objects.get(name = examName)
myQeustion.questionText = form.cleaned_data['questionText']
answer1.answerText = form.cleaned_data['firstChoiceText']
answer1.save()
answer2.answerText = form.cleaned_data['secondChoiceText']
answer2.save()
answer3.answerText = form.cleaned_data['thirdChoiceText']
answer3.save()
answer4.answerText = form.cleaned_data['forthChoiceText']
answer4.save()
variables = RequestContext(request, {'form':form,'examName':examName,'questionNo':str(nextQuestion)})
return render_to_response('exam_edit.html',variables)
please help
Assuming you are using a ModelForm, use the instance keyword argument, and pass the model you are updating.
So, if you have MyModel and MyModelForm (the latter of which must extend django.forms.ModelForm), then your code snippet might look like:
my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)
And then, when the user sends back data by POST:
form = MyModelForm(request.POST, instance=my_record)
Incidentally, the documentation for ModelForm is here: http://docs.djangoproject.com/en/1.8/topics/forms/modelforms/
I tried this, but there is no update done in django.
def update_product(request):
a= ProductForm(instance=Product.objects.get(product_id =2))#static id
render_to_response('profiles/updateproduct.html',{'form': a},RequestContext(request))
if request.method == "POST":
form = ProductForm(request.POST, instance=a)
if form.is_valid():
j=form.save(commit=False)
j.save
confirmation_message = "product information updated successfully!"
return HttpResponse("hhhh")
else:
form = ProductForm( instance = a )
You never actually call the model's save method since you are missing (). you must supply these in order to call the method.
j = form.save(commit=False)
j.save()
As a side note, since you are not doing anything to the model before saving it, you can simply replace these two lines with
j = form.save()
no real need here for the commit=False part.
I am trying to save a couple ModelFormset forms, but am running into an IntegrityError. Here is the code:
billing_formset = BillingFormSet(request.POST,prefix='billing')
cc_formset = CCFormSet(request.POST,prefix='cc')
if billing_formset.is_valid() and cc_formset.is_valid():
bp = UserBillingProfile()
cc = UserCreditCard()
for form in billing_formset.forms:
billing_profile = form.save(commit=False)
billing_profile.user = request.user
bp = billing_profile.save()
for form in cc_formset.forms:
cc = form.save(commit=False)
cc.billing_profile = bp
cc = form.save()
This code caused the following code:
IntegrityError at [url removed]
(1048, "Column 'user_billing_profile_id' cannot be null")
EDIT: Here is some iterative code that also fixes my typo. I'm running into basically the same problem.
billing_profile_form = billing_formset.forms[0]
cc_form = cc_formset.forms[0]
unsaved_billing_profile = billing_profile_form.save(commit=False)
user_billing_profile = unsaved_billing_profile.save()
unsaved_cc = cc_form.save(commit=False)
unsaved_cc.user_billing_profile = user_billing_profile
cc = unsaved_cc.save()
Problem line gives: "Cannot assign None: "UserCreditCard.user_billing_profile" does not allow null values." It seems unsaved_billing_profile.save() is returning null? Why?
This is kind of crazy; everything seems to be right. I don't get any errors when saving the billing profile. Any ideas on what I should check? Things seem to be going wrong in the second loop, where bp apparently has a value of None.
Thanks in advance.
This means you are trying to save a model instance with user_billing_profile set to None, looks like you are calling "billing_profile" instead of "user_billing_profile".
The "save" method returns None every time commit=False isn't specified. you should instead call something like this:
billing_profile.save()
bp = billing_profile.instance