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>
Related
On my homepage(http://127.0.0.1:8000/) I created a template and its function in views.py and the URL of the homepage directs to it, however, there is a form that I want also to show on the homepage.
views.py:
def index(request):
template = loader.get_template('tracker/index.html')
hours_grouped_project =
LogHours.objects.all().order_by('proj_assignment__project__name', 'day')
context = {
'hours_grouped_project':hours_grouped_project,
}
return HttpResponse(template.render(context,request))
def form(request):
if request.method== 'POST':
form = LogHoursForm(request.POST)
if form.is_valid():
day = form.cleaned_data['day']
hours = form.cleaned_data['hours']
developer = form.cleaned_data['developer']
project = form.cleaned_data['project']
proj_assignment=ProjectAssignment.objects.create(
developer=developer,project=project)
LogHours.objects.create(day=day,hours=hours,
proj_assignment= proj_assignment)
else:
form = LogHoursForm()
return render(request, 'tracker/form.html',{'form': form})
the index is for the template displayed on the homepage, and the form is for the form.py.
form.py
class LogHoursForm(forms.Form):
day = forms.DateField()
hours = forms.DecimalField(max_digits=10, decimal_places=2)
developer = forms.ModelChoiceField(queryset=Developer.objects.all())
project = forms.ModelChoiceField(queryset=Project.objects.all())
and here is the URL: urlpatterns = [
path('', views.index, name='index'),]
the form.html is
<h1> LogHours Form</h1>
<hr>
<form action="" method="post">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
and the index.html:
<ul>
<b>Logged hours grouped by project:</b>
{% for obj in hours_grouped_project %}
<li>
{% ifchanged obj.proj_assignment %}
<b>Project name:</b>
{{obj.proj_assignment|linebreaks}}
{% endifchanged %}
<i>Sorted Date: </i>
{{obj}}
</li>
{% endfor %}
</ul>
In your function index(request):
def index(request):
if request.method=='POST':
form(request)
else:
template = loader.get_template('tracker/index.html')
hours_grouped_project = LogHours.objects.all().order_by('proj_assignment__project__name', 'day')
form = LogHoursForm()
context = {
'hours_grouped_project': hours_grouped_project,
'form': form,
}
return HttpResponse(template.render(context, request))
Then, you can render the form from your index.html like this.
...
<form action="" method="post">
{% csrf_token %}
{{form}}
<input type="submit">
...
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
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 need to make a simple form. I can't understand why I don't see it. When I press a button which must show it, I see POST not GET request in my console. Which is not correct. Here is code:
form:
class DeviceAddForm(django.forms.Form):
name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
device_slug = django.forms.CharField(widget = django.forms.HiddenInput())
model_name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
platfrom = django.forms.ComboField(widget = django.forms.CheckboxInput())
sdk = django.forms.ComboField(widget = django.forms.CheckboxInput())
def __init__(self,request=None,*args,**kwargs):
self.request = request
super(DeviceAddForm,self).__init__(*args,**kwargs)
def clean(self):
if self.request:
if not self.request.session.test_cookie_worked():
raise django.forms.ValidationError("Cookies must be enabled")
return self.cleaned_data
saving data:
DEVICE_ID_SESSION_KEY = 'device_id'
def _device_id(request):
if request.session.get(DEVICE_ID_SESSION_KEY,'') == '':
request.session[DEVICE_ID_SESSION_KEY] = _generate_device_id()
return request.session[DEVICE_ID_SESSION_KEY]
def _generate_device_id():
device_id = ''
chars = '0123456789'
device_id_len = 5
for i in range (device_id_len):
device_id +=chars[random.randint(0,len(chars)-1)]
def get_device(request):
return Device.objects.filter(device_id= _device_id(request))
def add_device(request):
postdata = request.POST.copy()
device_slug = postdata.get('device_slug','')
name = postdata.get('name','')
model_name = postdata.get('model_name','')
platform = postdata.get('platform','')
sdk = postdata.get('SDK','')
d = get_list_or_404(Device, slug = device_slug)
dev = Device()
# dev = d
dev.name = name
dev.model_name = model_name
#dev.sdkID
#dev.plID
dev.id = _device_id(request)
dev.save()
view:
#csrf_exempt
def show_device(request, template_name = "onep_web/deviceForm.html"):
d = get_list_or_404(Device,slug = DeviceAddForm.device_slug)
if request.method == 'POST':
postdata = request.POST.copy()
form = DeviceAddForm(request,postdata)
if form.is_valid():
device.add_device(request)
if request.session.test.cookie_worked():
request.session.delete_test_cookie()
url = urlresolvers.reverse('show_device')
return HttpResponseRedirect(url)
else:
form = DeviceAddForm(request=request, label_suffix=':')
form.field['device_slug'].widget.attr['value'] = DeviceAddForm.device_slug
request.session.set_test_cookie()
# return render_to_response(template_name, locals(),csrf(context_instance RequestContext(request)))
return render_to_response(template_name, {'form':form})
urls:
urls form the app
urlpatterns = patterns('onep_web.views',
(r'^$','show_device',{'template_name':'onep_web/deviceForm.html'},'show_device'))
and some more urls:
urls.py from project
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'welcome_page.home', name='home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^welcome_page/', 'one_web.views.welcome_page'),
url(r'^onep_web/', include('onep_web.urls')),
url(r'^device_page/', 'one_web.views.device_page'),
url(r'^configuration_page/', 'one_web.views.configuration_page'),
url(r'^log_page/', 'one_web.views.log_page'),
)
templates :
it's one from which I call the form
<title>OnePK Web Tool - {%block page %}{% endblock %}</title>
</head>
<body>
<div >
<br>
<div> Welcome to OnePK web-tool</div>
</div>
<form >
<br>
<br>
<br>Username:
<input type="text" name="Username">
<br>Password:
<input type="password" name="pwd">
<br>
<br>
{% block content %}
<h4>List of devices and IP addresses:</h4>
<table border="1">
<tr>
<td>Dev1</td>
<td>Dev2</td>
<td>Dev3</td>
<td>Dev4</td>
</tr>
<tr>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
</tr>
</table>
{% endblock %}
<br>
<br>
<br>
<button type="button" onclick="ping()">Ping elenent</button>
<script>
function ping()
{
}
</script>
<br>
<br>
<label>Connection status</label>
<br>
<button type="button" onclick="openDev()">Connect to element</button>
<script>
function openDev()
{
window.open("p2t.html");
}
</script>
</form>
<form method = "post" action = "." class = "device">
{% csrf_token %}
{{form.as_p}}
<br />
<input type="submit" value="Add a new network device" name="submit" alt="Add a new network device"/>
</form>
<div class="cb"></div>
</body>
</body>
</html>
deviceForm:
{ % extends "p1t.html" % }
{ %block content% }
<h1> Add a new Device </h1>
Device info: { { device_data} }
<label for="name">Name</label><input type="text" id = "name" value = ""/>
{ %endblock% }