url doesn't match with url file - django

I'm trying to deploy an app, but I'm getting Page not found (404) error for my login template/view. But the same code works on localhost.
This is the error message:
The current URL, accounts/profile/profile.html, didn't match any of these.
URLs file:
urlpatterns = patterns('',
# Examples:
url(r'^$', 'survey.views.home', name='home'),
url(r'^survey/(?P<id>\d+)/$', 'survey.views.SurveyDetail', name='survey_detail'),
url(r'^confirm/(?P<uuid>\w+)/$', 'survey.views.Confirm', name='confirmation'),
url(r'^privacy/$', 'survey.views.privacy', name='privacy_statement'),
url(r'^admin/', include(admin.site.urls)),
url(r'^piechart/$', 'survey.views.piechart', name = 'chart_code.html'),
url('^accounts/', include('registration.urls')),
url('^accounts/login/$', 'survey.views.login'),
url('^accounts/auth/$', 'survey.views.auth_view'),
**url('^accounts/profile/$', 'survey.views.profile'),**
url('^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^map/$','survey.views.javamap', name = 'chart_code.html'),
url(r'^charts', 'survey.views.charts', name='charts'),
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/auth/profile', 'survey.views.profile', name = 'profile.html'),
url(r'^profile', 'survey.views.profile', name = 'profile.html'),
url(r'^accounts/auth/results', 'survey.views.survey_name', name = 'results.html'),
url(r'^answer_survey', 'survey.views.answer_survey'),
url(r'^results/(?P<id>\d+)/$', 'survey.views.SurveyResults', name='results'),
)
The profile views:
#login_required
def profile(request):
user = request.user
if user.is_authenticated():
n_survey = Survey.objects.filter(user = user)
if n_survey:
print "*---------- str " + str(n_survey)
for survey in n_survey:
print "survey id " + str(survey.id)
n = len(n_survey)
print "n " + str(n)
return render(request, 'profile.html')
else:
print("*---------- sem surveys para print")
return HttpResponseRedirect('profile.html')
else:
msg = "Usuario ou senha digitados incorretamente"
return HttpResponseRedirect('home.html', {'msg': msg})
In localhost, the URL accounts/profile matches because django doesn't incluse profile.html at the end. How to solve this?

You are doing a redirect to a relative URL:
return HttpResponseRedirect('profile.html')
That means, if you are currently at /accounts/profile/, you will be redirected to /accounts/profile/profile.html. If you want to redirect to the view named profile.html, you can, for example, use the redirect shortcut:
from django.shortcuts import redirect
# ...
return redirect("profile.html")
Which is roughly equivalent to HttpResponseRedirect(reverse("profile.html")).
There is another problem in your url configuration: it contains some lines like this:
url(r'^charts', 'survey.views.charts', name='charts'),
There are two problems with this line
There is no slash at the end of the URL. It is better to be consistent and have a slash at the end of all URLs
There is no end-of-line special character $ at the end of the pattern. This means that many different URLs will match the pattern, for example /charts, /charts/foo, /chartsarecool and so on..
Better write
url(r'^charts/$', 'survey.views.charts', name='charts')
^^

Related

How to get current url with filter parametres?

I have an url like this :
http://127.0.0.1:8000/uk/events/?title=qwerty&age_filter=1&date_filter=2`
How to get current url with filter parametres without language code?
`/events/?title=qwerty&age_filter=1&date_filter=2`
When I am trying request.resolver_match.url_name I am getting events.
urlpatterns += i18n_patterns(
path('events/', views.events, name='events'),
)
As #NicoGriffioen suggested in the comments, you could get all arguments from the URL by using request.GET which is a dictionary-like object (django.http.QueryDict) and then rebuild the url from the url name from request.resolver_match.url_name with arguments without the language code (/uk/)
from django.shortcuts import render
def my_view(request):
all_url_args = request.GET
final_url = request.resolver_match.url_name + "?"
for name, value in all_url_args.items():
final_url += name + "=" + value
...
For more information on how to use request.GET see here.

Why M I getting a 404 in my django project?

So I have a page which I want to render after the details section in my project. My urls.py is below:
from django.conf.urls import url
from . import views
app_name = 'main'
urlpatterns = [
url(r'^home/', views.home, name='home'), # Home page
url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page
url(r'about/', views.about, name='about'), # Websie about page
url(r'results', views.result, name = 'result'), # For search function
url(r'incubators/(?P<incubator_id>[0-9]+)/', views.details, name = 'details'), # shows details of incubators
url(r'incubators/add-incuabtor/$', views.AddIncubator.as_view(), name = 'add-incubator'), # Adding Inc
url(r'/add-details/', views.AddDetails.as_view(), name = 'add-details'), #for additional details
url(r'news/', views.news, name = 'news'),
url(r'added/', views.added, name = 'added'), #your incubator will be added soon page
url(r'apply/', views.apply, name = 'apply'),
url(r'done/', views.done, name = 'done'),
url(r'location/', views.location, name = 'location'),
url(r'prediction/', views.prediction, name = 'prediction'),
url(r'^/locate/', views.locate, name = 'locate'),
]
I want to open a page (present in the details.html) which will be showing some info (in my case latitude and longitude) of that particular element.
Following is my views.py
def details(request, incubator_id):
inc = get_object_or_404(Incubators, pk = incubator_id)
details = Details.objects.get(pk = incubator_id)
return render(request, 'main/details.html', {'inc': inc, 'details': details})
def locate(request):
locate = get_object_or_404(Incubators, pk = incubator_id)
return render(request, 'main/locate.html', {'locate': locate})
But I am getting the following error:
NameError at //locate/
name 'incubator_id' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000//locate/
Django Version: 1.11.3
Exception Type: NameError
Exception Value:
name 'incubator_id' is not defined
Exception Location: C:\Users\my dell\Desktop\Project\junityme\main\views.py in locate, line 137
Python Executable: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\python.exe
Using the URLconf defined in Ekyam.urls, Django tried these URL patterns, in this order:
I think I am doing some mistake in making urls for this. Help would be appriciated.
http://127.0.0.1:8000//locate/ would be looking for a URL pattern that starts with "locate," but you don't have any URL patterns that start with locate. The URL should match the pattern, not the name you give it, or the view name.

django redirect causes a redirect to next page, but then returns to original?

My redirect function is causing some issues. I call a url from a view using reverse with the parameters required for the view. There are no errors and in the browser of the url it correctly displays these parameters. However it seems like it redirects to the new url, but immediately after requesting the new view for the new url the page returns to the original view with the new url still displayed in the browser. Can anyone tell me if I am using the redirect function correctly or maybe I am using the reverse incorrectly?
P.S. I chopped out a lot of code because StackOverflow won't let me post all of it.
home/urls.py
from django.conf.urls import url
from home import views
app_name = 'home'
urlpatterns = [
url('^$', views.index, name='index'),
url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/', views.patient_summary, name='patient_summary'),
url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/careplanid=(?P<careplan_id>\d+)/', views.care_plan, name='care_plan'),
]
home/views.py
def patient_summary(request, token, patient_id, clinic_id):
user = get_user(token)
if request.method == "POST":
if ('careplanselected' in request.POST):
props = request.POST.get('careplan')
props = props.split("#")
CPID = props[0]
cpname = props[1]
my_dict = {'token': token, 'patient_id': patient_id, 'clinic_id': clinic_id, 'careplan_id': CPID}
return redirect(reverse('home:care_plan', kwargs=my_dict))
return render(request, 'home/patient_summary.html')
def care_plan(request, token, patient_id, clinic_id, careplan_id):
user = get_user(token)
care_plan = []
cpname = ''
return render(request, 'home/care_plan.html' )
Your URL patterns are missing dollars to mark the end of the URL. That means that your patient_summary view will be handling requests meant for the care_plan view.
Change the patterns to:
url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/$', views.patient_summary, name='patient_summary'),
url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/careplanid=(?P<careplan_id>\d+)/$', views.care_plan, name='care_plan'),

How to redirect url with added url parameters

I have a workout calendar app where if a user goes to /workoutcal, I want them to be redirected to workoutcal/<today's year>/<today's month>. That means I want them to be redirected to this route, should they go to /workoutcal:
url(r'^(?P<year>[0-9]+)/(?P<month>[1-9]|1[0-2])$', views.calendar, name='calendar'),
So how can I write a new url pattern in urls.py that does something like:
url(r'^$', RedirectView().as_view(url=reverse_lazy(),todays_year, todays_month)),
You can subclass RedirectView, override get_redirect_url, and reverse the url there.
class MonthRedirectView(RedirectView):
def get_redirect_url(*args, **kwargs):
today = timezone.now()
return reverse(calendar, args=[today.year, today.month])
Then include your view in the URL pattern:
url(r'^$', MonthRedirectView().as_view()),
I found another solution to my problem, which is making a view that simply calls the calendar with the right arguments:
the url:
url(r'^$', views.redirect_to_calendar),
the redirect view:
def redirect_to_calendar(request):
today = timezone.now()
return calendar(request, year = today.year, month = today.month)
the view we serve to the user:
def calendar(request, year = None, month = None):
## A bunch of server logic
return HttpResponse(template.render(context, request))
Assuming your RedirectView is in your app's urls.py:
url(r'^(?P<year>[0-9]+)/(?P<month>[1-9]|1[0-2])$', views.calendar, name='calendar'),
url(r'^$', RedirectView().as_view(url='{}/{}'.format(todays_year, todays_month)),
EDIT: This assumes that todays_year and todays_month are calculated when a user goes to /workoutcal/, which they aren't (they're loaded at URL load time). See Alasdair's answer.

Django: redirecting URL from auto-generated "?search_bar="

So I am a new Django programmer and was wondering about how to pass a user-given value from a form into my URL address using Get method.
So I have this search bar, and when the user presses enter, it automatically creates a url address of "?search_bar=user_input"
But my urls.py, which is programmed to take the user_input variable, now fails to recognize my url address and my address is no longer matched to proceed to view.py.
urls.py
urlpatterns = [
url(r'^class/(?P<user_input>\w+)', views.newview),
]
I understand that you cannot simply do the following because you shouldn't match query string with URL Dispatcher
urlpatterns = [
url(r'^class/?search_bar=(?P<user_input>\w+)', views.newview),
]
I should I solve this issue? How can I make the url.py recognize my new address and carry the user_input over to views.py?
when we talk about url like something/?search_bar=user_input ,something/ is the url part, and the ?search_bar=user_input part belongs to the GET method,so :
urls.py
urlpatterns = [
url(r'^class/$', views.newview),
]
and in your view.py:
def newview(request):
user_input = request.GET['user_input']
# or
# user_input = request.GET.get('user_input', None)