I want to save data from HTML template into database Model. I want to override this toplaner_name, toplaner_avatar, toplaner_price everytime I submit the Form. The img and span tags are dynamically changing by JS
template
<form method='POST'>
{% csrf_token %}
<div class="player-on-map toplaner">
<img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map">
<span class="nickname">Szygenda</span>
<span>Price: 1500</span>
</div>
<button type='submit'>SAVE TEAM</button>
</form>
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return f'{self.user.username} Profile'
class Team(models.Model):
toplaner_name = models.CharField(max_length=30, default='k1ck/Ibo')
toplaner_avatar = models.ImageField(default='avatar.png')
toplaner_price = models.IntegerField()
JS
toplaners.forEach(toplaner => toplaner.querySelector('.btn').addEventListener('click', function(){
toplaner_on_map.innerHTML = toplaner.innerHTML;
toplaner_on_map.querySelectorAll('.btn, .position, .player-price').forEach(item => item.classList.add('hide'))
}))
urlpatterns = [
path('', views.home, name='home'),
path('register/', views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='profilecontent/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='profilecontent/logout.html'), name='logout'),
path('profile/', views.profile, name='profile')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
First of all you have to make one URL in urls.py as below...
urlpatterns = [
path('', views.home, name='home'),
path('register/', views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='profilecontent/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='profilecontent/logout.html'), name='logout'),
path('profile/', views.profile, name='profile'),
# Add new URL
path('toplaner/', views.toplaner, name='toplaner'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then add toplaner view in views.py as below...
def toplaner(request):
# Here you can get all the form data
if request.method == 'POST':
field_name = request.POST.get('field_name_in_html_form')
# Add all other required field here
Then you have to add action url in form as below...
<form method='POST' action="{% url 'toplaner' %}">
{% csrf_token %}
<div class="player-on-map toplaner">
<img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map">
<span class="nickname">Szygenda</span>
<span>Price: 1500</span>
</div>
<button type='submit'>SAVE TEAM</button>
</form>
Now, when you press submit button you will get your form data in toplaner view and at there you can write your further logic.
Related
The Form in register.html request for POST method but GET method is working. Submit is calling register method in views.py using GET method, but this shouldn't be happening.
Error :
Request Method: POST
Request URL: http://127.0.0.1:8000/Profile/register/register/
views.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib import messages
def register(request):
if request.method == 'POST':
return redirect('/')
else:
return render(request, 'register.html')
register.html
<form action="register" method="post">
{% csrf_token %}
<input type="Submit">
</form>
urls.py of Project
from re import template
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
path('Profile/', include('Profile.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('login/', auth_views.LoginView.as_view(template_name="login.html"),
name='login'),
path('logout/', auth_views.LogoutView.as_view(),
name='logout'),
path('reset_password/', auth_views.PasswordResetView.as_view(),
name = 'reset_password'),
path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete')
]
urls.py of Profile app
from django.urls import path
from Profile import views
urlpatterns = [
path('profile/', views.profile, name='profile'),
path('register/', views.register, name='register'),
]
The URL is register/. Because you do not use a trailing slash, Django will make a redirect with a slash, but that will thus result in a GET request, not a POST request.
You thus should work with:
<form action="/profile/register/" method="post">
{% csrf_token %}
<input type="Submit">
</form>
or better is to work with the {% url … %} template tag [Django-doc]:
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
<input type="Submit">
</form>
I know similar kind of question is asked before, but I was not able to get it. This is my first project as a Django beginner.
In my Django blog app, I made a delete button but it is not working and I am finding for answers, trying different methods on the web but it did not help.
I am trying to do is when admin open the post, then on clicking the delete button, it take the post-id and delete that post and redirect to home page, but it is not working as expected. So, lastly I came here. Any help will be appreciated. Thanks!
This is my urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('post/<int:pk>', views.post, name='post'),
path('about', views.about, name='about'),
path('contact_us', views.contact_us, name='contact_us'),
path('register', views.register, name='register'),
path('login', views.login, name='login'),
path('logout', views.logout, name='logout'),
path('create_post', views.create_post, name='create_post'),
path('delete_post', views.delete_post, name='delete_post')
]
This is my views.py file:
def delete_post(request, *args, **kwargs):
pk = kwargs.get('pk')
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
post.delete()
return redirect('/')
return render(request, 'delete-post.html')
This is delete post html form:
<form action="{% url 'delete_post' post.id %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete post">
</form>
Delete button:
<button type="button" class="btn btn-danger" style="position:relative; right: -1145px;">Delete</button>
for deleting a post
def delete_post(request, id):
post = Post.objects.filter(id=id)
address.delete()
return redirect('/')
and in your html
<a class="btn btn-outline-danger" href="{% url 'appname:delete_post' id=post.id %}">Delete It</a>
and in your urls.py
path('<int:id>/delete-post',views.delete_post,name='delete_post')
I am. trying to. build a search function for my django project base on the enter link description here
and the error message popped out "Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name."
i have done the searching most of the advise asking me to check if the spelling is error
like my "search" in url or my search.html in my render
however, i have tried all the solution it still can't work
here is some of my code
urls.py:
from django.contrib import admin
from django.urls import path
from pages.views import home_view, contact_view, about_view
from products.views import product_detail_view, product_create_view, vendor_data,search_product
urlpatterns = [
path('', home_view, name='home'),
path('contact/', contact_view),
path('about/', about_view),
path('create/', product_create_view),
path('product/', product_detail_view),
path('search/', search_product),
path('vendor/', vendor_data),
path('admin/', admin.site.urls),
]
views.py
from django.shortcuts import render
from .models import Product
from .forms import ProductForm, RawProductForm,VendorForm
def search_product(request):
if request.method == "POST":
query_name = request.POST.get('title', None)
if query_name:
results = Product.objects.filter(name__contains=query_name)
return render(request, 'products/search.html', {"results":results})
return render(request, 'products/search.html')
search.html
<!DOCTYPE html>
<html>
<head>
<title>Django Search</title>
</head>
<body>
<form action="{% url 'search' %}" method="POST">
{% csrf_token %}
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
{% for result in results %}
<p>{{result.name}}</p>
{% endfor %}
</body>
</html>
and following is my folder in case if needed
You need to specify the name of the urls.py with the name=… parameter:
urlpatterns = [
# …,
# name ↓
path('search/', search_product, name='search'),
# …
]
Change this file.. urls.py
from django.contrib import admin
from django.urls import path
from pages.views import home_view, contact_view, about_view
from products.views import product_detail_view, product_create_view, vendor_data,search_product
urlpatterns = [
path('', home_view, name='home'),
path('contact/', contact_view),
path('about/', about_view),
path('create/', product_create_view),
path('product/', product_detail_view),
path('search/', search_product, name = 'search'), # changed here
path('vendor/', vendor_data),
path('admin/', admin.site.urls),
]
first i went to url
/idontknow/
the html of the template belonging to this url:
<body>
<form action="{% url 'polls:idk' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</body>
it loaded my form input the data and then submitted the form.
after i submitted it gave me the 405 error , how to solve this such that when i submit i want the same page to reload but with my submiited data inside form.
MY View:
class IDK(FormView):
form_class=NameForm
template_name = "polls/idk.html"
success_url = "polls/idontknow/"
def form_valid(self, form):
print("DATA="+form)
return super(IDK, self).form_valid(form)
my urls:
app_name = "polls"
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('idontknow/', views.IDK.as_view(), name='idk'),
]
So I am trying to display an image on the web page, i save the image path in the database as media/imagename and in my html page i am doing this :
{% for stuff in profile %}
<div class="alert alert-success" role="alert"> {{ stuff.text }} </div>
<img scr='/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media/{{ stuff.thumbnail }}' width="200">
{% endfor %}
And in my settings.py i do this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media')
But the image doesn't display. What am i doing wrong here? Thanks!
Edit:
#urls.py
from django.conf.urls import patterns, url
from django.conf import settings
from social import views
urlpatterns = [
# main page
url(r'^$', views.index, name='index'),
# signup page
url(r'^signup/$', views.signup, name='signup'),
# register new user
url(r'^register/$', views.register, name='register'),
# login page
url(r'^login/$', views.login, name='login'),
# user doesnt exist webpage
url(r'^user-doesnt-exist/$', views.login, name='user-doesnt-exist'),
#page to show that the password is incorrect
url(r'^wrongpass/$', views.login, name='wrongpass'),
#webpage to show an error when a user tries to input nothing in the fields when signing up
url(r'^novalues/$', views.register, name='novalues'),
# logout page
url(r'^logout/$', views.logout, name='logout'),
# members page
url(r'^members/$', views.members, name='members'),
#invites page
url(r'^invites/$', views.invites, name='invites'),
# friends page
url(r'^friends/$', views.friends, name='friends'),
# user profile edit page
url(r'^profile/$', views.profile, name='profile'),
# messages page
url(r'^messages/$', views.messages, name='messages'),
# Ajax: check if user exists
url(r'^checkuser/$', views.checkuser, name='checkuser'),
#commiting again
]
if settings.DEBUG:
urlpatterns += patterns(''(r'^media/(P<path>.*)$','django.views.static.serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes':True})),
Try setting your MEDIA_ROOT to:
MEDIA_ROOT = os.path.join(BASE_DIR, 'social/static/social/media')
MEDIA_URL = '/media/'
And in your project urls.py file add:
from django.conf import settings
from django.conf.urls import patterns
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))
Then, in your template call the image like:
{% if stuff.thumbnail %}
<img src="{{ object.thumbnail.url }}">
{% endif %}
And in models.py:
image = models.ImageField(upload_to='images/')
Here's some great documentation on serving media files, including how to serve them during development.