I want to allow user to search in database for the topic. and show the topic name in url.
I already created slug field in database but when i am trying to fetch the data from the database the url is not showing correctly.
url is showing:
http://127.0.0.1:8000/topic/<slug:topicname>/
what I want to show:
http://127.0.0.1:8000/topic/introduction-to-python/
My urls.py file
from django.urls import path
from . import views
urlpatterns = [
path('', views.apphome),
path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'),
]
My model for the project
class blogposts(models.Model):
topic = models.CharField(max_length = 200)
slug = models.SlugField(max_length = 150, null=True, blank = True)
post = models.TextField(max_length = 500)
def __str__(self):
return self.topic
This is my view
def searchtopic(request,topicname):
if request.method == 'POST':
topicname = request.POST.get('searchtopicname')
mypost = mypostlist.objects.filter(slug = topicname)
context = {
'mypost':mypost,
}
return render(request, 'blog/result.html',context)
My form for searching topic
<form action="topic/<slug:topicname>/" method="POST">
{% csrf_token %}
<input type="search" placeholder="Search topics or keywords" name="searchtopicname">
<button type="submit">Search</button>
</form>
You can use 'GET' method insted of 'POST'
replace form with:
<form action="{%url 'searchtopic' %}" method="GET">
{% csrf_token %}
<input type="search" placeholder="Search topics or keywords" name="searchtopicname">
<button type="submit">Search</button>
</form>
replace urls.py:
urlpatterns = [
path('', views.apphome),
path('topic/', views.searchtopic, name = 'searchtopic'),
]
replace views:
def searchtopic(request):
if request.method == 'GET':
topicname = request.GET['searchtopicname']
mypost = mypostlist.objects.filter(slug = topicname)
context = {
'mypost':mypost,
}
return render(request, 'blog/result.html',context)
Related
I'm learning Django and am running into an issue posting a piece of data to the database. Here's my code:
urls.py
urlpatterns = [
path("", views.index, name="index"),
...
path("listing/<int:listing_id>", views.display_listing, name="listing")
]
Models.py
class Bid(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usr_bids')
price = models.DecimalField(max_digits=5, decimal_places=2)
class Listing(models.Model):
title = models.CharField(max_length=50)
bids = models.ManyToManyField(Bid, blank=True, related_name='bids')
price = models.DecimalField(max_digits=7, decimal_places=2)
closed = models.BooleanField(default=False)
Forms.py
class BidForm(ModelForm):
class Meta:
model = Bid
fields = ['price']
views.py
def display_listing(request, listing_id):
listing = Listing.objects.get(pk=listing_id)
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('login'))
if request.method == "POST":
user = User.objects.get(username=request.user)
if request.POST.get("button") == "Watchlist":
if not user.watchlist.filter(listing=listing):
watchlist = Watchlist()
watchlist.user = user
watchlist.listing = listing
watchlist.save()
else:
user.watchlist.filter(listing=listing).delete()
return HttpResponseRedirect(reverse('listing', args=(listing.id, )))
if not listing.closed:
if request.POST.get("button") == "Close":
listing.closed = True
listing.save()
else:
price = float(request.POST["price"])
bids = listing.bids.all()
if user.username != listing.creator.username:
if price <= listing.price:
return render(request, 'auctions/listing.html',{
'listing': listing,
'form': BidForm(),
'message': 'Increase your bid.'
})
form = BidForm(request.POST)
if form.is_valid():
bid = form.save(commit=False)
bid.user = user
bid.save()
listing.bids.add(bid)
listing.price = price
listing.save()
else:
return render(request, 'auctions/listing.html', {
'form': form
})
return HttpResponseRedirect(reverse('listing', args=(listing.id, )))
else:
return render(request, 'auctions/listing.html', {
'listing': listing,
'form': BidForm(),
'comments': listing.comments.all()
})
auction/listings.html
<div>
<form action="{% url 'listing' listing.id %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="bid">{{ listing.bids.count }} bid(s) so far. You have the best bid!.</label>
</div>
<div class="form-group">
{{ form }}
</div>
<div class="form-group">
<input type="submit" name="button" class="btn btn-primary" value="Send Bid">
</div>
</form>
</div>
I populate a value (e.g. 300) in the price field. Then, I click the "Send Bid" button. Unfortunately, nothing happens.
Does anyone see why I'm unable to save a price to the database? Thanks in advance for taking a look!
At a first glance, you should rather have something like:
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" name="button" class="btn btn-primary" value="Send Bid">
</form>
in your template.
I am trying to create a search button for my database. But my self.request.POST.get('searched') is returning None
the form:
<form class="d-flex" action="{% url 'asset_app_search' %}">{% csrf_token %}
<input class="form-control me-2" type="search" placeholder="Søg" aria-label="Search" name="searched">
<button class="btn btn-outline-secondary" type="submit">Søg</button> -
</form>
my views.py
class SearchView(generic.TemplateView):
template_name = "asset_app/search.html"
def post(self):
searched = self.request.POST.get('searched')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
searched = self.post()
context['searched'] = searched
context_entry_today = datetime.date.today()
context_entry_overdue = datetime.date.today() - datetime.timedelta(days=90)
context_entry_inspection_time = datetime.date.today() - datetime.timedelta(days=76)
context['assets'] = models.Asset.objects.order_by('name')
context['rooms'] = models.Room.objects.order_by('last_inspected', 'location', 'name')
context['bundelReservations'] = models.Bundle_reservation.objects.order_by('return_date')
context['loan_assets'] = models.Loan_asset.objects.order_by('return_date')
context['to_dos'] = to_do_list_app.models.Jobs.objects.all()
context['today'] = context_entry_today
context['overdue'] = context_entry_overdue
context['inspection_time'] = context_entry_inspection_time
return context
and what is beeing posted
[11/Jun/2021 22:55:23] "GET /asset/search/?csrfmiddlewaretoken=fqb8jppygSbZ10ET8AXw6dd5B77z5OYudNJU0uyjp8jFNYDG57nkNvrcx5lHFsPo&searched=sdfdsff HTTP/1.1" 200 10418
You should let the form make a POST request, with:
<form method="post" class="d-flex" action="{% url 'asset_app_search' %}">{% csrf_token %}
…
</form>
You thus specify method="post" in the <form> tag.
In your view, your post method will eventually have to return a HttpResponse object:
class SearchView(generic.TemplateView):
template_name = "asset_app/search.html"
def post(self):
searched = self.request.POST.get('searched')
# …
return HttpResponse('some message')
This is my first Django project, however, I have a problem submitting the form.
I'm getting 'CSRF verification failed'. It's a very simple form just 2 fields(frontpage) and on submit to display the same page.
views.py
def newsletter(request):
if request.method == 'POST':
name = request.POST('name')
email = request.POST('email')
newsletter = Newsletter(name = name, email = email)
newsletter.save()
return HttpResponseRedirect('')
models.py
class Newsletter(models.Model):
name = models.CharField(max_length = 200)
email = models.CharField(max_length=100)
publish_date = models.DateTimeField(default = datetime.now, blank = True)
def __str__(self):
return self.name
admin.py
class NewsletterAdmin(admin.ModelAdmin):
list_display = ('name','publish_date')
admin.site.register(Newsletter, NewsletterAdmin)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name = 'home'),
path('events/', events, name = 'events'),
path('news/', news, name = 'mainnews'),
path('about/', about, name = 'about'),
path('', newsletter),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
html>
<div>
<form method = 'post'>
{% csrf_token %} {{ form.as_p }}
<input name = 'name' type = 'text' value = "{{ newsletter.name }}">
<input name = 'email' type = 'email' value = "{{ newsletter.email }}">
<button type = 'submit' name = 'save'>Send</button>
</form>
</div>
Write your form like this:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" value="Submit"></button>
</form>
Im new to Django. I am trying to create product archvisation, but when i click on the button to archive i've got error ,,Method Not Allowed (POST)". Dunno how to deal with it.
Here is my code
views.py
def to_archive(request):
if request.method == 'POST':
product = request.POST['to_archive']
product_archive = Product.objects.get(id=product)
if not product_archive.is_active:
product_archive.is_active = True
product_archive.archived_date = timezone.now
product_archive.save()
models.py
class Product(models.Model):
is_archived = models.BooleanField(_('Archive'), default=False)
archived_date = models.DateTimeField(_('Date Archived'), blank=True, null=True)
form in html file
<form action="{% url 'to_archive' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="to_archive" value="{{ object }}">
<input id="disactive_button" type="submit" class="btn btn-primary" value="To archive">
</form>
urls.py
urlpatterns = [
path('', IndexView.as_view(), name='home'),
path('to_archive/', to_archive, name='to_archive'),
]
Error:
Method Not Allowed (POST): /product/chair/
Method Not Allowed: /product/chair/
[09/Sep/2020 13:29:27] "POST /product/chair/ HTTP/1.1" 405 0
urls.py:
def shopgrid(request, proname=None):
products = Product.objects.all()
categories = Categories.objects.all()
recent_products = Product.objects.order_by('-date')[0:3]
if proname != None:
products = Product.objects.filter(categorie__title=proname)
if request.method == "GET":
recent = request.GET.get('val')
amount = request.GET.get('amount')
print('This is amount--->',amount)
if recent == 'name':
products = Product.objects.order_by('name')
if recent == 'price':
products = Product.objects.order_by('-price')
if 'val' in request.GET:
check_values = request.GET.getlist('val')
first_element=check_values[0]
last_element=check_values[-1]
fe = first_element[0:4]
le = last_element[-4:]
min_price = int(fe)
max_price = int(le)
products = Product.objects.filter(price__range=(min_price, max_price))
print(products)
context={'p':products, 'rp':recent_products, 'cat':categories}
return render(request, 'cart/shop-grid.html', context)
urls.py:
urlpatterns = [
path('', views.index, name="index"),
path('shopgrid/', views.shopgrid, name="shopgrids"),
path('shopgrid/<str:proname>/', views.shopgrid, name="shopgrid"),
path('cat_sort/<str:proname>/', views.cat_sort, name="cat_sort"),
]
ERROR:
**Reverse for 'shopgrid' with no arguments not found. 1 pattern(s) tried: ['shopgrid/(?P<proname>[^/]+)/$']**
<form id="priceform" action="**{% url 'shopgrid' %}**" method="GET">
{% csrf_token %}
<input type="text" id="amount" name="amount" placeholder="Add Your Price">
</form>
def shopgrid(request, proname=None):
proname is an optional parameter.Question is how to write optional parameter in Jinja template.
i already write a proname=None but I am facing error only HTML
The name of the view without a parameter is shopgrids, so the url should be:
<form id="priceform" action="{% url 'shopgrids' %}" method="GET">
{% csrf_token %}
<input type="text" id="amount" name="amount" placeholder="Add Your Price">
</form>