Newbie Django Issue - python

I'm getting this error:
NoReverseMatch at /genomics/ Reverse for 'pipelinedetail' with
arguments '('02152ad7-8399-441c-ba8f-f8871460cd5f',)' and keyword
arguments '{}' not found. 0 pattern(s) tried: []
When I navigate to this URL:
http://127.0.0.1:8000/genoa/
My genoa_urls.py has:
urlpatterns = [
# ex: /polls/samples
url(r'^$', views.samples, name='samples'),
url(r'^(?P<sequence_id>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/pipelinedetail/$', views.pipelinedetail, name='pipelinedetail'),
]
The offending line in my template is:
<td>JSON</td>
And my view contains:
def pipelinedetail(request, sequence_id):
# sequence_id = '7e6bd861-934f-44be-872a-b59826107bda'
sample = get_object_or_404(Sample, pk=sequence_id)
sample_details = sample.values('pipeline_detail')
context = {'sample_details': sample_details}
return render(request, 'polls/pipelinedetail.html', context)
Here's the top level urls.py:
urlpatterns = [
# polls in the url maps to polls.urls.py
url(r'^polls/', include('polls.urls')),
url(r'^genoa/', include('polls.genoa_urls')),
url(r'^admin/', admin.site.urls),
]
What am I doing wrong?

Your polls URLs are not in a namespace, so you don't need the prefix.
{% url 'pipelinedetail' me.sequence_id %}

Both of your suggestions ultimately worked as did my original code once I created a new app and placed my new code there. Thank you.

Related

Django - method not allowed error after moving ajax request to different app

I have a small form in my django app called home that I submit through jquery ajax request. Below is the setup that I have
home urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^submitseries/$', views.submitseries, name='submitseries'),
url(r'^getstats/$', views.getstats, name='getstats'),
]
home views.py
def submitseries(request,id=None):
if request.method == "POST":
series_url = request.POST.get("series_url")
# rest of the processing code that is working fine
application urls.py
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('', include(('home.urls','home'),namespace="home")),
path('series/', include(('series.urls','series'),namespace="series")),
path('submitseries/', include(('home.urls','submitseries'),namespace="submitseries")),
path('players/', include(('players.urls','players'),namespace="players")),
path('admin/', admin.site.urls),
]
This setup is working fine but I would like to move this ajax request to a different app in my application that is with name series
So I have moved the submitseries function to views.py of series app modified the
series urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^$submitseries/', views.submitseries, name='submitseries'),
]
((tried different variations such as series/submitseries/ ))
modified the application urls.py as following
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('', include(('home.urls','home'),namespace="home")),
path('series/', include(('series.urls','series'),namespace="series")),
path('submitseries/', include(('series.urls','submitseries'),namespace="submitseries")),
path('players/', include(('players.urls','players'),namespace="players")),
path('admin/', admin.site.urls),
]
rather than pointing it to home.urls I have pointed it to series.url
But it starts giving 405 Method not allowed error and it doesn't matter what I try I am not able to solve it.
I have tried giving different variations of path in urls.py of both application and series app. I am just not able to make it work.
The only different in both the setup is that home app is base and the relative path is "http://localhost:8000/submitseries"
but when I move it to series app the base url becomes
"http://localhost:8000/series/submitseries"
Adding AJAX code as requested
//function to submit series url and save to DB
$("#save_series").click(function(e){
e.preventDefault();
series_url = $("#series_url").val();
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
console.log("Series URL " + series_url);
$.ajax({
type: "POST",
url: "series/submitseries/",
data: {"series_url":series_url},
headers:{
"X-CSRFToken": csrftoken
},
success: function(result){
message = "Series #" + result["series_id"] + " inserted successfully";
bootstrap_alert['info'](message);
},
error: function(result){
bootstrap_alert['warning'](result.responseJSON.error_msg);
}
});//end of ajax submit
});//end of button click block
I was able to fix the issue thanks to the users pointing out different things in comments.
The first clue was suggestion by #amadou sow to use url substituting in JS using following expression
{% url 'submitseries:submitseries' %}
When I did this in the action attribute of the form then I started getting following error
"Reverse for 'submitseries' with no arguments not found. 1 pattern(s)
tried: ['series/submitseries/$submitseries/']
This made it clear that there is something wrong with endpoint I have provided in the series urls.py
After playing with some permutations and combinations what I found is that $ is being evaluated literally rather than a regex symbol in case of subdirectory case and #BrianD comment about the $ being in right place hit the nail in the head.
Finally changing the series urls.py to following got the whole thing working
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^submitseries/', views.submitseries, name='submitseries'),
]
P.S. submitseries is without $ in front.

Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name

I am getting the above error when I try to access the landing page.
What am I missing?
Traceback
NoReverseMatch at /
Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.2.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name.
Here is the base.html code
<button>
` Fleet Admin
</button>
and below is the app urls.py file
from django.urls import path
from .admin import fleet_admin_site
app_name = 'trucks'
urlpatterns = [
path('fleet/', fleet_admin_site.urls, name="fleet"),
]
and the main urls.py file
from django.contrib import admin
from django.urls import path, include, reverse
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', include('workers.urls')),
path('admin/', include('trucks.urls')),
path('', TemplateView.as_view(template_name='base.html')),
]
admin.py file where I extend the AdminSite
class FleetAdminSite(admin.AdminSite):
site_header = ''
site_title = ''
index_title = ''
fleet_admin_site = FleetAdminSite(name='fleet_admin')
by seeing your code
you need to add method or class not any extension
path('fleet/', fleet_admin_site.urls, name="fleet"),
path(route, view, kwargs=None, name=None)
refer this
You are including the fleet admin with:
urlpatterns = [
path('fleet/', fleet_admin_site.urls, name="fleet"),
]
You can't do {% url 'trucks:fleet' %} to reverse fleet_admin_site.urls. You need to reverse a particular admin URL.
For example, to reverse the index, you would do:
{% 'trucks:fleet_admin:index' %}
In the above, you use trucks because you have app_name = 'trucks' in the urls.py, fleet_admin because that is the namespace in fleet_admin_site = FleetAdminSite(name='fleet_admin'), and index because that's the view you want to reverse.
Finally, the name in your path() doesn't have any effect, so I would remove it.
urlpatterns = [
path('fleet/', fleet_admin_site.urls),
]

Python / Django NoReverseMatch

I'm giving Python / Django a ago, going alright so far. I'm in the middle of setting up Django authentication, but I've hit a error;
Reverse for 'user_review_list' not found. 'user_review_list' is not a valid view function or pattern name.
Here are my views:
def user_review_list(request, username=None):
if not username:
username = request.user.username
latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date')
context = {'latest_review_list':latest_review_list, 'username':username}
return render(request, 'reviews/user_review_list.html', context)
In my base.html I call the following:
<li><a href="{% url 'reviews:user_review_list' user.username %}">Hello {{ user.username }}</li>
I've checked my other html templates and they all seem to be calling it correctly, is there anything I'm missing?
EDIT: URL's
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^reviews/', include(('reviews.urls', 'reviews'), namespace='reviews')),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^accounts/', include('django.contrib.auth.urls')),
]
Apps URL's
from django.conf.urls import url
from . import views
app_name = 'reviews'
urlpatterns = [
# ex: /
url(r'^$', views.review_list, name='review_list'),
# ex: /product/5/
url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
# ex: /product/
url(r'^product$', views.product_list, name='product_list'),
# ex: /product/5/
url(r'^product/(?P<product_id>[0-9]+)/$', views.product_detail, name='product_detail'),
url(r'^product/(?P<product_id>[0-9]+)/add_review/$', views.add_review, name='add_review'),
]
Review.objects.filter() will return a list.
For a single user, you should use Review.objects.get() method
As #Exprator pointed out I was missing user_review_list from my app URL's.

Links based off slugs giving error

I have this link with url:
See More
It is directing it to this url pattern for my app:
from django.conf.urls import url
from listings import views
app_name = 'listings'
urlpatterns = [
url(r'^$',views.UniversityListView.as_view(),name='universities'),
url(r'^/(?P<name_initials>\w+)$',views.ListingView.as_view(),name='listing_detail'),
]
Here are the project url patterns to go along with it:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.HomeView.as_view(),name='index'),
url(r'^(?P<u_slug>[-\w]+)/$',views.UniversityHomePageView.as_view(),name='university_homepage'),
url(r'^(?P<u_slug>[-\w]+)/',include('listings.urls',namespace='listings')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
However I am getting this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'listing_detail' with arguments '('stafford-apartments',)' not found. 1 pattern(s) tried: ['(?P<u_slug>[-\\w]+)//(?P<name_initials>\\w+)$']
Django: 1.11
Edit:
Here is the detail view:
class ListingView(DetailView):
model = Listing
company = Company.objects.all()
university = University.objects.all()
context = {
'listing':model,
'company':company,
'university':university,
}
As the error says, your listing_detail URL requires two arguments - u_slug and name_initials - but you are only providing one.

Django - is not a registered namespace

I am trying to process a form in django/python using the following code.
home.html:
<form action="{% url 'home:submit' %}" method='post'>
views.py:
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
})
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^submit/$', views.submit, name='submit')
]
when I try to run it in a browser I get the error:
NoReverseMatch at /home/ u'home' is not a registered namespace
and another error message indicating a problem with the form.
You should just change you action url in your template:
<form action="{% url 'submit' %} "method='post'>
On the note of url namespaces...
In order to be able to call urls using home namespace you should have in your main urls.py file line something like:
for django 1.x:
url(r'^', include('home.urls', namespace='home')),
for django 2.x and 3.x
path('', include(('home.urls', 'home'), namespace='home'))
In your main project, open url.py first. Then check, there should be app_name declared at first. If it is not, declare it.
For example, my app name is user info which is declared in url.py
app_name = "userinfo"
urlpatterns = [
url(r'home/', views.home, name='home'),
url(r'register/', views.registration, name='register')
]
I also faced the same issue.
it is fixed now by adding
app_name = "<name of your app>"
in app/urls.py
For Django 3.0, if you're handling your urls within the app and using include with path, in your project/urls.py:
urlpatterns = [
path(os.getenv('ADMIN_PATH'), admin.site.urls),
path('', include('my_simple_blog.urls', namespace='my_simple_blog')),
path('account/', include('account.urls', namespace='account')),
]
You need to specify namespace in include.
And then in your app/urls.py:
app_name = 'account'
urlpatterns = [
path('register/', registration_view, name='register'),
path('logout/', logout_view, name='logout'),
path('login/', login_view, name='login'),
]
The app_name must match the namespace you've specified in project/urls.py.
Whenever you're referring to these urls, you need to do it like this:
{% url 'namespace:name' %}
If you're using it with redirect:
return redirect('namespace:name')
For the namespace error,
Make sure you have linked the app's url in the main urls.py file
path('app_name/',include('app_name.urls'))
also in the urls.py of your app,make sure you mention the app's name as
app_name='app_name'
Also make sure you have registered the app's name on your installed apps in settings.py
As azmirfakkri has said if you're using redirect, dont use this {% url 'namespace:name' %} syntax, use return redirect('namespace:name').
Probably 2 things could be a root cause,
in app/urls.py do include as below
app_name = 'required_name'
and in project urls.py also include the app_name
url(r'^required_name/$',views.home,name='required_name'),
Check: register app in settings.py INSTALLED_APPS
tag name must be unique in the urls.py file inside your application package inside the project! it is important for the template tagging to route whats what and where.
now [1] inside the urls.py file you need to declare the variable appName and give it the unique value. for example appName = "myApp"; in your case myHomeApp and [2] also define the urlpatterns list...
urlpatterns = [..., url(r'^submit/$', views.submit, name='submit'), ...];
in the html file just change the url tag to:
<form action="{% url 'myHomeApp:submit' %}" method='post'>
this should sifuce... else just write here and we'll see how to continue on
A common mistake that I always find is when you have some name space in your template,
and in YourApp.url you don't have any name space so if you should use name space add
in YourApp.url something like this
app_name = "blog"
then on your temples make sure you add your name space,
so you will have some thing like this "assumption errors are coming from edit.html"
then on that particular template you will do this
"{% url 'blog:vote' pk=post.pk %}" "{% url 'blog:post_category' category.name %}"
if you happen to be nesting include(s, the namespace compounds, eg. topappname:appname:viewname
Maybe someone will find this suggestion helpful.
Go to your applications urls.py and type this before the urlpatterns:
app_name = 'Your app name'
I got the same error below:
NoReverseMatch at /account/register/ 'account' is not a registered
namespace
So, I set "app_name" with the application name "account" to "account/urls.py" as shown below then the error above is solved:
# "account/urls.py"
from django.urls import path
from . import views
app_name = "account" # Here
urlpatterns = [
path("register/", views.register_request, name="register")
]
Check your urls.py
urlpatterns = [
re_path(r'^submit/expense/$', views.submit_expense, name='submit_expense'),
re_path(r'^submit/income/$', views.submit_income, name='submit_income'),
re_path(r'^register/$', views.register, name='register'),
]
then open template.html
put for example register register in your HTML tag like this:
<a class="navbar-brand" href="{% url 'register' %}">
For anyone who struggled on this error like me: After reading the solutions to this question, I was setting namespace in include function in a wrong urls file. Make sure you are modifying the right urls file. For me it was putting it in the main url.py besides settings.py. I hope this answer helps anyone who was confused as I was.
This worked for me:
In urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.index),
path("test/", views.test, name = 'test')]
In views.py:
def test(request):
return render(request, "base/test.html")
In the template:
href="{% url 'test' %}"

Categories