Please see my urlpatterns given below, I get the following error when I try to run the program...
ImproperlyConfigured at /
"^product/(?p<product_slug> [-\w]+)/$" is not a valid regular expression: unexpected end of pattern
Request Method:
GET
Request URL:
http://127.0.0.1:8000/
Django Version:
1.5.1
Exception Type:
ImproperlyConfigured
Exception Value:
"^product/(?p<product_slug> [-\w]+)/$" is not a valid regular expression: unexpected end of pattern
Exception Location:
C:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\core\urlresolvers.py in regex, line 178
Python Executable:
C:\Python27\python.exe
urls.py
urlpatterns = patterns('ecomstore.catalog.views',
(r'^$','index',{'template_name':'catalog/index.html'},'catalog_home'),
(r'^category/(?P<category_slug>[-\w]+)/$','show_category',{'template_name':'catalog/category.html'},'catalog_category'),
(r'^product/(?p<product_slug> [-\w]+)/$','show_product',{'template_name':'catalog/product.html'},'catalog_product'),
)
views.py
def index(request,template_name="catalog/index.html"):
page_title = 'Music instruments and Sheet music for musicians'
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def show_category(request,category_slug,template_name="catalog/category.html"):
print 'In Catalog views|category_slug=', category_slug
c = get_object_or_404(Category,slug=category_slug)
products = c.product_set.all()
page_title = c.name
meta_keywords = c.meta_keywords
meta_description = c.meta_description
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def show_product(request,product_slug,template_name="catalog/product.html"):
p = get_object_or_404(Product, slug=product_slug)
categories = p.categories.filter(is_active=True)
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
You just need to capitalize your ?p, so:
r'^product/(?P<product_slug> [-\w]+)/$'
Related
I want to test a view of my Django application.
def search(request):
query = request.GET.get('query')
query_lower = query.lower()
list_name = re.split("[- ’? ; , ' . : ' ' " " ]",query_lower)
stripped_query = [strip_accents(x) for x in list_name]
clean_query =[word for word in stripped_query if word not in stopwords]
match_list = []
for x in Product.objects.all():
match = 0
for y in clean_query:
if y in x.name or y in x.brand:
match += 1
if match == len(clean_query):
match_list.append(x.id)
else:
pass
if not query:
products_list= Product.objects.all()
else:
products_list = Product.objects.filter(id__in=match_list)
context = {
'products': products_list,
}
return render(request, 'finder/search.html', context)
I did create some products in my tests.py with setup and I want to test if I have a 200 status code if on of those products is searched:
def test_Search(self):
self.response = self.client.post(reverse(('finder:search'), {'query':'gazpacho'}))
self.assertEqual(self.response.status_code, 200)
I got a TypeError: unhashable type: 'dict'.
So, how I am supposed to pass my query into my test for it to be run?
Your view handles GET-parameters so the request itself is a GET-request.
In your test you are sending a post, which should be a get accordingly:
self.client.get(url, {'query': '...'})
Parameters are passed as the second argument for get()/post.
See more in the docs.
In your case most likely (without having the full trace of the error) your error is the way you are calling reverse() in your test.
The second argument passed to that function is urlconf. From the docs:
The urlconf argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used.
Something like this?
class TestKlass(...):
def test_Search(self):
url = reverse('finder:search')
url_with_param = "{}?{}".format(url, 'query=gazpacho')
self.response = self.client.post(url_with_param)
self.assertEqual(self.response.status_code, 200)
I am new to Django, I have created a model and trying to post data from the front end.
following is my view.py
def studentForm(request):
userProfile = StudentProfileForm.objects.create(FirstName=request.POST['userFirstName'] LastName=request.POST['userLastName'], GreScore= request.POST['userGreScore'], IELTSTOEFL=request.POST['userIeltsToefl'],WorkEx=request.POST['userWorkEx'],ResearchDone=request.POST['userResearch'])
userProfile.save()
return render(request,'register/bg-pages.html')
Following is my model
class StudentProfileForm(models.Model):
FirstName = models.CharField(max_length=255)
LastName = models.CharField(max_length=255)
GreScore = models.IntegerField()
IELTSTOEFL = models.IntegerField()
WorkEx = models.IntegerField()
ResearchDone = models.IntegerField()
Error is following:
Request
Method: GET
Request URL: http://127.0.0.1:8000/student_form
Django Version: 2.1.5
Exception Type: MultiValueDictKeyError
Exception Value:
'userFirstName'
Exception Location: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__, line 79
Python Executable: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.1
Python Path:
['D:\\AB\\UOR_everything\\semester_2(winter_2019)\\Software_Engineering\\login_registration',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\AB\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time: Sun, 10 Mar 2019 00:35:51 +0000
If one of your POST parameters is missing, you will get an error unless you use .get() with a fallback parameter. Also, You are missing a , in your .create() method.
Example:
name = request.POST.get('name', '') # This will get the name value, or be an empty string if empty
Try this:
def studentForm(request):
if request.METHOD == 'POST': # This will protect you against GET requests
first_name = request.POST.get('userFirstName', '')
last_name = request.POST.get('userLastName', '')
gre_score = request.POST.get('userGreScore', '')
ieltstoefl = request.POST.get('userIeltsToefl', '')
work_ex = request.POST.get('userWorkEx', '')
research_done = request.POST.get('userResearch', '')
# `userProfile.save()` is unnecessary bc `.create()` already does this
userProfile = StudentProfileForm.objects.create(FirstName=first_name, LastName=last_name, GreScore=gre_score, IELTSTOEFL=ieltstoefl, WorkEx=work_ex, ResearchDone=research_done)
return render(request,'register/bg-pages.html')
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 1.4.1. I have a form which appears to have all proper values present in the html yet the POST dict appears empty.
views.py (relevant portion):
#login_required
def event(request, event_id):
event = Event.objects.get(pk=event_id)
crew = event.userprofile_set.all()
current_user = request.user.get_profile()
if current_user in crew:
current_user_is_not_crew = False
elif request.user == event.host:
current_user_is_not_crew = False
else:
current_user_is_not_crew = True
if event.date > datetime.now():
future_event = True
else:
future_event = False
context = RequestContext(request)
context['event'] = event
context['crew'] = crew
context['current_user_is_not_crew'] = current_user_is_not_crew
context['future_event'] = future_event
return render_to_response('event.html', context)
def commit(request):
"""
Commit user to event. Check if enough members
(2 including event creator) are taking part to
publish the event. If there are, mark
sufficient_participants Boolean and publish the
event to Facebook.
clashing_commitment checks that request user is not
already committed to an event on this day. If she is
they will not be allowed to commit to this.
"""
member = request.user.get_profile()
event_id = request.POST.get('event_id','')
print event_id
event = Event.objects.get(pk=event_id)
event_less_3_hours = event.date - timedelta(hours=3)
event_plus_3_hours = event.date + timedelta(hours=3)
clashing_commitment = Event.objects.filter(userprofile__exact=member).\
filter(date__range=(event_less_3_hours, event_plus_3_hours))
crew = event.userprofile_set.all()
print crew
context = RequestContext(request)
if clashing_commitment:
context['event'] = event
context['crew'] = crew
messages.add_message(request, messages.INFO,
'You are already committed to another event at this time. \
You cannot commit to two simultaneous events. Sorry! \
Ask admin to remove you from other event if necessary.')
return render_to_response('event.html', context)
try:
# cronix test page token:
graph = GraphAPI("CAAk6zW7VBJL9eUZD")
# Publish Facebook event on page
eventdate = event.date
date_iso = eventdate.isoformat()
date_iso += '+0100'
graph.post(
path = '/449/events',
retry=1,
name = event.name,
description = event.description,
location = event.location,
start_time = date_iso,
)
# To post event image, retrieve all Page events and identify current event
# by its precise date in ISO format as captured above.
# TODO This is a hacky, error-prone means of identifying
# events and needs to be fixed.
fb_events = graph.get('/449/events')
fb_events = fb_events['data']
for item in fb_events:
if item["start_time"] == date_iso:
fb_event = item
fb_event_id = fb_event.values()[0]
fb_event_path = fb_event_id + '/picture'
# Get appropriate, environment-specific root url for urllib call below.
# TODO Set two img_url variables and wrap urllib2.urlopen call
# in try/except as it is error prone
try:
if os.environ['ENV'] == 'staging':
img_url = 'http://www.mysite.org.uk//img/logo-fb.jpg'
except:
img_url = 'http://localhost:8000/static/img/logo.png'
print img_url
graph.post(
path = fb_event_path,
source = urllib2.urlopen(img_url))
except GraphAPI.OAuthError, e:
print e.message
return redirect('commit')
member.event_commitments.add(event)
crew = event.userprofile_set.all()
if crew.count() > settings.EVENT_PUB_COMMITTED_CRITICAL_MASS and event.sufficient_participants == 0:
event.sufficient_participants = 1
event.save()
publish_event = True
context['event'] = event
context['crew'] = crew
messages.add_message(request, messages.SUCCESS, 'You have committed to this event.')
return render_to_response('event.html', context)
urls.py (as requested by commenter):
from crewcal.views import user, log_in
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
from crewcal import models, views
from crewcal.forms import CustomRegistrationForm
# from crewcal.forms import RegistrationFormUniqueEmail
urlpatterns = patterns('',
# Examples:
url(r'^$', 'crewcal.views.index', name='home'),
# url(r'^ssc/', include('ssc.foo.urls')),
url(r'^events/(?P<event_id>\d+)/$', 'crewcal.views.event', name='events'),
url(r'^events/new/$', 'crewcal.views.new_event', name='new_event'),
url(r'^commit/$', 'crewcal.views.commit', name='commit'),
url(r'^users/(?P<user_name>[A-Za-z]+)/$', 'crewcal.views.user', name="user-profile"),
url(r'^users/(?P<user_name>\d+)/$', 'crewcal.views.user', name="user-profile"),
url(r'^', include('registration.backends.default.urls')),
url(r'^register/$', 'RegistrationView',
{'form_class':CustomRegistrationForm,
'backend':'registration.backends.default.DefaultBackend' }, name='registration_register'),
# For Registration simple, one-step login
# url(r'^', include('registration.backends.simple.urls')),
url(r'^facebook/', include('django_facebook.urls')),
# (r'^$', include('django_facebook.auth_urls')),
url(r'^messages/', include('postman.urls')),
# url(r'^event/$', views.object_list, {'model': models.Event}),
url(r'^accounts/', include('registration.urls')),
# url(r'^register/$', register, name='join'),
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', logout, {'next_page': '/'}, name='logout'),
url(r'^log_in/$', log_in, name='log_in'),
Here's the form rendered in the page:
<p>
<form action="/commit/" method="post" id="event-commit">
<input type="hidden" name="event_id" id="event_id" value="4">
<input type="submit" value="Commit to this event »" class="btn")">
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='XXOqtkkxYQ0zAN1sv3KYxVD8ljhjMpit' /></div>
</form>
</p>
But the consequent page breaks because the event_id (or anything else) is present in the POST dictionary:
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: ''
...
request
"<WSGIRequest\npath:/commit/,\nGET:<QueryDict: {}>,\nPOST:<QueryDict: {}>,\nCOOKIES:
...
This is happening in my Heroku staging environment but not locally. Any ideas? Thanks.
Hmm maybe this line caused the error:
event_id = request.POST.get('event_id','')
event = Event.objects.get(pk=event_id)
You need to pass int instead of string to pk, so change it to something like:
event_id = request.POST.get('event_id', 0)
event = Event.objects.get(pk=int(event_id))
EDIT:
You also have this part of code:
except GraphAPI.OAuthError, e:
print e.message
return redirect('commit')
So if there is an exception, it's automatically redirect to this same view with an empty querydict. I think that could be the source of the problem, could you remove that redirection and try again?
I am very new to Python and Django. I am trying to redirect to a second view function. Here is my url configuration:
urlpatterns = patterns('dept.pv.verif.views',
(r'^apps/dept/pv/verif/$', 'index', {}, 'index'),
(r'^apps/dept/pv/verif/display$', 'display', {}, 'display'),
(r'^apps/dept/pv/verif/display/(?P<action>\w{1})/(?P<id>\w{8})/$', 'display', {}, 'display'),
url(r'^apps/dept/pv/verif/display/(?P<action>\w{1})/(?P<id>\w{8})/$', 'display', name='display'),)
And here are my view functions:
def index(request):
context = {}
visit_switch = request.GET.get('visit_switch')
if not visit_switch:
id_form = Enter_ID()
else:
id_form = Enter_ID(request.GET)
if id_form.is_valid():
return redirect('display', action='R', id='test')
context['id_form'] = id_form
return render_to_response('index.html', {'context':context})
and the second:
def display(request, action, id):
# ...
return render_to_response('index.html')
I'm getting a NoReverseMatch error. I don't understand why the redirect line is not matching up with one of my urls. I would appreciate any help you can offer.
This regular expression group:
(?P<id>\w{8})
Will only match something 8 characters long. If you're actually passing id='test', that would be your problem.