Render data on two templates from one function Django - django

Hi i need to render the data on two templates from one function my code is
def stylepoints(request):
a=Product.objects.all()[:3]
cursor = connection.cursor()
try:
cursor.execute("SELECT facebook_id,name FROM django_facebook_facebookuser WHERE user_id = %s ORDER BY RAND() LIMIT 1",[request.user.id])
except Exception as e:
return HttpResponse("error in fetching Friends")
rows_affected=cursor.rowcount
if rows_affected > 0:
row1 = cursor.fetchall()
row12 = row1[0]
else:
row12 = ''
value = request.user.id
cursor12 = connection.cursor()
cursor12.execute("SELECT Distinct email FROM myaccount_invitation WHERE reference_id = %s AND status = 1 AND invitation_type = 2",[value])
friend = cursor12.fetchall()
if friend:
friends = friend[0]
return render_to_response('swf.html',{'a':a,'userf':row12,'friendshow':friend} , context_instance=RequestContext(request))
like in this i have send a data to one template name as
swf.html
but i need to send the data also to another template such as
swf2.html
please tell me can i render a data to two templates

def view1(request):
template_name='swf1.html'
return stylepoints(request, template_name)
def view2(request):
template_name='swf2.html'
return stylepoints(request, template_name)
def stylepoints(request, template_name):
a=Product.objects.all()[:3]
cursor = connection.cursor()
try:
cursor.execute("SELECT facebook_id,name FROM django_facebook_facebookuser WHERE user_id = %s ORDER BY RAND() LIMIT 1",[request.user.id])
except Exception as e:
return HttpResponse("error in fetching Friends")
rows_affected=cursor.rowcount
if rows_affected > 0:
row1 = cursor.fetchall()
row12 = row1[0]
else:
row12 = ''
value = request.user.id
cursor12 = connection.cursor()
cursor12.execute("SELECT Distinct email FROM myaccount_invitation WHERE reference_id = %s AND status = 1 AND invitation_type = 2",[value])
friend = cursor12.fetchall()
if friend:
friends = friend[0]
return render_to_response(template_name,{'a':a,'userf':row12,'friendshow':friend} , context_instance=RequestContext(request))

Related

Calling a function name inside a function in Django Rest Framework

I have tried to call the two method inside the function where I couldn't able to call those method. I have tried few approaches but not succeeded. Here, What I have tried
"UserStartShift", "UserStopShift" are the API functions which have GET and POST method in it. These API are working fine individually, I wanted to return a different response using the conditional statement.
views.py:
# startshift
#api_view(['GET'])
def UserStartShift(request):
if request.method == 'POST':
UserId = request.data.get('UserId')
Ip = request.data.get('Ip')
PortNumber = request.data.get('PortNumber')
print("UserId-->", UserId)
print("Ip-->", Ip)
print('Portnumber-->', PortNumber)
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[Usp_StartShift] #UserId=%s, #IP=%s, #Port=%s', (UserId, Ip, PortNumber,))
return Response(True, status=status.HTTP_200_OK)
# endshift
#api_view(['GET'])
def UserStopShift(request, UserId):
try:
users = tblUserShiftDetails.objects.filter(UserId=UserId)
except tblUserShiftDetails.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_StopShift] #UserId=%s',(UserId,))
return Response(True)
#UserShiftDetailsView
#api_view(['GET'])
def UserShiftDetailsView(request, userid):
try:
users = tblUserShiftDetails.objects.filter(UserId=userid)
except tblUserShiftDetails.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
if UserStartShift == True:
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] #UserId=%s',(userid,))
result_set = cursor.fetchall()
for row in result_set:
row = row[0]
return Response({"IsStarted":True,"EstimatedShifEnd":(row + datetime.timedelta(hours=9)).strftime('%d-%m-%Y %H:%M %p'),"ReasonforAccess": "null"})
elif UserStopShift == True :
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] #UserId=%s',(userid,))
result_set = cursor.fetchall()
for row in result_set:
row = row[0]
return Response({"IsStarted":False,"EstimatedShifEnd":"null","ReasonforAccess": "null"})

How to access the return value from outside the function in Django

I wanted to access the value of the function outside in Django rest framework. I have checked this function which return value but I want to call that return value in another function.
I have tried this approach where I'm getting output ticketid as 'None'
views.py:
def GetUserTaskId(request):
userid = request.data.get('UserId')
ReportId = request.data.get('ReportId')
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetUserTaskId] #UserId=%s, #Ticket=%s', (userid, ReportId))
result_set =cursor.fetchall()
for row in result_set:
TaskId=row[0]
return Response({"TaskId":TaskId})
def inserttask(request):
ticketId = GetUserTaskId(request)
print("ticketId--->",ticketId)
if ticketId is not None:
/***somecode***/
Why not do something like this?
# common.py
def get_task_id(user_id, report_id):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[USP_GetUserTaskId] #UserId=%s, #Ticket=%s', (user_id, report_id))
result_set = cursor.fetchall()
for row in result_set:
TaskId=row[0]
return TaskId
# views.py
from .common import get_task_id
def GetUserTaskId(request):
userid = request.data.get('UserId')
ReportId = request.data.get('ReportId')
task_id = get_task_id(userid, ReportId) # call our function
return Response({"TaskId": task_id})
def inserttask(request):
userid = request.data.get('UserId')
ReportId = request.data.get('ReportId')
ticketId = get_task_id(userid, ReportId) # call our function
print("ticketId--->",ticketId)
if ticketId is not None:
pass
# somecode

How i can send recently save data into template in same view function in django

view.py
In the below code, I'm saved my recent data in model and create a dictionary order = order.save() because I can use this in my template. When I run the code the order is having ```None`` value.
What i can do for it.
def post(self, request, product_id):
product = Product.objects.get(id=product_id)
if request.POST['address'] and request.POST['quantity']:
order = Order()
order.or_proName = product.pro_name
order.or_companyName = product.companyName
order.or_quatity = request.POST['quantity']
order.or_quatity = int( order.or_quatity)
orderPrice = order.or_quatity*product.Sale_Price
order.or_bill = 100 + orderPrice
order.pub_date = timezone.datetime.now()
product.Quantity -= order.or_quatity
product.save()
order = order.save()
args = {'order':order}
return render(request, self.red_templateName, args)
The django.db.models.Model.save() does not usually return anything (unlike the django.forms.Form.save() function)
Remove the line order = order.save() from your code
You can see how the Model.save() is implemented here https://github.com/django/django/blob/master/django/db/models/base.py#L666
You should not assign the result of the .save() function to order, since that is indeed None. Just .save() the order, and use the order function further in your view:
def post(self, request, product_id):
product = Product.objects.get(id=product_id)
if request.POST['address'] and request.POST['quantity']:
order = Order()
order.or_proName = product.pro_name
order.or_companyName = product.companyName
order.or_quatity = request.POST['quantity']
order.or_quatity = int( order.or_quatity)
orderPrice = order.or_quatity*product.Sale_Price
order.or_bill = 100 + orderPrice
order.pub_date = timezone.datetime.now()
product.Quantity -= order.or_quatity
product.save()
order.save()
args = {'order':order}
return render(request, self.red_templateName, args)
You should however define an else case as well, since the post method is supposed to always return a HttpResponse object, for example an error mesage.

i want to show duplicate value error on front end

i have an query_name field in database. i want that every value should be unique so i changed it constraint and add unique= true.
now i want that if user enter the duplicate value then error duplicate value show to the user. currently error is showing only in backend
here is my code in python
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
data_dict = request.POST.dict()
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html', context = None)
database :
query_name = models.CharField(max_length=100,unique= True, default= True)
code 2 :
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
querydata = ReportCreationData.objects.all()
querydata_list = []
querydata_dict = {'query_name':''}
for data in querydata:
querydata_dict['query_name'] = data.query_name
print ('querydata_dict', querydata_dict)
data_dict = request.POST.dict()
query_name = data_dict['query_name'],
print ('query_name', query_name)
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
if (query_name == querydata_dict).exists():
raise ('already exists')
else:
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html')
with code 2 getting error:
AttributeError: 'bool' object has no attribute 'exists'
Please help
Thanks
You can try before inserting the data,run a select query from database and apply where clause on your query_name with your current value.So by this you can get duplicate records.

django save not working as update in views.py with model having an overridden save

I've looked at all the related answers but none fixed my issue. I'm trying to save an object that's already created with no luck. I could see the view getting executed and the values I updated for the object but changes are not reflecting in the database. Here is the code snippet of the view and the model.
views.py
class Workspace(_LoggedInMixin, View):
def get(self, request):
user = self.request.user
components = ComponentModel.objects.filter(Q(user=user) | Q(user=None)).order_by('time')
component_status = request.session.get('component', None)
request.session['component'] = None
params = dict(components=components, status=component_status)
return render(request, 'workspace.html', params)
def post(self, request):
data = request.POST
formtype = data['form-type']
error = None
user = self.request.user
if formtype == 'component':
if data['action'] == 'create':
try:
if not os.path.exists('D:/' + self.request.user.username):
os.makedirs('D:/' + self.request.user.username)
cparent = ComponentModel.objects.get(pk=data['cparent'])
component = ComponentModel(user=user, name=data['cname'], time=dt.now(), stats=data['cstats'],
output=data['coutput'], parent=cparent)
component.save()
file = open('D:/' + self.request.user.username + '/' + str(component.id) + '.py', 'w+')
usercode = data['usercode']
usercode = "\n".join(usercode.split("\r\n"))
file.write(usercode)
component.codefile = 'D:/' + self.request.user.username + '/' + str(component.id) + '.py'
component.save()
request.session['component'] = {'name': data['cname'], 'message': 'Component created successfully!'}
except Exception as e:
component.delete()
error = e.message
elif data['action'] == 'delete':
try:
c = ComponentModel.objects.get(pk=data['compid'])
cname = c.name
c.delete()
os.remove('D:/' + self.request.user.username + '/' + data['compid'] + '.py')
request.session['component'] = {'name': cname, 'message': 'Component deleted successfully!'}
except Exception as e:
error = e.message
elif data['action'] == 'save':
try:
if not os.path.exists('D:/' + self.request.user.username):
os.makedirs('D:/' + self.request.user.username)
cparent = ComponentModel.objects.get(pk=data['cparent'])
component = ComponentModel.objects.get(pk=data['compid'])
component.user = user
component.name = data['cname']
component.time = dt.now()
component.stats = data['cstats']
component.output = data['coutput']
component.parent = cparent
component.save()
print component
file = open('D:/' + self.request.user.username + '/' + str(component.id) + '.py', 'w+')
usercode = data['usercode']
usercode = "\n".join(usercode.split("\r\n"))
file.write(usercode)
request.session['component'] = {'name': data['cname'], 'message': 'Component saved successfully!'}
except Exception as e:
error = e.message
if error is not None:
components = ComponentModel.objects.filter(Q(user=user) | Q(user=None)).order_by('time')
params = dict(error=error, components=components)
return render(request, 'workspace.html', params)
return redirect('/workspace')
models.py
class ComponentModel(models.Model):
class Meta:
# overriding the default table name with the following name
db_table = 'components'
verbose_name = 'components'
get_latest_by = 'time'
user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=255)
time = models.DateTimeField(db_column='created_on')
codefile = models.CharField(max_length=100, db_column='code_file_name', null=True)
stats = models.TextField(db_column='statistical_fields', null=True)
output = models.TextField(db_column='output_fields')
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
def save(self, *args, **kwargs):
try:
super(ComponentModel, self).save(self, *args, **kwargs)
except Exception as e:
return "Something went wrong while saving the component. Details - %s" % e.message
def __str__(self):
return "{id: %s, name: %s, user: %s, time: %s, parent: %s}" % (
self.id, self.name, self.user, self.time, self.parent)
The second save call in data['action'] == 'create' and the save call in data['action'] == 'save' are not updating the database. I appreciate any help. Thank you.
Your super call is incorrect. Update so that self is not called as a method argument - as you have it written it will always fail.
In addition, you are not raising the exception when a save is not completed, so you have no idea if there was an error unless viewing the std output. You probably want this to actually raise an error.
Update as such -
def save(self, *args, **kwargs):
try:
super(ComponentModel, self).save(*args, **kwargs)
except Exception as e:
raise Exception("Something went wrong while saving the component. Details - %s" % (e.message,))