I want to get value of j in test function, but it returns None, How i get value of this session variable.
This is index function where session variable is created and passing it.
def index(request):
j = ''
if request.method == "POST":
form = InputForm(request.POST)
if form.is_valid():
form.save()
try:
ids = form.cleaned_data['git_Id']
print(ids)
obj = sql()
query = f""" SELECT request_id FROM request_form_db.request_form_mymodel
where git_Id= '{ids}' ;
"""
print(query)
p = obj.fetch_query(query)
print("Query Result", p)
for i in p:
print("Result[0] : ", i[0])
print("Result : ", p)
i = i[0]
j = i
approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}"
print("Url : ", approve_url)
form = InputForm()
else:
form = InputForm()
print('J : ', j)
request.session['j'] = j
print('Request ID Sent : ', j)
return render(request, 'home.html', {'form': form})
This is test function where i want to getting value of j, but here it returns None.
def test(request):
pro = request.session.get('j')
print("Request ID from Index View : ", pro)
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
print("Form is Valid")
selected = form.cleaned_data.get('myfield')
print(selected)
else:
rq = request_id["request_id"]
s = sql()
query = f"""update request_form_db.request_form_mymodel
set is_approved=1
where request_id = '{rq}' """
print(query)
s.update_query(query)
print("Updated Successfully")
form = TestForm()
else:
form = TestForm()
return render(request, 'test.html', {'form': form})
The code is working fine and no error when running the script, but i want to use value of j in test function as well. index and test both are view functionin django.
Related
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()
Here's my code
#login_required
def upload(request):
form_type = ''
transcript = Transcript()
transcript.file_path = ''
if request.method == 'POST':
if 'file_form' in request.POST:
file_form = FileForm(request.POST, request.FILES)
if file_form.is_valid():
path = handle_uploaded_file(request.FILES['file'], request.user)
transcript.file_path = path
transcript.user = request.user
export_form = InfoForm()
form_type = 'info_form'
elif 'info_form' in request.POST:
if transcript.file_path:
info_form = InfoForm(request.POST)
if info_form.is_valid():
transcript.user = request.user
transcript.title = info_form.cleaned_data.get('title')
transcript.instructions = info_form.cleaned_data.get('instructions')
transcript.save()
return HttpResponseRedirect('thanks')
else:
raise ValueError('Transcript object has no file path attribute')
else:
export_form = FileForm()
form_type = 'file_form'
return render(request, 'transcription/upload.html', {'form': export_form, 'form_type': form_type})
always, the file-form is called before the info-form, so the code in the if statement
if transcript.file_path:
#...
should always execute. But the ValueError always gets raised, meaning transcript.file_path is reset. How does this happen, and how can it be fixed?
file_form and info_form in POST are names of the different submit buttons, so I know which form I am dealing with.
def handle_uploaded_file(file, user):
id = randint(0, 10000)
user_dir = settings.MEDIA_ROOT + '/' + str(user.id).replace(".", "") + '/'
path = user_dir + file.name.replace(".mp3", str(id) + ".mp3")
if not os.path.exists(user_dir):
os.makedirs(user_dir)
with open(path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
file = File(destination)
info = {'path': path, 'file': file}
return path
So it was a rookie mistake.
I didn't know that during each post request the whole view gets called again.
So I just initialized my variables
form_type = ''
transcript = Transcript()
transcript.file_path = ''
outside the view and voila!
What my problem is this code is displaying records whether there is 1 record or many...But i want to delete if there is 1 record....
Any advise for good code writing is obliged....
Here is my view
def delete(request):
form = SearchForm(request.POST)
searched_data = Information.objects.filter(name="full_name").count()
d_data = None
if form.is_valid():
if (searched_data == 1):
d_data = Information.objects.filter(name= form.cleaned_data.get('full_name')).delete()
else:
d_data = Information.objects.filter(name=form.cleaned_data.get('full_name'))
context = {
'form': form,
'd_data': d_data,
}
return render(request, 'delete.html', context)
I would not do anything unless the form is valid:
if form.is_valid():
d_data = Information.objects.filter(name=form.cleaned_data.get('full_name'))
if len(d_data) == 1:
d_data.delete()
d_data = None
else:
d_data = None
context = {
'form': form,
'd_data': d_data,
}
return render(request, 'delete.html', context)
Note: I set d_data to None after it's been deleted.
On wheter to use d_data.count() or len(d_data), please see this
Here is my code:
def render_new_article(request):
if request.method == "POST":
step_number = int(request.POST.get("step_number", ""))
new_article = request.session['new_article']
if 'prev' in request.POST:
step_number = step_number - 1
elif 'next' in request.POST:
if step_number == 0:
print type(new_article.steps)
new_article.title = request.POST.get("title", "")
new_article.description = request.POST.get(
"description", "")
else:
print type(new_article.steps)
new_article.steps[int(step_number)] = request.POST.get(
"step_description", "")
request.session['new_article'] = new_article
step_number = step_number + 1
elif 'publish' in request.POST:
new_article.draft = False
draft_article = Article.objects.filter(
parent_id=new_article.pk).exclude(parent_id=None)[:1]
if len(draft_article) > 0:
draft_article[0].delete()
new_article.full_clean()
new_article.save()
del request.session['new_article']
return HttpResponseRedirect("/article?articleid=" + str(new_article.pk))
c = RequestContext(request, {
'user': request.user, 'step_number': step_number,
'article': new_article,
})
return render_to_response("new_article.html", c)
else:
# This function renders the home.
article_id = request.GET.get('article_id', '')
user = User.objects.get(id=request.user.pk)
app_user = AppUser.objects.get(user=user)
new_article = Article(created_by=app_user, steps={}, id=None,
draft=True, parent_id=None, pk=None)
if article_id.strip() != '':
new_article = Article.objects.get(pk=article_id)
new_article.steps = ast.literal_eval(new_article.steps)
print "getting article from DB"
request.session['new_article'] = new_article
c = RequestContext(request, {
'user': request.user, 'step_number': 0,
'article': new_article,
})
return render_to_response("new_article.html", c)
This gives me an error whenever I try to run it on Openshift, but it works fine locally. I have checked the Django Version and Python Version also.
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().