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
Related
I tried to create a simple Django Chat App. There is no login system.
Whenever a user(e.g. John) tries to create a message, it stores under 'messageroom'
I tried to pass the username 'John' value in the URL but somehow it is not creating a message as expected.
Here is my code
Urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('checkview',views.checkview,name='checkview'),
path('messageroom/<str:room_name>/<str:username>',views.messageroom,name='messageroom'),
]
Models.py
class Room(models.Model):
roomname = models.CharField(max_length=1000)
class Message(models.Model):
messagetext = models.CharField(max_length=10000)
username = models.CharField(max_length=1000)
datetime = models.DateTimeField(default=datetime.now,blank=True)
messageroom = models.CharField(max_length=1000)
Views.py
def home(request):
return render(request,'home.html',{})
def checkview(request):
room_name=request.POST.get('room_name')
username = request.POST.get('username')
Roomexists = Room.objects.filter(roomname=room_name)
if Roomexists.exists():
return redirect('messageroom/'+room_name+'/'+username)
else:
newroom = Room(roomname=room_name)
newroom.save()
return redirect('messageroom/'+room_name+'/'+username)
def messageroom(request,room_name,username):
if request.method == "POST":
messagetext = request.POST.get('message')
newmessage = Message(messagetext=messagetext,messageroom=room_name,username=username)
newmessage.save()
listmessages = Message.objects.filter(messageroom=room_name)
return render(request, 'room.html', {'listmessages':listmessages,'room_name':room_name,'username':username})
Room.html
<form id="post-form2" method="POST" action="messageroom">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
I want to create messages under the user which should be there on the URL.
you should pass values in urls in html form like this....
<form id="post-form2" method="POST" action="{% url 'messageroom' room_name username %}">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
-------------------------- OR ------------------
<form id="post-form2" method="POST" action="/messageroom/room_name/username/">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
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>
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 am making a Django website where I need to display images selected by user.
These are the things I've done:
Html form for image:
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<label >Article Logo</label>
<input type="file" class="btn btn-primary" name="article_image">
</div>
<input type="submit" class="btn btn-success">
</form>
models.py
class Content(models.Model):
article_image = models.ImageField(upload_to = 'media', null=True)
views.py
def submit_article(request):
if request.method == 'POST':
a_image = request.FILES['article_image']
new_article.article_image = a_image
new_article.save()
I've added below code to settings.py to specify media directory:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Added below code to urls.py of the website:
urlpatterns = [
path(r'admin/', admin.site.urls),
url(r'', include('logio.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The form is not able to add images to the media folder. If I'm adding images through the admin panel it works.
Thanks in advance....
You need to add enctype="multipart/form-data" to your form, like this:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
For more information, please check the documentation.
Just a suggestion, it is better to use a Django form to handle this. For example, you can have a form:
class ContentForm(forms.ModelForm):
class Meta:
model = Content
fields = ['article_image']
Then pass this form via context to template and render it:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="submit'>
</form>
Finally, handle validation in view:
def submit_article(request):
if request.method == 'POST':
form = ContentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
...
Here is what i have in base.html (inside the footer, so this newsletter form will be in every page)
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder='Enter email address' onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'">
<div class="input-group-append">
<button class="btn" type="submit"><span class="lnr lnr-arrow-right"></span></button>
</div>
</div>
</div>
</form>
Here is the model (subscribe/models.py)
class Subscriber(models.Model):
email = models.EmailField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
what i have in views.py
def subscribe_form(request):
if request.method == 'POST':
email = request.POST.get('email')
new_email = Subscriber()
new_email.email = email
new_email.save()
return redirect('home-page')
here is urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.PostListView.as_view(), name='home-page'),
path('subscribe/', views.subscribe_form, name='subscriber'),
path('archive/', views.archive, name='archive-page'),
path('category/', views.category, name='category-page'),
path('contact/', views.contact, name='contact-page')
]
after submitting the submit button i'm getting this error in shell
Method Not Allowed (POST): /
Method Not Allowed: /
[18/Jan/2020 04:13:11] "POST / HTTP/1.1" 405 0
so, i'm a beginner, im trying to build a blog, but i didn't find any useful solution that can solve this issue. maybe i'm going totally wrong, but anyway if someone can help me to make this working.
Thank you all.
In your index URL, you are not allowed to post.So change it to subscribe/
<form action="{% url 'subscriber' %}" method="POST>