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>
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.
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>
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)
I have a pretty simple contact us form but the success_url is not working. The page isn't getting redirected to home after successful form submission.
I've followed the documentation available here https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/
class ContactFormView(SuccessMessageMixin, FormView):
form_class = ContactForm
template_name = 'contact.html'
success_message = 'Thank you!'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.send_email()
return super(ContactFormView, self).form_valid(form)
form_valid is being called but redirection to sucess_url doesn't happen and there are no errors.
Thanks for your help.
-------------UPDATED-----------------
forms.py
class ContactForm(forms.Form):
name = forms.CharField(widget = TextInput(attrs={'placeholder': 'Your Name'}))
email = forms.CharField(widget = EmailInput(attrs={'placeholder': 'Email'}))
phone = forms.CharField(widget = TextInput(attrs={'placeholder': 'Phone'}))
comment = forms.CharField(widget = forms.Textarea(attrs={'placeholder': 'Please write a comment'}))
def send_email(self):
# send email using the self.cleaned_data dictionary
print("email sent!")
urls.py
import web.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^contact/', web.views.ContactFormView.as_view(), name='contact'),
url(r'^$', web.views.home, name='home')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
contact.html
<div class="as-form">
<form method="post" class="myform" action="{% url 'contact' %}">
{% csrf_token %}
{% if form.errors %}{{ form.errors }}{% endif %}
<p> {{form.name}} </p>
<p> {{form.phone}} </p>
<p> {{form.email}} </p>
<p class="as-comment"> {{form.comment}} </p>
<hr>
<p class="as-submit"> <input type="submit" value="Submit" class="as-bgcolor"> </p>
</form>
</div>
I don't know how you set it up but the below works brilliantly (Django 1.10, Python 3.5)
# urls.py
urlpatterns = [
url(r'^$', home_view, name='home'),
url(r'^form/$', ContactFormView.as_view(), name='contact')
]
# forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=20)
def send_email(self):
print('Email sent!')
# views.py
# Your ContactFormView as is
# contact.html
<form action="" method="post">{% csrf_token %}
{% if form.errors %}{{ form.errors }}{% endif %}
{{ form.as_p }}
</form>