Django view got an unexpected keyword argument - django

I have a following url pattern:
urlpatterns = pattern('',
...
url(r'edit-offer/(?P<id>\d+)/$', login_required(edit_offer), name='edit_offer'),
)
and a corresponding edit_offer view:
def edit_offer(request, id):
# do stuff here
a link on offer page leads to edit offer view:
<a class="btn" href="{% url edit_offer offer.id %}">Edit</a>
clicking on the button throws a TypeError:
edit_offer() got an unexpected keyword argument 'offer_id'
Any ideas what is going on? I don't see what's wrong here. I have other views with similar patterns and they all work ok.

Try this:
Your urls.py:-
urlpatterns = pattern('whatever_your_app.views',
...
url(r'edit-offer/(?P<id>\d+)/$', 'edit_offer', name='edit_offer'),
)
Your views.py:-
from django.contrib.auth.decorators import login_required
...
#login_required
def edit_offer(request, id):
# do stuff here
and in your template:-
{% url 'edit_offer' offer.id %}

Related

How can I print the url to the order id field of my django form?

I am doing a simple form site with Django. This is what my sites url is looks like: mysite.com/register/12345678
I want to print the part after the register (12345678) to the order id field. When someone goes this mysite.com/register/87654321 url then i want to print it.
How can i do that? These are my codes.(Currently using Django 1.11.10)
forms.py
from django import forms
from .models import Customer
from . import views
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = (
'order_id','full_name','company','email',
'phone_number','note')
widgets = {
'order_id': forms.TextInput(attrs={'class':'orderidcls'}),
'full_name': forms.TextInput(attrs={'class':'fullnamecls'}),
'company': forms.TextInput(attrs={'class':'companycls'}),
'email': forms.TextInput(attrs={'class':'emailcls'}),
'phone_number': forms.TextInput(attrs={'class':'pncls'}),
'note': forms.Textarea(attrs={'class':'notecls'}),
}
views.py
from django.shortcuts import render
from olvapp.models import Customer
from olvapp.forms import CustomerForm
from django.views.generic import CreateView,TemplateView
def guaform(request,pk):
form = CustomerForm()
if request.method == "POST":
form = CustomerForm(request.POST)
if form.is_valid():
form.save(commit=True)
else:
print('ERROR FORM INVALID')
theurl = request.get_full_path()
orderid = theurl[10:]
return render(request,'forms.py',{'form':form,'orderid':orderid})
customer_form.html
{% extends 'base.html' %}
{% block content %}
<h1>REGÄ°STRATÄ°ON</h1>
<form class="registclass" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-default">REGISTER</button>
</form>
{% endblock %}
urls.py
from django.conf.urls import url
from django.contrib import admin
from olvapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^thanks/$',views.ThankView.as_view(),name='thank'),
url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'),
]
You have passed the value to your view as 'pk' so you can use that to set the the initial value:
views.py
form = CustomerForm(initial={'order_id': pk})
SamSparx is right, here's some additional information to help prevent such errors in advance:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^thanks/$',views.ThankView.as_view(),name='thank'),
url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'),
]
You are using regex to parse your path. Regex is generally speaking not recommended in this case according to the docs because it might introduce more errors and is harder to debug. (Unoptimized) RegEx also tends to be slower.
For simple use cases such as your path here, consider choosing the default pathing syntax as below:
urlpatterns = [
url('admin/', admin.site.urls),
url('thanks/',views.ThankView.as_view(),name='thank'),
url('register/<int:pk>',views.guaform,name='custform'),
]
You could of course also use string instead of int depending on your usage of pk.
Your paths do not all end with a slash consistently. This might impact your SEO and confuse users. See this and this.
Also your form is not imported .as_view() for some reason which could cause some problems.

Type Error Django 3.0.4 : Typer Error while Runserver

I am learning Django from clever programmer and have run into an issue.
I am trying to **./manage.py runserver and I run into a type error issue as provided on the below link
i assume there seems to be a problem on the line: return render(request, 'movies/movies_stuff.html' , stuff_for_frontend)
TypeError - Screen Shot
views.py_
from django.shortcuts import render
from .models import movies
# Create your views here.
def Home_page(request):
user_query = str(request.GET.get('query' , ''))
search_result = movies.objects.filter(name__icontains=user_query)
stuff_for_frontend={'Search_result :', search_result}
return render(request, 'movies/movies_stuff.html' , stuff_for_frontend)
urls.py
from django.urls import include, path
from .views import Home_page
urlpatterns= [
path('', Home_page, name='Home _page')
]
Templates-->movies-->movies_stuff.html
<html>
<body>
<form action = "" name="search"
<input type= "text" name="query" value="{{request.GET.query}}"
<input type = "submit" value="Search" />
{%for movies in search_result%}
<p>{{movies.name}}</p>
{% endfor %}
</body>
</html>
The issue here is as it states, it's a type error. This is happening because the render method requires a dictionary and you are sending a set instead.Correct the following
stuff_for_frontend={'Search_result :', search_result} // this will become a set
to this
stuff_for_frontend={'Search_result' : search_result} // now a dictionary
The error occurs when try to access using keys on set. And in the template try to correct the form as I suspect it is incomplete.
Hope that helps! Happy coding!

How to correctly write url for #hashtag in Django

I want to insert data with modal form and show it on current page. Page already show data on table and modal form, now i need to add modal form to urls.py.
path('viewpost/#add_data_Modal', views.createpost, name='createpost'),
You could use a RedirectView for this:
from django.views.generic import RedirectView
from django.urls import reverse
class ViewpostRedirectView(RedirectView):
def get_redirect_url(*args, **kwargs):
hash_part = "add_data_Modal" # the data you want to add to the hash part
return reverse("createpost") + "#{0}".format(hash_part)
Then in your urls.py you would have something lime this:
path('viewpost/', views.createpost, name='createpost'),
path('viewpost/modal/', views.ViewpostRedirectView.as_view(), name='createpost_modal')
The viewpost/modal/ url will redirect to the viewpost/ url with the hash part appended to it.
I find another simpler way to do it, I suggest passing the hashtag as a query string to the view then reverse redirect there, so
in urls.py keep it the simple
path('', views.home, name='main-home')
in home function in views.py
#csrf_exempt
def home(request):
hashtag = request.GET.get("hashtag", "")
if hashtag:
return HttpResponseRedirect(reverse("main-home") + "#{0}".format(hashtag))
context = {}
return render(request, 'index.html', context)
and in the html u can pass any hashtag you want
<a class="nav-link" href="{% url 'main-home' %}?hashtag=team" >Team</a>
<a class="nav-link" href="{% url 'main-home' %}?hashtag=contact">Contact</a>

Is there way a to pass URL values in html files in django templates using constant substitution?

This is Django problem. I am a newbie to this.
This is my url.py file
from django.urls import path
from splunkAutomation.logic.Constants import Constants
from . import views
app_name = 'splunkAutomation'
urlpatterns = [
path(Constants.URL_FOR_SEEING_ALL_SPLUNK_QUERIES,views.viewForSeeingAllSplunkQueries, name=Constants.NAME_OF_URL_FOR_SEEING_ALL_SPLUNK_QUERIES),
]
I want to be able to reference this name "Constants.NAME_OF_URL_FOR_SEEING_ALL_SPLUNK_QUERIES" in html template.
The following is the snippet from the html file
<ul class="actions">
<li>Check</li>
</ul>
Basically I want to use the constant substitution instead of {% url 'splunkAutomation:splunkQuerySpecific' query.id %}
Is there a way to use this ?
I you add a name to the path:
path(Constants.URL_FOR_SEEING_ALL_SPLUNK_QUERIES,views.viewForSeeingAllSplunkQueries, name="url_link"),
You can use it like this:
Check
If you want to have a dynamic url, you can do this (example for class based views):
urlpatterns = patterns('',
url(
regex=r'^(?P<webaddress>\w+)/$',
view=Mysite.as_view(),
),
)
And in your view you grap the parameter:
def dispatch(self, request, *args, **kwargs):
self.webaddress= kwargs.get('webaddress', '')
In your template you can then access the value with
{{ view.webaddress }}

Django: Model parameter in the URL template tag

I want to use the url template tag for my generic view.
I have been searching a lot about this and I didn't find what I want, but it seems a simple issue.
I will use the example that the Django book, Making a View Generic, has used:
# urls.py
from django.conf.urls.defaults import *
from mysite import models, views
urlpatterns = patterns('',
(r'^events/$', views.object_list, {'model': models.Event}),
(r'^blog/entries/$', views.object_list, {'model': models.BlogEntry}),
)
# views.py
from django.shortcuts import render
def object_list(request, model):
obj_list = model.objects.all()
template_name = 'mysite/%s_list.html' % model.__name__.lower()
return render(request, template_name, {'object_list': obj_list})
So, I have one view for two URLs, my question is: How can I use the django URL template tag for this two URLs?
I want to do something like this in the html template:
href={% url "mysite.views.object_list" model="Event" %}
href={% url "mysite.views.object_list" model="BlogEntry" %}
Thanks!
You need to define name for the url:
(r'^events/$', views.object_list, {'model': models.Event}, name='my_name'),
and use it instead of the view path:
href={% url "my_name" model="Event" %}