def detail(request,slug): product_list = Product.objects.order_by('created_at')[:5] product = get_object_or_404(Product,slug=slug) formset = CommentForm(request.POST or None) if formset.is_valid(): comment = formset.save(commit=False) comment.product = product comment.author = request.user comment.save() return redirect(request.path) try: ldc = str(product.post_set.last().created)[:10].split("-") ldc = [int(i) for i in ldc] comments = product.post_set.filter(created__year=ldc[0],created__month=ldc[1],created__day=ldc[2]) more_comments = product.post_set.exclude(created__year=ldc[0],created__month=ldc[1],created__day=ldc[2]) more_comments.order_by('created_at') #print(comments,comments2) context = {'product_list':product_list,'product':product,'comments':comments,'more_comments':more_comments,'formset': formset} context.update(csrf(request)) return render(request, 'product/detail.html', context) except: context = {'product_list':product_list,'product':product,'formset': formset} context.update(csrf(request)) return render(request, 'product/detail.html', context)
def get_context_data(self, **kwargs): data = CreateView.get_context_data(self, **kwargs) product = get_object_or_404(Product, pk=self.kwargs['pk']) data['product'] = product data['user'] = self.request.user if product.courier: data['courier'] = Courier.objects.get(pk=product.courier) data['comment_list'] = product.comment_set.all().order_by('id') data['comment_form'] = CommentForm(initial={'user': self.request.user, 'product': product}) data['hardware_comment_form'] = CommentForm(initial={'user': self.request.user, 'product': product}) return data
def add_comment_to_product(request, product_id): p = get_object_or_404(Product, id=product_id) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.product = p u = User.objects.get(username=request.user) comment.author = Account.objects.get(user=u) comment.save() messages.add_message(request, messages.SUCCESS, "نظر ثبت گردید") return redirect('product_page', product_id=product_id)
def product_page(request, product_id): p = Product.objects.get(id=product_id) product = { 'name': p.name, 'price': p.price, 'is_available': p.is_available, 'expires_at': jdatetime.date.fromgregorian(date=p.expires_at), 'manufacture_date': jdatetime.date.fromgregorian(date=p.manufacture_date), 'photo': p.photo, 'product_id': p.id } comments = Comment.objects.filter(product=p, approved=True) form = CommentForm() if request.user.is_authenticated: account = Account.objects.get(user=request.user) else: account = None return render(request, 'product_page.html', context={ 'product': product, 'comments': comments, 'form': form, 'account': account })
def post(self, request, **kwargs): form = CommentForm(self.request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = self.request.user \ if self.request.user.is_authenticated() else None comment.product = self.get_object() comment.save() messages.success(self.request, 'Comment successfully added') return render( self.request, 'product_detail.html', {'form': CommentForm(), 'product': self.get_object()}) else: messages.error(self.request, 'Can\'t add you comment') return render( self.request, 'product_detail.html', {'form': form, 'product': self.get_object()})
def addcomment(request, product_id): if request.POST and ('pause' not in request.session): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments = Product.objects.get(id=product_id) form.save() request.session.set_expiry(60) request.session['pause'] = True if form.is_valid(): form.save() messages.success(request, 'Comment sended.') return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def post(self, request, **kwargs): form = CommentForm(self.request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = self.request.user \ if self.request.user.is_authenticated() else None comment.product = self.get_object() comment.save() messages.success(self.request, 'Comment successfully added') return render(self.request, 'product_detail.html', { 'form': CommentForm(), 'product': self.get_object() }) else: messages.error(self.request, 'Can\'t add you comment') return render(self.request, 'product_detail.html', { 'form': form, 'product': self.get_object() })
def product_view(request, category_slug, subcategory_slug, product_id): context_dict = {} category = Category.objects.get(cat_slug=category_slug) subcategory = Category.objects.get(cat_slug=subcategory_slug) product = Product.objects.get(id=product_id) commnets = Comment.objects.filter( product=product).order_by('date').reverse() context_dict['proid'] = product_id context_dict['category'] = category context_dict['subcategory'] = subcategory context_dict['product'] = product context_dict['categories'] = Category.objects.filter(parent=None) context_dict['comments'] = commnets if request.method == 'POST' and request.is_ajax: form = CommentForm(request.POST) products = get_object_or_404(Product, pk=product_id) User = request.user if form.is_valid(): cm_text = form.cleaned_data['cm_text'] comment = Comment() comment.product = products comment.users = User comment.cm_text = cm_text comment.date = datetime.datetime.now() comment.save() # form.save() msg = "The operation has been received correctly." print(request.POST) return HttpResponse(msg) else: msg = "GET petitions are not allowed for this view." return HttpResponse(msg) else: form = CommentForm() context_dict['form'] = form return render( request, 'product.html', context=context_dict, )
def get(self, request, pk): x = Product.objects.get(id=pk) comments = Comment.objects.filter(product=x).order_by('-updated_at') comment_form = CommentForm() context = { 'product': x, 'comments': comments, 'comment_product': comment_form } return render(request, self.template_name, context)
def create_comment(request, item_id): if request.user.is_authenticated: if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user_id = request.user.id form.item_id = item_id form.save() return redirect('/item/{}'.format(item_id)) else: return redirect('/')
def add_product_comment(request, prod_id, comment_id=None): # TODO: func -> user can edit and delete his comments """Создает новый комментарий под породуктом, если пользователь авторизован и перенаправляет обратно на страницу продукта. Не реалезованно: передача существующего коментария для его редоктирования""" product = Product.objects.get(pk=prod_id) comment, _ = Comment.objects.get_or_create(pk=comment_id, product=product, user=request.user) form = CommentForm(request.POST, instance=comment) if form.is_valid(): text = form.cleaned_data['text'] # comment, _ = Comment.objects.get_or_create(pk=comment_id, product=product, # user=request.user) comment.text = text comment.save() return redirect(product.get_absolute_url())
def add_comment(request, product_slug): if request.POST: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.product = Product.objects.get(slug=product_slug) form.save() return redirect('product', product_detail=product_slug)
def open_detail(request, item_id): item = Item.objects.filter(id=item_id).first() if not item: raise Http404 items = Item.objects.exclude(id=item_id).exclude(status=0)[:3] comments = Comment.objects.filter(item=item) form = CommentForm() return render(request, 'product/detail.html', { 'item': item, 'items': items, 'comments': comments, 'form': form })
def update_comment(request, comment_id, item_id): if request.user.is_authenticated: comment = get_object_or_404(Comment, id=comment_id, user=request.user.id) if request.method == "POST": form = CommentForm(request.POST, instance=comment) if form.is_valid(): form.save() return redirect('/item/{}'.format(item_id)) else: form = CommentForm(instance=comment) return render(request, 'product/comment_update.html', {'form': form}) else: return redirect('/')
def showProduct(request, productId): product = get_object_or_404(Producto, pk=productId) valoracion = Valoracion.objects.filter(producto=product).aggregate( Avg('puntuacion'))["puntuacion__avg"] precio_medio = UbicacionProducto.objects.filter( producto=product).aggregate(Avg('precio'))["precio__avg"] valoracion_media = int(round(valoracion, 0)) if valoracion != None else 0 aportaciones = Aportacion.objects.filter(producto=product) recetas = Receta.objects.filter(productos__in=[product]).distinct() if request.method == 'GET': form = ReporteForm() formComment = CommentForm() formUbicacion = AddUbicationForm() if product.estado == 'Pendiente' and request.user.is_superuser: return render( request, 'products/show.html', { 'product': product, 'valoracion_media': valoracion_media, 'precio_medio': precio_medio }) elif product.estado == 'Aceptado': return render( request, 'products/show.html', { 'product': product, 'valoracion_media': valoracion_media, 'precio_medio': precio_medio, 'form': form, 'formComment': formComment, 'aportaciones': aportaciones, 'recetas': recetas, 'formUbicacion': formUbicacion }) else: messages.error( request, 'Los productos pendientes de revisión solo pueden ser vistos por el administrador.' ) return redirect('/authentication/login') elif request.method == 'POST': if 'reportButton' in request.POST: form = ReporteForm(request.POST) formComment = CommentForm() formUbicacion = AddUbicationForm() formComment.empty_permitted = True if form.is_valid(): reporte = form.save(commit=False) reporte.producto = Producto(id=productId) reporte.user = get_object_or_404(User, pk=request.user.pk) reporte.save() return redirect('product:show', product.id) else: return render( request, 'products/show.html', { 'product': product, 'valoracion_media': valoracion_media, 'precio_medio': precio_medio, 'form': form, 'formComment': formComment, 'aportaciones': aportaciones, 'recetas': recetas, 'formUbicacion': formUbicacion }) if 'commentButton' in request.POST: form = ReporteForm() formComment = CommentForm(request.POST) formUbicacion = AddUbicationForm() form.empty_permitted = True if formComment.is_valid(): comentario = formComment.save(commit=False) comentario.producto = Producto(id=productId) comentario.user = get_object_or_404(Perfil, user=request.user) comentario.save() return redirect('product:show', product.id) else: return render( request, 'products/show.html', { 'product': product, 'valoracion_media': valoracion_media, 'precio_medio': precio_medio, 'form': form, 'formComment': formComment, 'aportaciones': aportaciones, 'recetas': recetas, 'formUbicacion': formUbicacion }) if 'addingUbication' in request.POST: form = ReporteForm() formComment = CommentForm() formUbicacion = AddUbicationForm(request.POST) product = get_object_or_404(Producto, pk=productId) if formUbicacion.is_valid(): ubicaciones = formUbicacion.cleaned_data['ubicaciones'] nombre = formUbicacion.cleaned_data['nombreComercio'] latitud = formUbicacion.cleaned_data['lat'] longitud = formUbicacion.cleaned_data['lon'] precio = formUbicacion.cleaned_data['precio'] if (nombre != '' and latitud != '' and longitud != ''): ubicacion = Ubicacion(nombre=nombre, latitud=latitud, longitud=longitud) ubicacion.save() ubicacionProducto = UbicacionProducto( producto=product, ubicacion=ubicacion, user=get_object_or_404(Perfil, user=request.user), precio=precio) ubicacionProducto.save() else: ubicacionProducto = UbicacionProducto( producto=product, ubicacion=ubicaciones, user=get_object_or_404(Perfil, user=request.user), precio=precio) ubicacionProducto.save() return redirect('product:show', product.id) else: return render( request, 'products/show.html', { 'product': product, 'valoracion_media': valoracion_media, 'precio_medio': precio_medio, 'form': form, 'formComment': formComment, 'aportaciones': aportaciones, 'recetas': recetas, 'formUbicacion': formUbicacion })
def get(self, request, **kwargs): form = CommentForm() return render(self.request, 'product_detail.html', { 'form': form, 'product': self.get_object() })