async def ad_create(request):
    """
    Ad create form
    """
    u = User
    session_user = (
        await u.select(u.id, u.username)
        .where(u.username == request.user.username)
        .first()
        .run()
    )
    data = await request.form()
    form = AdForm(data)
    title = form.title.data
    if request.method == "POST" and form.validate():
        query = Ad(
            title=title,
            slug="-".join(title.lower().split()),
            content=form.content.data,
            created=datetime.datetime.now(),
            view=0,
            price=form.price.data,
            room=form.room.data,
            visitor=form.visitor.data,
            city=form.city.data,
            address=form.address.data,
            ad_user=session_user["id"],
        )
        await query.save().run()
        return RedirectResponse(url="/ads/images", status_code=302)
    return templates.TemplateResponse(
        "ads/ad_create.html", {"request": request, "form": form}
    )
Exemplo n.º 2
0
 def test_form_invalid(self):
     data = {
         'title': '',
         'content': '',
         'date': '',
         'contact': '',
         'city': ''
     }
     form = AdForm(data=data)
     self.assertFalse(form.is_valid())
Exemplo n.º 3
0
 def test_form_valid(self):
     form_data = {
         'title': "title",
         'content': "content",
         'city': self.city.id,
         'date': datetime.date.today(),
         'contact': "contact"
     }
     form = AdForm(data=form_data)
     self.assertTrue(form.is_valid())
Exemplo n.º 4
0
    def post(self, request, pk: int):
        ad = get_object_or_404(Ad, pk=pk, owner=request.user)
        form = AdForm(request.POST, request.FILES or None, instance=ad)
        
        if not form.is_valid():
            context = {'form': form}
            return render(request, self.template_name, context)

        ad = form.save(commit=False)
        ad.save()
        return redirect(self.success_url)
Exemplo n.º 5
0
    def post(self, request, pk: int = None):
        form = AdForm(request.POST, request.FILES or None)

        if not form.is_valid():
            context = {'form': form}
            return render(request, self.template_name, context)

        # Add owner to the model before saving
        ad = form.save(commit=False)
        ad.owner = request.user
        ad.save()
        return redirect(self.success_url)
Exemplo n.º 6
0
def create(request):
    page = request.GET.get("page", 1)
    ads = Ad.objects.filter().order_by("-created_at")
    p = Paginator(ads, settings.ITEMS_PER_PAGE)
    if request.method == 'GET':
        ads = Ad.objects.all()
        form = AdForm()
        return render(request,
                      'create.html',
                      context={
                          "form": form,
                          'page': p.page(page),
                      })
    elif request.method == 'POST':
        form = AdForm(request.POST, request.FILES)
        if form.is_valid():
            ad = form.save(commit=False)
            ad.author = request.user
            form.save()
            return render(request,
                          'create_success.html',
                          context={
                              'page': p.page(page),
                          })
        else:
            return render(request,
                          'create.html',
                          context={
                              "form": form,
                              'page': p.page(page),
                          })
Exemplo n.º 7
0
 def get(self, request):
     """
     Muestra el formulario para crear un anuncio
     :param request: objeto HttpRequest
     :return: HttpResponse con la respuesta
     """
     form = AdForm()
     context = {'form': form}
     return render(request, 'ads/form.html', context)
Exemplo n.º 8
0
 def post(self, request):
     ad_form = AdForm(request.POST)
     formset = formset_factory(ImageForm, max_num=5)
     image_form_set = formset(request.POST, request.FILES)
     if ad_form.is_valid() and image_form_set.is_valid():
         new_ad = ad_form.save(commit=False)
         new_ad.save()
         for form in image_form_set.forms:
             if form.cleaned_data:
                 image = form.save(commit=False)
                 image.ad = new_ad
                 image.save()
         messages.success(request, 'Your ad successfully saved!')
         return redirect('/advert/%s/' % new_ad.id)
     else:
         return render(request, 'addition.html', {
             'ad_form': ad_form,
             'image_form_set': image_form_set
         })
Exemplo n.º 9
0
def add_ad(request):
    if request.method == 'GET':
        form = AdForm()
        return render(request, 'ads/add_ad.html', {'form': form})
    elif request.method == 'POST':
        form = AdForm(request.POST, request.FILES)
        if form.is_valid():
            new_obj = Ads.objects.create(
                author=request.user,
                title=form.cleaned_data['title'],
                category=form.cleaned_data['category'],
                phone=form.cleaned_data['phone'],
                price=form.cleaned_data['price'],
                content=form.cleaned_data['content'],
            )
            for f in request.FILES.getlist('photos'):
                data = f.read()
                photo = Images(ad=new_obj)
                photo.img.save(f.name, ContentFile(data))
                photo.save()
            return redirect(new_obj)
        else:
            return render(request, 'ads/add_ad.html', {'form': form})
Exemplo n.º 10
0
 def post(self, request):
     """
     Procesa el formulario para crear un anuncio
     :param request: objeto HttpRequest
     :return: HttpResponse con la respuesta
     """
     ad = Ad()
     ad.owner = request.user
     form = AdForm(request.POST, request.FILES, instance=ad)
     if form.is_valid():
         # creamos el anuncio
         ad = form.save()
         # limpiar el formulario
         form = AdForm()
         # Devolvemos un mensaje de OK
         messages.success(request, 'Anuncio creado correctamente')
     context = {'form': form}
     return render(request, 'ads/form.html', context)
Exemplo n.º 11
0
def edit_ad(request, pk):
    current_ad = Ads.objects.get(pk=pk)
    if request.user == current_ad.author:
        if request.method == "POST":
            form = AdForm(request.POST, request.FILES, instance=current_ad)

            if form.is_valid():
                form.save()
                for f in request.FILES.getlist('photos'):
                    data = f.read()
                    photo = Images(ad=current_ad)
                    photo.img.save(f.name, ContentFile(data))
                    photo.save()
                messages.success(request, 'Ваше объявление успешно обновлено')
                return redirect('edit_ad', pk=pk)
        else:
            form = AdForm(instance=current_ad)
    else:
        return redirect('home')

    data = {'form': form, 'current_ad': current_ad}

    return render(request, 'ads/edit_ad.html', data)
Exemplo n.º 12
0
 def get(self, request, pk: int):
     ad = get_object_or_404(Ad, pk=pk, owner=request.user)
     form = AdForm(instance=ad)
     context = {'form': form}
     return render(request, self.template_name, context)
Exemplo n.º 13
0
 def get(self, request, pk: int = None):
     form = AdForm()
     context = {'form': form}
     return render(request, self.template_name, context)
Exemplo n.º 14
0
 def test_updating_published_at(self):
     "Published_at is not updated after creating."
     published_at = self.ad.published_at
     form = AdForm(self.data, instance=self.ad)
     instance = form.save()
     self.assertEquals(instance.published_at, published_at)