views.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. from django.shortcuts import render, redirect, get_object_or_404, HttpResponse, HttpResponseRedirect
  2. from django.core.exceptions import ObjectDoesNotExist
  3. from django.template import loader, Context
  4. from django.template.loader import get_template
  5. import json
  6. # Decorator to use built-in authentication system
  7. from django.contrib.auth.decorators import login_required
  8. from django.shortcuts import render, redirect
  9. from django.core.urlresolvers import reverse
  10. from django.core import serializers
  11. # Used to generate a one-time-use token to verify a user's email address
  12. from django.contrib.auth.tokens import default_token_generator
  13. # Used to send mail from within Django
  14. from django.core.mail import send_mail
  15. # Used to create and manually log in a user
  16. from django.contrib.auth.models import User
  17. from django.contrib.auth import login, authenticate
  18. # Django transaction system so we can use @transaction.atomic
  19. from django.db import transaction
  20. from socialnetwork.s3 import s3_upload, s3_delete
  21. from socialnetwork.models import *
  22. from socialnetwork.forms import RegistrationForm, EditProfile, EditRegistrationForm, AddPostForm
  23. @login_required
  24. def home(request):
  25. posts = Posts.objects.all().order_by('-date_time')
  26. comments = Comment.objects.all()
  27. addpost_form=AddPostForm(request.POST)
  28. if (posts):
  29. finalpost = posts[0]
  30. profiles = Profile.objects.all()
  31. context = {'posts' : posts,'finalpost' : finalpost.id, 'comments':comments, 'profiles':profiles, 'addpost_form':addpost_form}
  32. return render(request, 'socialnetwork/globalstream.html', context)
  33. profiles = Profile.objects.all()
  34. context = {'posts' : posts, 'comments':comments, 'profiles':profiles, 'addpost_form':addpost_form}
  35. return render(request, 'socialnetwork/globalstream.html', context)
  36. def redirect(request):
  37. return HttpResponseRedirect('socialnetwork')
  38. @login_required
  39. def add_comment(request):
  40. context={}
  41. errors=[]
  42. if not 'commenttext' in request.GET or not request.GET.get('commenttext'):
  43. errors.append('Enter a comment!')
  44. else:
  45. commenttext=request.GET.get('commenttext')
  46. post_id=request.GET.get('post_id')
  47. user=User.objects.get(id=request.user.id)
  48. post_attached_to_user = Posts.objects.get(id=post_id).user
  49. profile=Profile.objects.get(user=request.user)
  50. currpost = Posts.objects.get(id=post_id)
  51. new_comment=Comment()
  52. new_comment.comment_text=commenttext
  53. new_comment.comment_datetime=timezone.now()
  54. new_comment.comment_by=profile
  55. new_comment.comment_post=currpost
  56. new_comment.save()
  57. t = get_template('socialnetwork/commenttemplate.html')
  58. comments = Comment.objects.filter(id=new_comment.id)
  59. c = Context({'comments': comments})
  60. rendered = t.render(c)
  61. response_text = json.dumps({'html': rendered})
  62. return HttpResponse(response_text, content_type='application/json')
  63. return HttpResponse("", content_type='application/json')
  64. def get_list_json(request):
  65. response_text = serializers.serialize('json', Posts.objects.all())
  66. return HttpResponse(response_text, content_type='application/json')
  67. @login_required
  68. def editprofile(request):
  69. context={}
  70. user=request.user
  71. if request.method == 'GET':
  72. #populating it with the values saved in the database
  73. context['registration_form'] = EditRegistrationForm(initial={'first_name': user.first_name,
  74. 'last_name': user.last_name})
  75. profile_of_user = User.objects.get(id=user.id)
  76. userprofileinfo = Profile.objects.get(user=profile_of_user)
  77. addpost_form = AddPostForm(request.POST)
  78. context['addpost_form'] = addpost_form
  79. context['profile_form'] = EditProfile(instance=userprofileinfo)
  80. return render(request, 'socialnetwork/editprofile.html', context)
  81. registration = User.objects.get(id=user.id)
  82. registration_form=EditRegistrationForm(request.POST)
  83. edit_profile = Profile.objects.get(user=registration)
  84. profile_form = EditProfile(request.POST, request.FILES, instance=edit_profile)
  85. if not registration_form.is_valid():
  86. return render(request, 'socialnetwork/editprofile.html', {'registration_form':registration_form, 'profile_form':profile_form})
  87. registration.first_name=registration_form.cleaned_data['first_name']
  88. registration.last_name=registration_form.cleaned_data['last_name']
  89. registration.save()
  90. if not profile_form.is_valid():
  91. return render(request, 'socialnetwork/editprofile.html', {'registration_form':registration_form, 'profile_form':profile_form})
  92. if profile_form.cleaned_data['picture']:
  93. url = s3_upload(profile_form.cleaned_data['picture'], registration)
  94. profile=Profile.objects.get(user=request.user)
  95. profile.picture_url = url
  96. profile_form.save()
  97. posts = Posts.objects.all().order_by('date_time').reverse()
  98. profiles= Profile.objects.all()
  99. comments = Comment.objects.all()
  100. addpost_form = AddPostForm(request.POST)
  101. context['addpost_form']=addpost_form
  102. context = {'posts' : posts, 'comments':comments, 'profiles':profiles, 'addpost_form':addpost_form}
  103. return render(request, 'socialnetwork/globalstream.html', context)
  104. @transaction.atomic
  105. def register(request):
  106. context = {}
  107. print (request.FILES)
  108. # Just display the registration form if this is a GET request.
  109. if request.method == 'GET':
  110. context['registration_form'] = RegistrationForm()
  111. context['profile_form'] = EditProfile()
  112. return render(request, 'socialnetwork/register.html', context)
  113. # Creates a bound form from the request POST parameters and makes the
  114. # form available in the request context dictionary.
  115. registration_form = RegistrationForm(request.POST)
  116. profile_form = EditProfile(request.POST, request.FILES)
  117. # Validates the form.
  118. if not registration_form.is_valid():
  119. print ("reg form not valid")
  120. return render(request, 'socialnetwork/register.html', {'registration_form':registration_form, 'profile_form':profile_form})
  121. if not profile_form.is_valid():
  122. print ("profile form not valid")
  123. return render(request, 'socialnetwork/register.html', {'registration_form':registration_form, 'profile_form':profile_form})
  124. # At this point, the form data is valid. Register and login the user.
  125. new_user = User.objects.create_user(username=registration_form.cleaned_data['username'],
  126. password=registration_form.cleaned_data['password1'],
  127. first_name=registration_form.cleaned_data['first_name'],
  128. last_name=registration_form.cleaned_data['last_name'],
  129. email=registration_form.cleaned_data['email'])
  130. # Mark the user as inactive to prevent login before email confirmation.
  131. new_user.is_active = False
  132. new_user.save()
  133. new_profile = Profile()
  134. new_profile.user = new_user
  135. new_profile.age=profile_form.cleaned_data['age']
  136. new_profile.bio=profile_form.cleaned_data['bio']
  137. if profile_form.cleaned_data['picture']:
  138. url = s3_upload(profile_form.cleaned_data['picture'], new_user.id)
  139. new_profile.picture_url = url
  140. new_profile.save()
  141. # Generate a one-time use token and an email message body
  142. token = default_token_generator.make_token(new_user)
  143. email_body = """
  144. Welcome to your Social Network. Please click the link below to
  145. verify your email address and complete the registration of your account:
  146. http://%s%s
  147. """ % (request.get_host(),
  148. reverse('confirm', args=(new_user.username, token)))
  149. send_mail(subject="Verify your email address",
  150. message= email_body,
  151. from_email="abiyer@andrew.cmu.edu",
  152. recipient_list=[new_user.email])
  153. context['email'] = registration_form.cleaned_data['email']
  154. return render(request, 'socialnetwork/needsconfirmation.html', context)
  155. @transaction.atomic
  156. def confirm_registration(request, username, token):
  157. user = get_object_or_404(User, username=username)
  158. # Send 404 error if token is invalid
  159. if not default_token_generator.check_token(user, token):
  160. raise Http404
  161. # Otherwise token was valid, activate the user.
  162. user.is_active = True
  163. user.save()
  164. return render(request, 'socialnetwork/confirmed.html', {})
  165. @login_required
  166. @transaction.atomic
  167. def add_post(request):
  168. errors = []
  169. context={}
  170. addpost_form = AddPostForm(request.POST)
  171. context['addpost_form']=addpost_form
  172. if not addpost_form.is_valid():
  173. print ("Add post form not valid")
  174. comments = Comment.objects.all()
  175. posts = Posts.objects.all().order_by('-date_time')
  176. if (posts):
  177. finalpost = posts[0]
  178. profiles = Profile.objects.all()
  179. context = {'posts' : posts,'finalpost' : finalpost.id, 'comments':comments, 'profiles':profiles, 'addpost_form':addpost_form}
  180. return render(request, 'socialnetwork/globalstream.html', context)
  181. if not addpost_form.cleaned_data['post_content']:
  182. errors.append('Enter a post!')
  183. else:
  184. if(len(addpost_form.cleaned_data['post_content'])>160):
  185. errors.append("It should be less than 160 characters")
  186. else:
  187. new_post_user=request.user
  188. new_post_datetime = timezone.now()
  189. new_post= Posts(post_content=addpost_form.cleaned_data['post_content'],user=new_post_user,date_time=new_post_datetime)
  190. new_post.save()
  191. posts = Posts.objects.all().order_by('date_time').reverse()
  192. finalpost = posts[0]
  193. comments = Comment.objects.all()
  194. profiles = Profile.objects.all()
  195. context = {'posts' : posts,'errors' :errors,'finalpost' : finalpost.id, 'comments':comments, 'profiles':profiles, 'addpost_form':addpost_form}
  196. return render(request, 'socialnetwork/globalstream.html', context)
  197. @login_required
  198. def refresh_page(request):
  199. context={}
  200. if(request.GET.get('id')):
  201. finalpost_id=request.GET.get('id')
  202. else:
  203. errors.append("Enter a valid input!")
  204. raise Http404
  205. posts=Posts.objects.all().filter(id__gt=finalpost_id).order_by('-date_time')
  206. if (posts):
  207. finalpost = posts[0]
  208. t = get_template('socialnetwork/poststemplate.html')
  209. c = Context({'posts': posts, 'finalpost': finalpost})
  210. rendered = t.render(c)
  211. profiles = Profile.objects.all()
  212. response_text = json.dumps({'html': rendered, 'finalpost':finalpost.id})
  213. return HttpResponse(response_text, content_type='application/json')
  214. c = Context({'finalpost': finalpost_id})
  215. t = get_template('socialnetwork/poststemplate.html')
  216. rendered = t.render(c)
  217. response_text = json.dumps({'finalpost':finalpost_id})
  218. return HttpResponse(response_text, content_type='application/json')
  219. @login_required
  220. def profile(request,user_id):
  221. errors=[]
  222. try:
  223. user=User.objects.get(id=user_id)
  224. posts=Posts.objects.filter(user=user).order_by('date_time').reverse()
  225. profile=Profile.objects.get(user=user)
  226. context = {'user':user,'posts':posts, 'profile':profile, 'current_user':request.user}
  227. return render(request,'socialnetwork/profile.html',context)
  228. except ObjectDoesNotExist:
  229. errors.append('The profile you asked for does not exist.')
  230. posts = Posts.objects.all().order_by('date_time').reverse()
  231. profiles = Profile.objects.all()
  232. comments = Comment.objects.all()
  233. addpost_form=AddPostForm(request.POST)
  234. context = {'posts' : posts, 'errors' : errors, 'profiles':profiles, 'comments':comments, 'addpost_form':addpost_form}
  235. return render(request,'socialnetwork/globalstream.html',context)
  236. @login_required
  237. def get_photo(request, id):
  238. profile = get_object_or_404(Profile, id=id)
  239. if not profile.picture:
  240. raise Http404
  241. return HttpResponse(profile.picture, content_type=profile.content_type)
  242. @login_required
  243. @transaction.atomic
  244. def follow(request,user_id):
  245. context={}
  246. errors=[]
  247. try:
  248. user=User.objects.get(id=user_id)
  249. profile=Profile.objects.get(user=user)
  250. posts=Posts.objects.filter(user=user).order_by('date_time').reverse()
  251. current_user = request.user
  252. Profile.objects.get(user=current_user).followusers.add(user)
  253. current_user.save()
  254. context = {'user':user,'posts':posts, 'profile':profile,'messages1':"test"}
  255. return render(request,'socialnetwork/profile.html',context)
  256. except ObjectDoesNotExist:
  257. errors.append('You cannot follow this user.')
  258. posts = Posts.objects.all().order_by('date_time').reverse()
  259. profiles = Profile.objects.all()
  260. comments = Comment.objects.all()
  261. addpost_form=AddPostForm(request.POST)
  262. context = {'posts' : posts, 'errors' : errors, 'profiles':profiles, 'comments':comments, 'addpost_form':addpost_form}
  263. return render(request,'socialnetwork/globalstream.html',context)
  264. @login_required
  265. def followerstream(request):
  266. context = {}
  267. user=request.user
  268. posts=Posts.objects.filter(user__in=Profile.objects.get(user=user).followusers.all()).order_by('-date_time')
  269. context = {'posts' : posts}
  270. return render(request, 'socialnetwork/followerstream.html', context)
  271. @login_required
  272. @transaction.atomic
  273. def unfollow(request,user_id):
  274. context={}
  275. errors=[]
  276. try:
  277. user=User.objects.get(id=user_id)
  278. profile=Profile.objects.get(id=user_id)
  279. posts=Posts.objects.filter(user=user).order_by('date_time').reverse()
  280. current_user = request.user
  281. Profile.objects.get(user=current_user).followusers.remove(user)
  282. current_user.save()
  283. context = {'user':user,'posts':posts, 'profile':profile, 'messages2':"test"}
  284. return render(request,'socialnetwork/profile.html',context)
  285. except ObjectDoesNotExist:
  286. errors.append('You cannot unfollow this user.')
  287. posts = Posts.objects.all().order_by('date_time').reverse()
  288. profiles = Profile.objects.all()
  289. comments = Comment.objects.all()
  290. addpost_form=AddPostForm(request.POST)
  291. context = {'posts' : posts, 'errors' : errors, 'profiles':profiles, 'comments':comments, 'addpost_form':addpost_form}
  292. return render(request,'socialnetwork/globalstream.html',context)