def image_create(request): if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): new_item = form.save(commit=False) # assing current user to the item new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image added successfully') return redirect(new_item.get_absolute_url()) else: # build form with data provided by the bookmarklt via GET form = ImageCreateForm(data=request.GET) return render( request, 'images/image/create.html', {'section': 'images', 'form': form} )
def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create( user_from=request.user, user_to=user ) create_action(request.user, 'is following', user) else: Contact.objects.filter( user_from=request.user, user_to=user ).delete() create_action(request.user, 'is unfollowing', user) return JsonResponse({'status': 'ok'}) except User.DoesNotExist: return JsonResponse({'status': 'ko'}) return JsonResponse({'status': 'ko'})
def image_create(request): ''' View for creating an Image using the JavaScript Bookmarklet. ''' if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # assign current user to the item new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image added successfully!') # redirect to new created item detailed view return redirect(new_item.get_absolute_url()) else: # build form with data provided by the bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
def post(request, id): post = get_object_or_404(Post, id=int(id), status='P') if not request.session.get('viewed'): post.views += 1 post.save() request.session['viewed'] = True comments = post.comments.all().filter(active=True) if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.name = request.user new_comment.save() create_action(request.user, '评论了', post) return redirect(reverse('blog:post', args=[id,])) #else: comment_form = CommentForm() context = {'post': post, 'comments': comments, 'comment_form': comment_form} return render(request, 'blog/post.html', context)
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() profile = Profile.objects.create(user=new_user) create_action(new_user, 'has created an account') return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form})
def image_create(request): if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, "Image added successfully") return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
def image_like(request): image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Image.objects.get(id=image_id) if action == 'like': image.users_like.add(request.user) create_action(request.user, 'likes', image) else: image.users_like.remove(request.user) except: pass return JsonResponse({'status': 'ko'})
def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: user = User.objects.get(pk=user_id) if action == 'follow': request.user.following.add(user) create_action(request.user, FOLLOW, user) elif action == 'unfollow': request.user.following.remove(user) else: return JsonResponse(JSON_FAIL(STATUS_INVALID_ARGUMENTS)) return JsonResponse({'status': True}) return JsonResponse(JSON_FAIL(STATUS_INVALID_ARGUMENTS), status=400)
def user_follow(request): user_id = request.POST.get("id") action = request.POST.get("action") if user_id and action: try: user = User.objects.get(id=user_id) if action == "follow": Contact.objects.get_or_create(user_from=request.user, user_to=user) create_action(request.user, "is following", user) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({"status": "ok"}) except User.DoesNotExist: return JsonResponse({"status": "ko"}) return JsonResponse({"status": "ko"})
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() profile = Profile.objects.create(user=new_user) create_action(new_user, 'has created an account') messages.success(request, 'You have been successfully registered!') return redirect('login') else: messages.error(request, 'Error while registering User!') else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form' : user_form})
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new User object, but don't save it just yet new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() # '.create()' is a convinience method for creating an object and saving it in one step profile = Profile.objects.create(user=new_user) # create the user Profile create_action(new_user, 'has created an account') # NOTE: this will render the template wihtout redirecting the user to 'account/register_done.html' URL return render(request, 'account/register_done.html', {'user':new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form':user_form})
def image_create(request): if request.method == 'POST': form = ImageCreateForm(request.POST, request.FILES) if form.is_valid(): new_image = form.save(commit=False) new_image.user = request.user new_image.slug = slugify(request.user) new_image.save() create_action(request.user, 'bookmarked image', new_image) messages.success(request, 'Image added successfully!') return redirect(new_image.get_absolute_url()) else: form = ImageCreateForm() return render(request, 'images/image/create.html', {'section' : 'images', 'form' : form})
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Set the chosen password new_user.set_password(user_form.cleaned_data['password']) # Save the User object new_user.save() # Create the user profile profile = Profile.objects.create(user=new_user) create_action(new_user, 'has created an account') return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form})
def topic_collect(request): topic_id = request.POST.get('id') action = request.POST.get('action') if topic_id and action: topic = FoodTopic.objects.get(pk=topic_id) if action == 'collect': topic.users_collect.add(request.user) topic.total_collects += 1 create_action(request.user, COLLECT, topic) elif action == 'uncollect': topic.users_collect.remove(request.user) topic.total_collects -= 1 else: return JsonResponse(JSON_FAIL(STATUS_INVALID_ARGUMENTS)) topic.save() return JsonResponse(JSON_SUCCESS) return JsonResponse(JSON_FAIL(STATUS_INVALID_ARGUMENTS), status=400)
def register(request): if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Utworzenie nowego obiektu użytkownika, # ale jeszcze nie zapisujemy go w bazie danych. new_user = user_form.save(commit=False) # Ustawienie wybranego hasła. new_user.set_password(user_form.cleaned_data["password"]) # Zapisanie obiektu User. new_user.save() # Utworzenie profilu użytkownika. profile = Profile.objects.create(user=new_user) create_action(new_user, "utworzył konto") return render(request, "account/register_done.html", {"new_user": new_user}) else: user_form = UserRegistrationForm() return render(request, "account/register.html", {"user_form": user_form})
def image_create(request): if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) # assign user to item new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image saved') # redirect to new created item return redirect(new_item.get_absolute_url()) else: # build form with data from bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
def collecting(request): post_id = int(request.POST.get('id')) action = request.POST.get('action') if post_id and action: try: post = Post.objects.get(id=post_id) if action == 'collect': new_item, status = Collection.objects.get_or_create(user=request.user) new_item.posts.add(post) create_action(request.user, '收藏了', post) else: # 下面的这个语句错了,会把user的collections直接给删掉,而不是某一收藏内容 # Collection.objects.filter(user=request.user, posts=post).delete() Collection.objects.get(user=request.user).posts.remove(post) create_action(request.user, '取消收藏', post) return JsonResponse({'status': 'ok'}) except: return JsonResponse({'status': 'ko'}) return JsonResponse({'status': 'ko'})
def edit(request): if request.method == "POST": user_form = UserForm(instance=request.user, data=request.POST) profile_form = ProfileForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() create_action(request.user, '修改了', request.user.profile) messages.success(request, '成功啦') else: messages.error(request, user_form.errors) return redirect(reverse('accounts:edit')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'accounts/admin/edit.html', {'user_form': user_form, 'profile_form': profile_form})
def post_index(request): if request.method == 'POST': if request.user.is_authenticated(): form = ForumPostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.creator = request.user post.save() create_action(request.user, POST, post) return HttpResponseRedirect(reverse('forum:index')) else: return HttpResponseRedirect(reverse('user:login')) else: order = request.GET.get('order', 'default') if not order in ('time', 'all'): order = 'default' cache_key = REDIS_POSTS_KEY.format(order) query_set = ForumPost.objects.defer('content', 'created', 'updated') if order == 'time': posts = make_paginator(request, query_set.order_by('-created'), per_page=20, cache_key=cache_key, cache_time=POSTS_CACHE_TIME) elif order == 'all': # 待写排名方法,参考了HackerNews的排名算法 posts = make_paginator(request, query_set.extra( select = { 'score': '(total_likes + 1) / POW(datediff(NOW(), created) + 1, 1.3)' }, order_by = ['-score'] ), per_page=20, cache_key=cache_key, cache_time=POSTS_CACHE_TIME) else: posts = make_paginator(request, query_set.order_by('-id'), per_page=20, cache_key=cache_key, cache_time=POSTS_CACHE_TIME) form = ForumPostForm() return render(request, 'forum/index.tpl', { 'form': form, 'posts': posts }) return render(request, 'forum/index.tpl', { 'form': form })
def image_create(request): """ View for creating an Image using the JavaScript Bookmarklet. """ if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) # type(form) = <class 'images.forms.ImageCreateForm'> if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # ImageCreateForm.save(), type(new_item) = <class 'images.models.Image'> # assign current user to the item new_item.user = request.user new_item.save() # Image.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image added successfully') # redirect to new created item detail view return redirect(new_item.get_absolute_url()) else: # build form with data provided by the bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
def image_create(request): if request.method == 'POST': #formularz wyslany form = ImageCreateForm(data=request.POST) if form.is_valid(): #formularz prawidlowy cd = form.cleaned_data new_item = form.save(commit=False) #przypisanie biezacego uzytkownika do nowego elemetnu new_item.user = request.user new_item.save() create_action(request.user, 'dodał obraz', new_item) messages.success(request, 'Obraz został dodany') #przekierowanie do widoku szcegolwego nowego elementu return redirect(new_item.get_absolute_url()) else: #utworzenie formularza na podstawie danych dostarczonych przez bookmarklet w zadaniu GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(data=request.POST) profile_form = ProfileEditForm(data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): new_user = user_form.save(commit=False) # User 模型的set_password() 方法将用户的原密码进行加密后再保存 new_user.set_password(user_form.cleaned_data['password']) # modelform才有save方法 new_user.save() new_profile = profile_form.save(commit=False) new_profile.user = new_user new_profile.save() create_action(new_user, '注册成功') return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() profile_form = ProfileEditForm() return render(request, 'account/register.html', { 'user_form': user_form, 'profile_form': profile_form })
def image_create(request): if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) new_item.user = request.user new_item.save() messages.success(request, 'Image added successfully.') create_action(request.user, 'bookmarked image', new_item) return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form' : form })
def image_create(request): if request.method == 'POST': form = ImageCreateForm(request.POST) if form.is_valid(): cd = form.cleaned_data instance = form.save(commit=False) # assigning user instance.user = request.user instance.save() # create bookmark action create_action(request.user, 'bookmarked an image', instance) messages.success(request, 'Image added successfully') # redirecting to new created image detail view return redirect(instance.get_absolute_url()) else: form = ImageCreateForm(request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def edit(request, username): user = get_object_or_404(User, username=username) if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() new_item = profile_form.save(commit=False) profile_form.save() create_action(request.user, 'Updated his profile', new_item) messages.success(request, 'Profile updated successfully') return redirect('user_detail', username=user.username) else: messages.error(request, 'Error in updating your profile') else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'edit.html', { 'user_form': user_form, 'profile_form': profile_form })
def image_create(request): if request.method == 'POST': # Formularz został wysłany. form = ImageCreateForm(data=request.POST) if form.is_valid(): # Dane formularza są prawidłowe. cd = form.cleaned_data new_item = form.save(commit=False) # Przypisanie bieżącego użytkownika do elementu. new_item.user = request.user new_item.save() create_action(request.user, 'dodał obraz', new_item) messages.success(request, 'Obraz został dodany.') # Przekierowanie do widoku szczegółowego dla nowo utworzonego elementu. return redirect(new_item.get_absolute_url()) else: # Utworzenie formularza na podstawie danych dostarczonych przez bookmarklet w żądaniu GET. form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def image_create(request): if request.method == "POST": # 表单被提交 form = ImageCreateForm(request.POST) if form.is_valid(): # 表单验证通过 cd = form.cleaned_data new_item = form.save(commit=False) # 将当前用户附加到数据对象上 new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image added successfully') # 重定向到新创建的数据对象的详情视图 return redirect(new_item.get_absolute_url()) else: # 根据GET请求传入的参数建立表单对象 form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Создаем нового пользователя, но пока не сохраняем в базу данных. new_user = user_form.save(commit=False) # Задаем пользователю зашифрованный пароль. new_user.set_password(user_form.cleaned_data['password']) # Создать Profile новому пользователю Profile.objects.create(user=new_user) create_action(new_user, 'has created an account') # Задаем пользователю зашифрованный пароль. new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form})
def comment_detail(request, comment_id, event_id): event = get_object_or_404(Event, pk=event_id) comment = get_object_or_404(Comment, pk=comment_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.event = event new_comment.parent = comment new_comment.created_by = request.user create_action(request.user, 'you replied a comment', comment) new_comment.save() messages.success(request, 'You replied a comment') return redirect('events:event-detail', pk=event_id) else: form = CommentForm() return render(request, 'comments/detail.html', { 'comment': comment, 'form': form })
def image_create(request): if request.method == 'POST': # form is sent form = ImageCreateForm(request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # assign current user to the item new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image added successfully') # redirect to new created item detail view return redirect(new_item.get_absolute_url()) # build form with data provided by the boomarklet via GET form = ImageCreateForm(data=request.GET) context = { 'section': 'images', 'form': form, } return render(request, 'images/image/create.html', context)
def image_create(request): if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): # Данные формы валидны. cd = form.cleaned_data new_item = form.save(commit=False) # Добавляем пользователя к созданному объекту. new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) print('New item', new_item) messages.success(request, 'Image added successfully') # Перенаправляем пользователя на страницу сохраненного изображения. return redirect(new_item.get_absolute_url()) else: # Заполняем форму данными из GET-запроса. form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def image_create(request): if request.method=="POST": # form is sent form = ImageCreateForm(request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # assign current user to the item new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked images', new_item) messages.success(request, 'Image added successfully.') item = get_object_or_404(Image, title=new_item.title, url=new_item.url) return redirect(reverse('images:detail', args=[item.id, item.slug])) else: # build form with data provided by the bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Set the chosen password new_user.set_password( user_form.cleaned_data['password'] ) # Save the User object new_user.save() # Create the user profile Profile.objects.create(user=new_user) create_action(new_user, 'has created an account') return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form})
def follow_user(request): id = request.POST['id'] action = request.POST['action'] # try: user = get_object_or_404(User, id=id) if action == 'follow': contact.objects.get_or_create(user_from=request.user, user_to=user) create_action(request.user, "fonnows", user) # Action.objects.create(user=request.user,verb="follows",content_object=user) return JsonResponse({'status': 'ok'}) elif action == 'unfollow': contact.objects.filter(user_from=request.user, user_to=user).delete() Action.objects.create(user=request.user, verb="unfollows", content_object=user) return JsonResponse({'status': 'ok'}) # except: # pass return JsonResponse({'status': 'ko'})
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) new_user.is_active = False # Set the chosen password new_user.set_password(user_form.cleaned_data['password']) # Save the User object new_user.save() # Create the user profile Profile.objects.create(user=new_user) new_user.profile.rating += 20 new_user.profile.save() create_action(new_user, 'has created an account') # confirm by email current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('account/activate.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.pk)), 'token': account_activation_token.make_token(new_user), }) to_email = user_form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() messages.success(request, 'Please confirm your email address to complete the registration.') return redirect('reActivation') else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form})
def create_image(request): if request.method == 'POST': form = ImageCreationForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data # save the data and image in the object, but in the database new_item = form.save(commit=False) # add current user to the user of this item new_item.user = request.user # now save to db new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image has been sucessfully added') # redirect to new created item detail view return redirect(new_item.get_absolute_url()) else: # fill the form with the GET data that contains url and title form = ImageCreationForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def image_create(request): if request.method == "POST": #means form is save form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) #assign current user to the item new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) messages.success(request, "Image was added successfully") #redirect to new created item details return redirect(new_item.get_absolute_url()) else: #build form data provided by the bookmarker via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def image_like(request): image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Image.objects.get(id=image_id) if action == 'like': image.users_like.add(request.user) create_action(request.user, 'likes', image) else: image.users_like.remove(request.user) return JsonResponse({'status':'ok'}) except: pass return JsonResponse({'status':'error'})
def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() # 两个表单对象不是模型模型实例,无法作为target参数传递 create_action(request.user,'修改资料') # create_action(request.user,'修改资料',profile_form) messages.success(request,'保存成功') else: messages.error(request,'保存失败') else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'account/edit.html', {'user_form':user_form, 'profile_form':profile_form})
def edit(request): if request.method == "POST": user_form = UserForm(instance=request.user, data=request.POST) profile_form = ProfileForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() create_action(request.user, '修改了', request.user.profile) messages.success(request, '成功啦') else: messages.error(request, user_form.errors) return redirect(reverse('accounts:edit')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'accounts/admin/edit.html', { 'user_form': user_form, 'profile_form': profile_form })
def image_create(request): if request.method == 'POST': # form is sent form = ImageCreationForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) # assign current user to the item new_item.user = request.user new_item.save() create_action(request.user, 'likes', new_item) messages.success(request, 'Image added successfully') # redirect to the new created item detail view return redirect(new_item.get_absolute_url()) else: # build the form with the data provided form = ImageCreationForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user, user_to=user) create_action(request.user, 'is following', user) request.user.profile.rating += 5 request.user.profile.save() if not request.user == user: user.profile.rating += 10 user.profile.save() else: Contact.objects.filter(user_from=request.user, user_to=user).delete() request.user.profile.rating -= 5 request.user.profile.save() user.profile.rating -= 5 user.profile.save() return JsonResponse({'status': 'ok'}) except User.DoesNotExist: return JsonResponse({'status': 'ko'}) return JsonResponse({'status': 'ko'})
def image_create(request): """使用图片的视图函数""" if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) #指定用户 new_item.user = request.user new_item.save() create_action(request.user, 'bookmarked image', new_item) #添加用户行为 messages.success(request, '图片添加成功') #返回一个新建的item的细节视图 return redirect(new_item.get_absolute_url()) else: #通过GET建立一个表单 form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def image_create(request): """ View for creating an Image using the JavaScript Bookmarklet. """ if request.method == 'POST': # form is sent form = CreateImageForm(data=request.POST, files=request.FILES) if form.is_valid(): # form data is valid image = form.save(commit=False) image.user = request.user posted = image.caption hashtag = re.compile(r'(^|[^#\w])#(\w{1,30})\b') hashtag = re.sub( r'(^|[^#\w])#(\w{1,15})\b', '\\1<a href="http://127.0.0.1:8000/hashtag/\\2">#\\2</a>', posted) caption = re.sub( r'(^|[^@\w])@(\w{1,15})\b', '\\1<a href="http://127.0.0.1:8000/\\2">@\\2</a>', hashtag) caption = caption.strip() image.caption = caption image.save() #image = form.save() create_action(request.user, ' ', image) messages.success(request, 'Image added successfully') # redirect to new created item detail view return redirect(image.get_absolute_url()) else: # build form with data provided by the bookmarklet via GET form = CreateImageForm() return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password( user_form.cleaned_data['password'] ) new_user.save() messages.success(request,'注册成功') # 将保存的用户关联到Profile表 根据user字段 profile = Profile.objects.create(user=new_user) create_action(new_user,'注册账号',new_user) return render(request, 'account/register_done.html', {'new_user':new_user}) else: messages.error(request,'注册失败') else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form':user_form})
def user_follow(request): """ follow the user """ user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(from_user=request.user, to_user=user) create_action(request.user, 'is following', user) else: Contact.objects.filter(from_user=request.user, to_user=user).delete() create_action(request.user, 'unfollowed', user) return JsonResponse({'status': 'Ok'}) except User.DoesNotExist: return JsonResponse({'status': 'error'}) return JsonResponse({'status': 'error'})
def create_post(request): if request.method == 'POST': print('check post') files = request.FILES.getlist('image') if len(files) >= 1 or request.POST.get('article') != '': post = Post() if request.POST.get('article') != '': post.article = request.POST.get('article') else: post.slug = slugify(random_string_generator()) post.user = request.user post = post.save() create_action(request.user, 'added', post) if len(files) >= 1: # files = request.FILES.getlist('image') for f in files: gallery = Images(post=post, image=f) gallery.save() else: print('no img') tag_form = TagForm(data=request.POST) if tag_form: if tag_form.is_valid(): form = tag_form.save(commit=False) form.post = post form.save() tag_form.save_m2m() messages.success(request, 'Posted!') return redirect('account:home') return redirect('account:home')
def follow_user(request): """(取消)关注用户""" user_id = int(request.POST.get('user_id')) follow_status = True if request.POST.get( 'follow_status') == 'true' else False fan = request.user star = get_object_or_404(User, id=user_id) # if user follow self if star.id == fan.id: return JsonResponse({'action': 'self'}) try: # user is unfollow:follow others if not follow_status: Contact.objects.create(fans=fan, star=star) create_action(fan, star, f"{fan.username} 关注了 {star.username}") json = {'action': 'followed'} # user is followed:unfollow else: Contact.objects.filter(fans=fan, star=star).delete() create_action(fan, star, f"{fan.username} 取消了关注 {star.username}") json = {'action': 'unfollow'} return JsonResponse(json) except User.DoesNotExist: return JsonResponse({})
def image_create(request): if request.method == "POST": form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) # assign auth user to the bookmarked image new_item.user = request.user new_item.save() # create an action or activity stream for this action create_action(request.user, "bookmarked image", new_item) messages.success(request, 'Image added successfully') # redirect to new created item detail view return redirect(new_item.get_absolute_url()) else: # build form with data provided by the bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', { 'section': 'images', 'form': form })
from django.shortcuts import render, redirect
def edit(request, id): post = get_object_or_404(Post, id=int(id)) # 判断这篇文章的作者是不是正要编辑其的人 if request.user != post.author: raise Http404('您的权限不足以修改这篇博客!') # 获取用户设置的编辑器 try: editor = request.user.setting.setting except: editor = 'M' if editor == 'M': if request.method == 'POST': form = PublishMdForm(request.POST, instance=post) if form.is_valid(): new_post = form.save() create_action(request.user, '修改了', new_post) # 用户后输入的标签 extra_tags_list = form.cleaned_data['extra_tags'] for exttag in extra_tags_list: if exttag: obj, created = Tag.objects.get_or_create(name=exttag) if created: new_post.tags.add(obj) else: try: new_post.tags.add(obj) except: pass if new_post.status == 'P': return HttpResponseRedirect(reverse("blog:post", args=(new_post.id,))) return HttpResponseRedirect(reverse("accounts:mydrafts")) else: form = PublishMdForm(instance=post) return render(request, 'blog/publish-md.html', {'form': form}) if request.method == 'POST': form = PublishForm(request.POST, instance=post) if form.is_valid(): new_post = form.save() extra_tags_list = form.cleaned_data['extra_tags'] for exttag in extra_tags_list: if exttag: obj, created = Tag.objects.get_or_create(name=exttag) if created: new_post.tags.add(obj) else: try: new_post.tags.add(obj) except: pass if new_post.status == 'P': return HttpResponseRedirect(reverse("blog:post", args=(new_post.id,))) return HttpResponseRedirect(reverse("accounts:mydrafts")) else: form = PublishForm(instance=post) return render(request, 'blog/publish.html', {'form': form})
def publish(request): user = request.user # 获取用户设置的编辑器 try: editor = user.setting.setting except: editor = 'M' if editor == 'M': if request.method == 'POST': form = PublishMdForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() # Adding user actions to the activity stream create_action(request.user, '发表了', new_post) # 必须save后才能添加manytomany关系 for tag in form.cleaned_data['tags']: new_post.tags.add(tag) # 用户后输入的标签 extra_tags_list = form.cleaned_data['extra_tags'] # get_or_create() # 1、If an object is found, get_or_create() returns a tuple of that object and False. # 2、If multiple objects are found, get_or_create raises MultipleObjectsReturned. # 3、If an object is not found, get_or_create() will instantiate and save a new object, # returning a tuple of the new object and True. The new object will be created # roughly according to this algorithm: for exttag in extra_tags_list: if exttag: obj, created = Tag.objects.get_or_create(name=exttag) if created: new_post.tags.add(obj) else: try: new_post.tags.add(obj) except: pass if new_post.status == 'P': return HttpResponseRedirect(reverse("blog:post", args=(new_post.id,))) return HttpResponseRedirect(reverse("accounts:mydrafts")) else: form = PublishMdForm() return render(request, 'blog/publish-md.html', {'form': form}) # 火候未到,未能将其融合为一 if request.method == 'POST': form = PublishForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() create_action(request.user, '发表了', new_post) for tag in form.cleaned_data['tags']: new_post.tags.add(tag) extra_tags_list = form.cleaned_data['extra_tags'] for exttag in extra_tags_list: if exttag: obj, created = Tag.objects.get_or_create(name=exttag) if created: new_post.tags.add(obj) else: try: new_post.tags.add(obj) except: pass if new_post.status == 'P': return HttpResponseRedirect(reverse("blog:post", args=(new_post.id,))) return HttpResponseRedirect(reverse("accounts:mydrafts")) else: form = PublishForm() return render(request, 'blog/publish.html', {'form': form})