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.
Related
I am learning python with the below example code and facing the above error. Below is the code. I am using the class componentModel from models.py in the app.py code. and then passing the values to the front end. Not able to find where I am going wrong.
Models.py
class componentModel(db.Model):
__tablename__ = "component"
id = db.Column(db.Integer, primary_key=True)
comp_name = db.Column(db.String())
comp_owner = db.Column(db.String())
def __init__(self, comp_name, comp_owner):
self.comp_name = comp_name
self.comp_owner = comp_owner
def __repr__(self):
return f"{self.comp_name}:{self.comp_owner}"
#validates('name')
def validate_name(self, key, name):
try:
if not comp_name:
comp_name="Not_Valid"
raise AssertionError('No name provided')
if componentModel.query.filter(componentModel.comp_name == comp_name).first():
comp_name="Not_Valid"
raise AssertionError('name is already in use')
if len(comp_name) < 0 or len(comp_name) > 20:
raise AssertionError('Username must be between 5 and 20 characters')
s= " #,#,$,%,!,&,^,*,(,),_,=,-"
for ch in s:
if ch in comp_name:
comp_name="Not_Valid"
raise AssertionError('Invalid country name')
except AssertionError as msg:
return msg
else:
return comp_name
App.py
#app.route('/component/add', methods=['GET', 'POST'])
def componentadd():
error_msg = ''
success_msg = ''
if request.method == 'GET':
return render_template('component/add.html')
if request.method == 'POST':
cursor.execute('SELECT Empnum,Employee_Name FROM empmaster')
empmaster_data = cursor.fetchall()
componentname = request.form['componentname']
componentowner = request.form['componentowner']
comp_result = componentModel(comp_name=componentname)
if str(comp_result) != componentname:
return render_template('component/add.html', msg=comp_result)
else:
db.session.add(comp_result, componentowner)
db.session.add(empmaster_data)
db.session.commit()
success_msg = 'Added successfully !'
return redirect(url_for('componentlist'))
return render_template('component/add.html', empmaster_data=empmaster_data, componentowner =componentowner)
change your code like this
...
if request.method == 'POST':
cursor.execute('SELECT Empnum,Employee_Name FROM empmaster')
empmaster_data = cursor.fetchall()
componentname = request.form['componentname']
componentowner = request.form['componentowner']
comp_result = componentModel(comp_name=componentname, comp_owner=componentowner)
...
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.
enter image description here
i just want to fetch the data from my website and record it to my django databae
this my views.py code :
def index(request):
feature1 = Feature.objects.all()
Appnt = Appointment.objects.all()
if request.method == 'GET':
Appnt.name = request.GET['name']
Appnt.email = request.GET['email']
Appnt.phone = request.GET['phone']
Appnt.Adate = request.GET['date']
Appnt.Dept = request.GET['department']
Appnt.Doc = request.GET['doctor']
Appnt.message = request.GET['message']
contaxt = {
'feature1' : feature1,
'Appointment' : Appnt
}
return render(request, 'index.html', contaxt)
If the parameters can be blank (not passed), use get:
def index(request):
feature1 = Feature.objects.all()
Appnt = Appointment.objects.all()
if request.method == 'GET':
Appnt.name = request.GET.get('name')
Appnt.email = request.GET.get('email')
Appnt.phone = request.GET.get('phone')
Appnt.Adate = request.GET.get('date')
Appnt.Dept = request.GET.get('department')
Appnt.Doc = request.GET.get('doctor')
Appnt.message = request.GET.get('message')
context = {
'feature1' : feature1,
'Appointment' : Appnt
}
return render(request, 'index.html', context)
If the parameters should not be blank, the problem is how the client makes the request.
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!