Example #1
0
def create(request):
    form = PostForm(request.POST, user=request.user)
    if form.is_valid():
        post = form.save()
        return JsonResponse(post.to_client())
    else:
        return JsonResponse(form.errors, status=400)
Example #2
0
    def post(self, request, *args, **kwargs):
        post = PostForm(request.POST, request.FILES)
        if post.is_valid():
            post.instance.usuario = request.user
            post.save()

        return redirect('core:index')
Example #3
0
def edit_post(request, post_id):
    post = get_object_or_404(Post, 
                             pk=post_id,
                             user=request.user)

    if request.method == 'POST':
        form = PostForm(request.POST, 
                        request.FILES, 
                        instance=post)
        if form.is_valid():
            # set user to form instance
            form.instance.user = request.user
            
            # update post
            post = form.save()

            # add resize image task to celery
            resize_post_image.delay(post)

            messages.success(request, _("Post updated succesfully."))
            return redirect("my_posts")
    else:
        form = PostForm(instance=post)

    return render(request, 'post/edit_post.html', {
        'form': form,
    })
def post_add(request):
    def create_post_comment(file, comment_content):
        post = Post(author=request.user, photo=file)
        post.save()

        if comment_content != '':
            post.add_comment(request.user, comment_content)

    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            files = request.FILES.getlist('photo')
            comment_content = form.cleaned_data.get('content', '').strip()

            for file in files:
                create_post_comment(file, comment_content)

            return redirect('post:list')
    else:
        form = PostForm()

    context = {
        'form': form,
    }
    return render(request, 'post/post_add.html', context)
Example #5
0
def post_create(request):
    # 로그인한 유저만 접근 및 POST요청 가능
    if not request.user.is_authenticated:
        return redirect('member:login')

    if request.method == 'POST':
        # POST요청의 경우 PostForm인스턴스 생성과정에서 request.POST, request.FILES를 사용
        form = PostForm(request.POST, request.FILES)
        # 만약 form이 유효성검사를 통과헀다면 true리턴
        if form.is_valid():
            # 유효할 경우 Post인스턴스를 생성 및 저장
            post = Post.objects.create(
                author=request.user,
                photo=form.cleaned_data['photo'],
            )
            return redirect('post:post_list')

    else:
        # GET 요청의 경우 빈 PostForm인스턴스를 생성해서 템플릿에 전달
        form = PostForm()

    # GET 요청에선 이 부분이 무조건 실행
    # POST 요청에선 form.is_valid()를 통과하지 못하면 이 부분이 실행
    context = {
        'form': form,
    }
    return render(request, 'post/post_create.html', context)
Example #6
0
def save_post(request):
    """Saves a Post

    Check if the post's island exists
    If not redirect the user to Island creation page
    If no island was included, use the default island.
    Add post to user's likes then save the post and
    return the user to a page specified with the next variable
    """
    if request.method == "POST":
        form = PostForm(request.POST)

        if form.is_valid():
            post = form.cleaned_data["post"]
            island_name = form.cleaned_data["island"]

            if island_name:
                try:
                    island = Island.get_island(island_name)
                except ObjectDoesNotExist:
                    create_form = IslandCreationForm()
                    return render(
                        request,
                        "island/island_not_created.html",
                        {
                            "form": create_form,
                            "submitted_island": island_name
                        },
                    )
            else:
                island = Island.get_island(settings.DEFAULT_ISLAND)
            post = Post(post=post, user=request.user, island=island)
            post.save()
            request.user.likes.add(post)
            return HttpResponseRedirect(request.GET.get("next", ""))
Example #7
0
def create_post(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/')
    return render(request, 'posts/create_post.html', {'form': form})
Example #8
0
def update_post(request, id):
    post = Post.objects.get(id=id)
    form = PostForm(
        request.POST or None, request.FILES or None, instance=post
    )
    if form.is_valid():
        form.save()
        return redirect('/')
    return render(request, 'post/create_post.html', {'form': form})
Example #9
0
def add_post(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            book = form.save(commit=False)
            book.create_by_id = request.user.pk
            book.save()
            return redirect('post_list')
    return render(request, 'post/add_post.html', {'form': PostForm})
Example #10
0
def add_post(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        post = form.save(commit=False)
        post.save()
        return redirect('http://localhost:8000/posts/')
    return render(template_name='add_post.html',
                  context={"form": form},
                  request=request)
Example #11
0
 def post(self, request, *args, **kwargs):
     if not request.user.is_authenticated:
         return HttpResponseRedirect(reverse('login'))
     else:
         post_form = PostForm(request.POST, request.FILES)
         if post_form.is_valid():
             post1 = Post.objects.create(author=request.user,text=post_form.cleaned_data['text'],original=post_form.cleaned_data['original'])
             post1.thema.add(*post_form.cleaned_data['thema'])
             print(post_form.cleaned_data["thema"])
             return super().get(self, request, *args, **kwargs)
Example #12
0
def add_post(request, add_post_success_url="home", template="post/add_post.html"):

	form = PostForm(request.POST or None)
	if form.is_valid():
		post = form.save(commit=False)
		post.author = request.user
		post.save()
		return redirect(add_post_success_url)

	return render(request, template, {'form': form})
Example #13
0
 def post(self, request, pk):
     try:
         post = Post.objects.get(pk=pk)
     except Post.DoesNotExist:
         raise Http404
     form = PostForm(instance=post, author=request.user, data=request.POST)
     if form.is_valid():
         form.save()
         return HttpResponseRedirect(reverse("home:index"))
     return render(request, "post/edit.html", {"form": form, "pk": pk})
Example #14
0
def index(request):


    if request.method == "POST":
        # Convert
        form = PostForm(request.POST)

        # Check
        if form.is_valid():
            keyword = form.cleaned_data["keyword"]
            # Create
            Post.objects.create(keyword = keyword, ip = request.META['REMOTE_ADDR'])
            return redirect('/post/')
    else:
        # Convert
        form = PostForm()
        # form = PostForm(request.GET)

        # Check
        if form.is_valid():
            pass

    page = 1
    page = request.GET.get('page')


    # Get
    entries = Post.objects.all().order_by('-created_at')

    # Show 3 per page
    paginator = Paginator(entries, 5)

    try:
        data = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        data = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        data = paginator.page(paginator.num_pages)

    latest = entries.first()

    return render_to_response(
        'post/index.html',
        context_instance=RequestContext(
            request,
            {
                'form': form,
                'entries': data,
                'latest': latest,
            }
        )
    )
Example #15
0
def add_post(request):
    if request.method == 'POST':  # If the form has been submitted...
        form = PostForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            form.save()
            return HttpResponseRedirect('/account/blog/')

    else:
        form = PostForm()

    return render(request, 'post/add_post.html', {'form': form, })
Example #16
0
def post_edit(request, id):
    post = Post.objects.get(id=id)
    if request.method == 'POST':  # If the form has been submitted...
        form = PostForm(request.POST, instance=post)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            form.save()
            return HttpResponseRedirect('/account/blog/')    # Redirect after POST
    else:
        form = PostForm(instance=post)

    return render(request, 'post/post_edit.html', {'form': form, 'post': post, })
Example #17
0
def create_post(request):
    title = "Create"
    form = PostForm(request.POST or None, request.FILES or None)
    author = get_author(request.user)  # Get the Post author
    if request.method == "POST":
        if form.is_valid():
            form.instance.author = author
            form.save()
            return redirect(
                reverse("post-detail", kwargs={"myid": form.instance.id}))
    context = {"form": form, "title": title}
    return render(request, "create_post.html", context)
Example #18
0
def createpost_view(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user  # save the user who created the post
            post.save()
            return redirect(post.get_absolute_url())
    else:
        form = PostForm
    context = {'form': form}
    return render(request, 'post/createpost.html', context)
Example #19
0
def edit_post(request, post_id=None):
    post = get_object_or_404(Post, id=post_id)
    form = PostForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        messages.success(request, "Post edited successfully")
        return redirect("index")

    context = {
        'post_form': form,
    }

    return render(request, 'user/edit_post.html', context)
Example #20
0
def post_create(request):
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        # message success
        messages.success(request, "Successfully Created")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form": form,
    }
    return render(request, "post_form.html", context)
Example #21
0
    def post(self, request, title=None):
        form = PostImportForm(request.POST, files=request.FILES)

        if form.is_valid() is True:
            print("VALID")
            json_data_string = form.cleaned_data.get("file").read()
            json_data = json.loads(json_data_string)
            json_data["pk"] = None

            content_set = json_data["fields"].pop("content_set")

            json_data_string = json.dumps([json_data])

            deserialized_object = next(serializers.deserialize("json", json_data_string))
            instance = deserialized_object.object
            instance.slug_title = None

            instance.author = request.user
            data = model_to_dict(instance)

            post_form = PostForm(data)

            if post_form.is_valid() is True:
                instance = post_form.save()

                for content_json in content_set:
                    content_json["pk"] = None
                    content_json["fields"]["post"] = instance
                    # content_json["fields"]["sequence"] = None

                    image_base64_string = None

                    if content_json["fields"]["image"]:
                        image_base64_string = content_json["fields"]["image"]
                        content_json["fields"]["image"] = None

                    content_instance = Content.objects.create(**content_json["fields"])

                    if image_base64_string:
                        image = Image.objects.create(
                            content=content_instance)
                        image.image_file.save("", content=ContentFile(base64.b64decode(image_base64_string)))
                        print(content_json)
                        print(image.image_file)

                    instance.content_set.add(content_instance)

                return HttpResponseRedirect(
                    reverse_lazy("blog:post-detail", kwargs={"title": instance.slug_title}))
            else:
                return render(request, template_name="post/import.html", context={"form": form, "post_form": post_form})
Example #22
0
    def post_community_new(request, community_url):
        """
        Function for creating post

        :param community_url: community custom_url field
        :type community_url: str
        :param request: object with request details
        :type request: :class:`django.http.HttpRequest`
        :return: responce object with HTML code
        :rtype: :class:`django.http.HttpResponse`
        :raises: :class:`django.http.Http404` if custom url not valid
        """

        community = get_object_or_404(Community, custom_url=community_url)

        post_image_form_set = modelformset_factory(PostImages,
                                                   form=PostImageForm,
                                                   extra=10,
                                                   max_num=10)

        if request.method == "POST":
            postForm = PostForm(request.POST)
            formset = post_image_form_set(request.POST,
                                          request.FILES,
                                          queryset=PostImages.objects.none())

            if postForm.is_valid() and formset.is_valid():
                post_form = postForm.save(commit=False)
                post_form.community = community
                post_form.owner_community = community
                post_form.save()

                if request.POST.get('music'):
                    for music_id in [
                            int(i) for i in request.POST.get('music').split()
                    ]:
                        music_item = get_object_or_404(Music, id=music_id)
                        post_form.music.add(music_item)

                community.posts.add(post_form)

                for form in formset.cleaned_data:
                    if form:
                        image = form['image']
                        photo = PostImages(post=post_form,
                                           image=image,
                                           from_user_id=request.user.id)
                        photo.save()

        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Example #23
0
def add_post(request):
    context = {}
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save()
            post.owner = request.user
            post.save()
            return redirect('post:get', post_id=post.pk)
        else:
            context['form'] = form
    else:
        context['form'] = PostForm()
    return render(request, 'add-post.html', context)
Example #24
0
def new_post(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            time = timezone.now()
            new_post = Post.objects.create(author=get_object_or_404(
                Author, username=request.user.username),
                                           caption=data["caption"],
                                           image=data['image'],
                                           timestamp=time)
            new_post.save()
            return redirect(reverse("homepage"))
    form = PostForm()
    return render(request, "../templates/post/post_form.html", {"form": form})
Example #25
0
def add_post(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            post = Post()
            post.title = cleaned_data['title']
            post.content = cleaned_data['content']
            post.image = cleaned_data['image']
            post.save()
            return redirect('post-detail', pk=post.pk)
    else:
        form = PostForm(request.FILES)

    return render(request, 'post/post_form.html', {'form': form})
Example #26
0
File: post.py Project: jcasmer/blog
    def post(self, request, *args, **kwargs):
        """
        Muestra el formulario 
        """
        form = PostForm(request.POST)
        if not form.is_valid():
            messages.error(request, 'Valide los errores')
            output = {
                'form': form,
            }
            return render(request, self.template_name, output)

        form.save()
        messages.success(request, 'Post registrado exitosamente')
        return HttpResponseRedirect(reverse('post:index'))
Example #27
0
def post_create(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            new_post = Post(
                title=data['title'],
                content=data['content'],
            )
            new_post.save()
            return redirect('/')
    context = {'form': form}

    return render(request, 'post/post_create.html', context)
Example #28
0
def post_create(request):
    if request.method == "POST":
        post_form = PostForm(request.POST, request.FILES)
        if post_form.is_valid():
            title = post_form.cleaned_data['title']
            photo = post_form.cleaned_data['photo']
            content = post_form.cleaned_data['content']
            Post.objects.create(title=title, photo=photo, content=content)
            return redirect('post_list')
    else:
        post_form = PostForm()
    context = {
        'post_form': post_form,
    }
    return render(request, 'post/post_create.html', context)
Example #29
0
def post_create(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            Post.objects.create(
                comment=comment,
                author=request.user,
            )
            return redirect('post_list')
    else:
        form = PostForm()
    context = {'form': form}

    return render(request, 'post/post_create.html', context)
Example #30
0
def create_post(request, *args, **kwargs):
    form = PostForm(request.POST or None, request.FILES or None)

    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.save()
        messages.success(request, "Your post has been created")
        return redirect("index")

    context = {
        'post_form': form,
    }

    return render(request, 'user/create_post.html', context)
Example #31
0
def submit(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            post_form = PostForm(data=request.POST)

            if post_form.is_valid():
                post = post_form.save(commit=False)

                post.author = request.user
                post.save()
                return redirect('/')
            else:
                return post_list(request, post_form)
    else:
        redirect('/auth/login.html')
    return redirect('/')
Example #32
0
 def get(self, request, **kwargs: dict) -> render:
     if not Profile.objects.filter(custom_url=kwargs['user_url']).exists():
         raise Http404()
     self.context = self.get_menu_context('profile', 'Профиль')
     self.context['profile'] = Profile.objects.get(custom_url=kwargs['user_url'])
     user_item = User.objects.get(profile=Profile.objects.get(custom_url=kwargs['user_url']))
     self.context['c_user'] = user_item
     post_image_form_set = modelformset_factory(
         PostImages, form=PostImageForm, extra=10, max_num=10
     )
     pass_add_to_friends = False
     is_blacklisted = False
     if user_item != request.user:
         pass_add_to_friends = self.is_in_friend_list(pass_add_to_friends, request, user_item)
         is_blacklisted = self.is_in_blacklist(is_blacklisted, request, user_item)
     self.context['is_in_blacklist'] = is_blacklisted
     self.context['is_friend'] = True if request.user in user_item.profile.friends.all() \
                                    and request.user != user_item else False
     self.context['pass_add_to_friends'] = pass_add_to_friends
     self.context['postform'] = PostForm()
     self.context['formset'] = post_image_form_set(queryset=PostImages.objects.none())
     if not is_blacklisted:
         self.pagination_elements(
             request,
             list(reversed(user_item.profile.posts.all())),
             self.context,
             'c_user_posts'
         )
     self.context['action_type'] = reverse('profile-post-create')
     return render(request, self.template_name, self.context)
Example #33
0
def new_post(request):
    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            obj = Post(author=request.user,
                       timestamp=timezone.now(),
                       description=form.cleaned_data.get('description'),
                       image=form.cleaned_data.get('image'))
            obj.save()

            return redirect('/post/%d/' % obj.id)

    context = dict()
    context['form'] = PostForm()

    return render(request, 'post_new.html', context)
Example #34
0
    def get_context(self, request):
        self.post_instance = get_object_or_404(
            Post.objects_from_local_language,
            slug_title=self.kwargs.get("title"))
        self.content_instance = self.get_instance(
            Content, self.kwargs.get("content_pk"))
        if self.content_instance:
            self.image_instance = self.content_instance.get_image()
            print(self.image_instance)

        self.post_form = PostForm(instance=self.post_instance)
        self.content_form = self.get_form(request,
                                          ContentUpdateForm,
                                          instance=self.content_instance)
        self.image_form = self.get_form(request,
                                        ImageForm,
                                        instance=self.image_instance)
        context = {
            "post_form": self.post_form,
            "content_form": self.content_form,
            "post_instance": self.post_instance,
            "image_form": self.image_form,
            "content_pk": self.kwargs.get("content_pk")
        }
        return context
Example #35
0
File: post.py Project: jcasmer/blog
    def post(self, request, *args, **kwargs):
        """
        Muestra el formulario 
        """
        post = PostBlog.objects.get(id=kwargs['id'])
        form = PostForm(request.POST, instance=post)
        if not form.is_valid():
            messages.error(request, 'Valide los errores')
            output = {
                'form': form,
            }
            return render(request, self.template_name, output)

        form.save()
        messages.success(request, 'Post actualizado exitosamente')
        return HttpResponseRedirect(reverse('post:index'))
Example #36
0
        def get(self, request, community_url):
            """
            Representation of community page

            :param community_url: community custom_url field
            :type community_url: str
            :param request: object with request details
            :type request: :class:`django.http.HttpRequest`
            :return: responce object with HTML code
            :rtype: :class:`django.http.HttpResponse`
            :raises: :class:`django.http.Http404` if custom url not valid
            """
            context = self.get_menu_context('community', 'Сообщество')

            context['community'] = get_object_or_404(Community,
                                                     custom_url=community_url)

            post_image_form_set = modelformset_factory(PostImages,
                                                       form=PostImageForm,
                                                       extra=10,
                                                       max_num=10)

            context['postform'] = PostForm()
            context['formset'] = post_image_form_set(
                queryset=PostImages.objects.none())

            context['action_type'] = '/post/create/{}/'.format(community_url)

            return render(request, self.template_name, context)
Example #37
0
 def get_context(self, request):
     self.post_instance = get_object_or_404(Post.objects_from_local_language, slug_title=self.kwargs.get("title"))
     self.post_form = PostForm(instance=self.post_instance)
     self.image_form = self.get_form(request, ImageForm, None)
     self.content_form = self.get_form(request, ContentNewForm, None)
     context = {"post_form": self.post_form, "content_form": self.content_form,
                "image_form": self.image_form, "post_instance": self.post_instance}
     return context
Example #38
0
def post_modify(request, post_pk):
    post = Post.objects.get(pk=post_pk)
    next = request.GET.get('next')
    # if request.method == 'GET':
    #     forms = ModifyPost(initial={'image': post.image})
    #     context = {
    #         'forms': forms,
    #         'post': post,
    #     }
    #     return render(request, 'post/post_modify.html', context=context)
    #
    # elif request.method == 'POST':
    #     forms = ModifyPost(request.POST, request.FILES)
    #     if forms.is_valid():
    #         post.image = request.FILES['image']
    #         post.save()
    #         return redirect('post:post_detail', post_pk=post.id)
    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES, instance=post)
        if form.is_valid():
            form.save()
            if next:
                return redirect(next)
            return redirect('post:post_detail', post_pk)
    else:
        form = PostForm(instance=post)
    context = {
        'form': form,
    }
    return render(request, 'post/post_modify.html', context=context)
Example #39
0
def post_update(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    form = PostForm(request.POST or None,
                    request.FILES or None,
                    instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, 'Post Updated')
        return HttpResponseRedirect(instance.get_absolute_url())
    else:
        messages.error(request, 'Post not updated')
    return render(request,
                  'post_form.html',
                  context={
                      'post': instance,
                      'form': form
                  })
Example #40
0
def post(req):
    if req.method == 'POST':
        form = PostForm(req.POST)
        if form.is_valid():
            formData = form.cleaned_data
            articles = Post(
                author =  User.objects.get(username=req.user.username),
                title = formData['title'],
                category = Category.objects.get(name=formData['category']),
                content = formData['content']
            )
            articles.save()

        return HttpResponseRedirect('/')

    else:
        form = PostForm()

    return render(req, 'write.html', {'form': form})
Example #41
0
def write_post(request):
    lastposts = Post.objects.all()
    cat = Category.objects.all()
    layout = 'vertical'

    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.save()
            return home(request)
    else:
        form = PostForm()

    return render_to_response('writepost.html', RequestContext(request, {
        'form': form,
        'layout': layout,
        'cat':cat,
        'lastposts':lastposts,
        }))
Example #42
0
def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST, 
                        request.FILES)
        if form.is_valid():
            # set user to form instance
            form.instance.user = request.user

            # save form, create post
            post = form.save()

            # add resize image task to celery
            resize_post_image.delay(post)

            messages.success(request, _("Post created succesfully."))
            return redirect("my_posts")
    else:
        form = PostForm()

    return render(request, 'post/create_post.html', {
        'form': form,
    })
Example #43
0
 def post(self, request):
     """
     Crea un post en base a la información POST
     :param request: HttpRequest
     :return: HttpResponse
     """
     success_message = ""
     post_with_owner = Post()
     blog = self.get_blogs_queryset(request.user.username).all()
     post_with_owner.blog = blog[0]
     post_with_owner.owner = request.user  # asigno como propietario de la foto, el usuario autenticado
     form = PostForm(request.POST, instance=post_with_owner)
     if form.is_valid():
         new_post = form.save()  # Guarda el objeto Photo y me lo devuelve
         form = PostForm()
         success_message = "Guardado con éxito!"
         success_message += '<a href="{0}">'.format(
             reverse("post_detail", args=[new_post.blog.owner.username, new_post.pk])
         )
         success_message += "Ver post"
         success_message += "</a>"
     context = {"form": form, "success_message": success_message}
     return render(request, "post/new_post.html", context)
Example #44
0
def sendPost(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            form.instance.user = request.user
            form.save(commit=True)
            messages.success(request, _("Send Post Succesfully."))
            return redirect('index')
    else:
        form = PostForm()

    return render(request, 'post/sendpost.html', {'form': form})
Example #45
0
def save_post(request, post_id=None):
    post = post_id is None and Post(user_id=request.user.id) \
        or get_object_or_404(Post, id=post_id)
    if request.POST:
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            return redirect('edit_post', post.id)
    else:
        form = PostForm(instance=post)
    images = Image.objects.filter(user_id=request.user.id)
    form.new = post_id is None or False
    return render(request, 'post/form.html', {'form': form,
                                              'images': images})
Example #46
0
 def post(self, request):
     form = PostForm(data=request.POST, author=request.user)
     if form.is_valid():
         form.save()
         return HttpResponseRedirect(reverse("home:index"))
     return render(request, "post/create.html", {"form": form})