Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to grab related post/object using django-taggit?
I'm new in django/python, so please bear with me. I want to create some sort of "Related Post" in django. How I can do that? I'm following this : How to fetch related items when using taggit in django? but dont know how to use/implement it and how to render it in template. This is my view : def trip_list(request): trip_list = Trip.objects.filter(misc_published=True).order_by('-misc_published')[:12] related = Trip.objects.filter(tags=trip_list.tags.similar_objects())[:3] return render(request, 'app_trip/trip_list.html', {'trip_list': trip_list}) Any help would be greatly appreciated! Thank you -
How to run a Django project without a manage.py file?
I'm not experienced with Django. I just want to get this project running on a localhost (on Mac). Normally I run python manage.py runserver inside a virtualenv but I can't do that without a manage.py file! I must be doing something obviously wrong if this project has 264 GitHub stars. https://github.com/shacker/django-todo How can I make this work? -
How to restore the default shcema model of django
Before to generate the models on django, I created a table with the name User, but at the moment of generate the migrations, this table wasn't replaced for the new one. Now, I have an incomplete Auth system. How I can restore the default schema model of django? -
django-tables2 exclude & field not working
I'm new to django and stumbling through creating my first site. I'm using django-tables2 to display a table and it appears to be working (the table shows up, it's sortable). Except I can't seem to customize anything. Exclude, field and sequence don't work. Can't change column verbose names. TABLE: import django_tables2 as tables from sl_overview.models import DailyslSumm class slsummTable(tables.Table): class Meta: model = DailyslSumm exclude = ('index') VIEW: class sl_summ(SingleTableView): model = DailyslSumm context_object_name = 'slsummdb' table_class = slsummTable TEMPLATE: {% load render_table from django_tables2 %} {% render_table slsummdb %} The exclude in the code above doesn't work. The column is still there. Using field doesn't adjust columns either. I'm sure I'm missing something simple, thanks for any help. -
Django Channel with Nginx Redirect
I'm using django channel for my Django application. On top of Django, I add nginx as layer for http request. All http request is working nicely, but when I tried to create a websocket connection, it was getting 302 HTTP Code. Nginx Configuration # Enable upgrading of connection (and websocket proxying) depending on the # presence of the upgrade field in the client request header map $http_upgrade $connection_upgrade { default upgrade; '' close; } # Define connection details for connecting to django running in # a docker container. upstream uwsgi { server uwsgi:8080; } server { # OTF gzip compression gzip on; gzip_min_length 860; gzip_comp_level 5; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain application/xml application/x-javascript text/xml text/css application/json; gzip_disable “MSIE [1-6].(?!.*SV1)”; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # the port your site will be served on listen 8080; # the domain name it will serve for #server_name *; charset utf-8; error_page 500 502 /500.html; location = /500.html { root /html; internal; } # max upload size, adjust to taste client_max_body_size 15M; # Django media location /media { # your Django project's media files - amend as required alias /home/web/media; expires 21d; # cache for 71 days } location /static { # … -
(urls.W005) URL namespace 'LnkIn' isn't unique.
Hi I'm getting this error when doing my migrations or using the python manage.py runserver command. (urls.W005) URL namespace 'LnkIn' isn't unique.You may not be able to reverse all URLs in this namespace. This is how I have my urls.py inside my app directory (LnkIn). from django.conf.urls import url from . import views app_name = 'LnkdIn' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<user_id>[0-9]+)/$', views.profile, name='profile'), url(r'^(?P<song_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), url(r'^trabajos/$', views.trabajos, name='trabajos'), url(r'^crear_oferta/$', views.crear_oferta, name='crear_oferta'), url(r'^(?P<user_id>[0-9]+)/create_trabajo/$', views.create_trabajo, name='create_trabajo'), url(r'^(?P<user_id>[0-9]+)/crear_amistad/$', views.crear_amistad, name='crear_amistad'), url(r'^(?P<user_id>[0-9]+)/delete_trabajo/(?P<trabajo_id>[0-9]+)/$', views.delete_trabajo, name='delete_trabajo'), url(r'^(?P<album_id>[0-9]+)/favorite_album/$', views.favorite_album, name='favorite_album'), url(r'^(?P<album_id>[0-9]+)/delete_album/$', views.delete_album, name='delete_album'), ] And this is how I have my urls.py in my main directory. from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^LnkdIn/', include('LnkdIn.urls')), url(r'^', include('LnkdIn.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I really have no idea what could I've done wrong. I checked in my views and in my templates and everything seems to be fine, I don't seem to be having any typo on my urls. I've search but haven't find this error, I've seem similars one and they suggest to check … -
Django custom model class functions- .save()
Can you define a function in a Django model that will use the .save() function. Class Restaurant(models.Model) name = models.CharField(max_length=25) rating = models.PositiveIntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)], default=50) def change_rating(self, value) self.rating += value self.rating.save() Will this work? Is this best practices? Is it better to accomplish this in views like so: *views.py def change_rating(name, amount): res = Restaurant.objects.get(name=name) res.rating += amount res.save() Thanks for the help! -
Python/Django. How to generate database schema(png, pdf) from my project?
I want to generate schema of my database to png/jpg/pdf format. I use SQLite. How I can do this? -
SQL query in Django filter by previous queries
I'm trying to find common events in python. I have manage to do the queries, but there must be a better way, could you comment please? Id date event 31 2016-10-05 1 44 2016-10-07 1 32 2016-10-05 2 36 2016-10-06 2 45 2016-10-07 2 33 2016-10-05 3 41 2016-10-07 3 34 2016-10-05 4 37 2016-10-06 4 43 2016-10-07 4 35 2016-10-05 5 38 2016-10-06 6 42 2016-10-07 6 39 2016-10-06 8 40 2016-10-06 10 This query does the Thing: select A.event as nA, B.event as nB, C.event as nC, count(C.event) as count from event as A, event as B, event as C where A.date = B.date and B.date=C.date and nA=1 and nB=2 and nC<>nA and nC<>nB group by (nC) Result: nA nB Nc count 1 2 5 1 1 2 6 1 1 2 3 2 1 2 4 2 but in python my code is as bad as: (this is an exert) b1 = event1 b2 = event2 b3 = event3 q1 = (events.objects.filter(event=b1)) for r1 in q1: #q1 contains all dates for event1 d1 = r1.dates q2 = (events.objects.filter(dates=d1).filter(event=b2)) for r2 in q2: #q2 contains all comun dates d2 = r2.dates q3 = (events.objects.filter(dates=d2).filter(event=b3)) for r3 in q3: … -
django.db.utils.IntegrityError: update or delete on table when deleting a record
I use django and postgress and have a very odd exception. I have a model object called ProductModel (with upc as a unique_id). This is how the model looks like: class ProductModel(models.Model): def __str__(self): return self.clean_name + " " + str(self.product_upc) product_name = models.CharField(max_length=300, blank=True) product_upc = models.CharField(max_length=300, primary_key=True) official_price = models.DecimalField(default=0, decimal_places=5, max_digits=10) mrsp = models.DecimalField(default=0, decimal_places=5, max_digits=10) last_seen = models.DateTimeField(default=now) clean_name = models.CharField(max_length=200, default='') unfortunately (as I understand now) at the begining of times I made a mistake and created a class called product that inherits the ProductModel - this class has some regular methods nothing fancy. class Product(ProductModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.create_clean_name() self.img_list = [] self.scraped_content = "" self.specs = {} Now, I was sure that this class has nothing to do with the db and the db doesnt aware of its existence - but now When I try to delete some product records using this command: p = ProductModel.objects.all().filter(last_seen__month__lt=4,product_name__contains='a') p.delete() I get the following error - django.db.utils.IntegrityError: update or delete on table "my_app_productmodel" violates foreign key constraint "f64b7bfb6c6019a35bf6b81e4125240f" on table "my_app_product" DETAIL: Key (product_upc)=(852896336240) is still referenced from table "my_app_product" And in this point I got totally lost and confused what the h*** … -
AttributeError: "module" has no attributes views [on hold]
I've spent countless hours on this problem. cant seem to point my finger at the issue. from django.conf.urls import url, include from . import views from django.contrib import * import django urlpatterns = [ #url(r'^login/$', views.user_login, name = "login"), url(r'^login/$', django.contrib.auth.views.login, name = 'login'), url(r'^logout/$', django.contrib.auth.views.logout, name = 'logout'), url(r'^logout-then-login/$', django.contrib.auth.views.logout_then_login, name = "logout_then_login"), url(r'^$', views.dashboard, name = "dashboard"), -
Can't get my django program to increment values that are on the server
I am very new to Django and I found a lot on other sites but nothing that really could help me. I am making a movie rating app that has a slider that controls how many stars you want to give a movie it then takes that number and adds it to the grand total of stars and then takes the number of votes and finds the average number of stars for the movie. Right now I can not get the values that are stored on the server ie total number of stars and total number of votes to update with the submit button. currently here is my template form <form action="{% url 'polls:vote' %}" method="post">{% csrf_token %} <input action="/vote/" name="myvote" related-image-id="votes{{movie.Movie_Title}}" type="range" min="1" max="5" value="0" oninput="mySlider(this)"> <input type="submit" value="Vote!"/> </form> here is my Url text from django.conf.urls import url from . import views app_name ='polls' urlpatterns = [ url(r'^', views.index, name='index'), url(r'^', views.vote, name='vote'), ] views.py def index(request): data=Movies.objects.order_by('-pub_date') for movie in data: if movie.Total_Number_of_Votes==0: movie.avg="No one has voted for this yet be the first" else: movie.avg=movie.Total_Number_of_Stars/movie.Total_Number_of_Votes return TemplateResponse(request, 'polls/index.html', {"data": data}) def vote(self, request): movie=get_object_or_404(Movies) thisVote=movie.choice_set.get(pk=request.POST['myvote']) movie.Total_Number_of_Stars=movie.Total_Number_of_Stars+ thisVote movie.Total_Number_of_Stars.save() movie.Total_Number_of_Votes += 1 movie.Total_Number_of_Votes.save() return HttpResponseRedirect(reverse(request, 'polls:index.html')) I have … -
Django, Create-react-app, Heroku
I have 3 folders in a Django web application. The folders are as follows: the folder that contains settings.py(project), the folder that contains models.py(application), and a folder that contains a front end react application created by create-react-app. I would like to build the react front end, copy the build artifacts into a static folder and then run the django application on heroku, but they have made this process practically impossible with my current folder structure. The alternative is to flatten the react application out and have build, src, node_modules, packagejson etc etc etc all at the root of the project, but this seems really bad. some config in settings.py: STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), os.path.join(BASE_DIR, 'front-end/build/static') ) what i run locally inside front-end: npm run build what i'm returning from views: def index(request): return HttpResponse(loader.get_template('build/index.html').render()) #above line returns index.html that is generated by npm run build How do I deploy the project described above to Heroku so it can find all static resources? -
SyntaxError: invalid syntax shipping method
I have a shipping repository.py file where I have my methods stated as follows- from decimal import Decimal as D from oscar.apps.shipping.methods import Free, FixedPrice, NoShippingRequired from oscar.apps.shipping.repository import Repository as CoreRepository from oscar.apps.shipping import methods, models from oscar.apps.shipping.models import WeightBased from django.utils.translation import ugettext_lazy as _ from django.contrib import messages class SelfCollection(methods.NoShippingRequired): # self pick up, customers can pick items up themselves code = "Self-Collection" name = _("Self Collection") charge_excl_tax = D('00.00') class Repository(CoreRepository): """ This class is included so that there is a choice of shipping methods. Oscar's default behaviour is to only have one which means you can't test the shipping features of PayPal. """ #methods = [Free(), FixedPrice(D('10.00'), D('10.00'))] methods = [SelfCollection()] # init shipping method to default hand delivery def get_available_shipping_methods( self, basket, user=None, shipping_addr=None, request=None, **kwargs): # check if shipping method(s) is available for shipping country (for instance 'FR') if shipping_addr : # retrieve shipping method(s) for shipping country weightbased_set = WeightBased.objects.all().filter(countries=shipping_addr.country.code) # set shipping method(s) if available for shipping country if weightbased_set : methods = (list(weightbased_set)) methods += [SelfCollection()] else : # no shipping method is available for shipping country, error message will be displayed by oscar core methods = [] # no … -
Cannot resolve keyword 'slug' into field. Choices are: emp_no, emp_no_id, from_date, id, title, to_date
I'm trying to display data from the TITLE table using detailview. But got an error message: "Cannot resolve keyword 'slug' into field. Choices are: emp_no, emp_no_id, from_date, id, title, to_date" url.py urlpatterns = [ url(r'^employee/(?P<slug>[0-9]+)/$', TitleDetail.as_view(), name='e-title'), # /employee/10001/ ] views.py class TitleDetail(DetailView): model = Title def get_context_data(self, **kwargs): context = super(TitleDetail, self).get_context_data(**kwargs) context['title_list'] = Title.objects.all() return context models.py class Title(models.Model): emp_no = models.ForeignKey(Employee, on_delete=models.CASCADE) title = models.CharField(max_length=50) from_date = models.DateField() to_date = models.DateField() # sample data in database: id title from_date to_date emp_no_id ---------- --------------- ---------- ---------- ---------- 1 Senior Engineer 1986-06-26 9999-01-01 10001 2 Staff 1996-08-03 9999-01-01 10002 title_detail.html {{ object.emp_no }} {{ object.title }} {{ object.from_date }} {{ object.to_date}} -
Issue connecting ESP8266 to Raspberry Pi Django Webserver
I'm having an issue getting my ESP8266 returning the correct information from a Django view on a local webserver (running off of a Raspberry Pi). I'm a fairly new developer - so any help would be appreciated! Here's the situation, my code, and my thought process so far: I can GET data from my app on any computer in my network using CURL and it returns the correct information. But if I try to GET data from my app through the ESP8266 it does not work. The ESP8266 DOES let me GET data from an outside website, though. So I know the ESP8266 is 1) working, 2) connected to my wifi, 3) capable of GET requests to outside websites. But for some reason it's not getting the data back from an app hosted on my local server. Here's what I have so far: views.py: @csrf_exempt def test_light(request): if request.method == "GET": print("Get Request Incoming") response_string = "Responding from the Django View" return HttpResponse(response_string) if request.method == "POST": request_dict = json.loads(request.body) print(request_dict) return HttpResponse(status=204) return HttpResponse(status=400)``` Now when I run the following CURL command from any computer on my local network: Terminal: curl “http://pi.local:8000/planner/test-light/" I get the following response on my … -
Changing the default placeholder in a Django model form for a ForeignKey
I have my code set up as follows: models.py class Category(models.Model): name = models.CharField(max_length=255) class Product(models.Model): category = models.ForeignKey(Category) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('category',) widgets = { #'category' : forms.TextInput(attrs={'placeholder' : 'Select the category'}), } Basically, right now, without the widgets part, I get -------- as the placeholder for this field. However, I want to get 'Select the category', how can I do this? Thanks! -
Custom CSS in Django Crispy forms
forms.py: from django import forms from .models import SignUp from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field class ContactForm(forms.Form): full_name = forms.CharField( required=False) email = forms.EmailField() message = forms.CharField() class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['full_name', 'email'] ### exclude = ['full_name'] helper = FormHelper() helper.layout = Layout( Field('full_name', css_class='container'), Field('email', css_class='input-sm'), ) The HTML I get shows that it using different CSS classes instead of the ones that are in the layout. Have I missed something? Am I doing something wrong? How do I add custom CSS to my form? HTML: <div id="div_id_full_name" class="form-group"> <label for="id_full_name" class="control-label "> Full name </label> <div class="controls "> <input class="textinput textInput form-control" id="id_full_name" maxlength="120" name="full_name" type="text" /> </div> </div> <div id="div_id_email" class="form-group"> <label for="id_email" class="control-label requiredField"> Email<span class="asteriskField">*</span> </label> <div class="controls "> <input class="emailinput form-control" id="id_email" maxlength="254" name="email" type="email" required /> </div> </div> -
Email in Django not working sometimes
sometimes the mail can be sent.But sometime an error if value[0] in CFWS_LEADER: IndexError: string index out of range is showing. This is my code: settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'abcd@gmail.com' EMAIL_HOST_PASSWORD = '**********' EMAIL_PORT = 587 views.py from django.core.mail import EmailMessage def accepted(request, retest_id): retest = get_object_or_404(Retest, pk=retest_id) if request.method == 'POST': retest.is_principal = True retest.save(update_fields=['is_principal']) email = EmailMessage('RMS', 'Your Notifications are Pending.', to=[request.user.email]) email.send() return render(request, 'retest/request.html' , {'retest': retest}) -
How to upload images to a public website and have it processed by a remote computer?
I have a computer that can be accessed remotely, and I would like a public user to be able to upload an image to a website and have it processed by a specific python code on the remote computer (which requires the computer's GPU resources). This is the desired flow of events: 1- User accesses the website; 2- User uploads an image to the website; 3- The website sends the image to the remote computer; 4- The remote computer runs a python code on the image and creates a new image; 5- The remote computer sends the new image to the website where it is displayed to the user. Is there an easy way to achieve this ? Thanks! -
Create collections inside migrations
i want create migrations for create collections applying one migration. I haven't clear which is the properly workflow for it, can anyone help to me? -
Optimizing Django REST framework load times without .select_related or .prefetch_related
I am experiencing slow load times (~13 seconds) for the Django REST framework due to the amount of data that is being returned (~1000 rows, 116 columns per row, no relationships). ~1000 rows $ curl -w "@curl-format.txt" -o /dev/null -s "http://127.0.0.1:8000/systemstates/3296" time_namelookup: 0.005 time_connect: 0.006 time_appconnect: 0.000 time_pretransfer: 0.006 time_redirect: 0.000 time_starttransfer: 12.968 ---------- time_total: 12.975 Limit to 10 rows $ curl -w "@curl-format.txt" -o /dev/null -s "http://127.0.0.1:8000/systemstates/3296" time_namelookup: 0.005 time_connect: 0.006 time_appconnect: 0.000 time_pretransfer: 0.006 time_redirect: 0.000 time_starttransfer: 1.657 ---------- time_total: 1.657 This is the model class SystemState(models.Model): systemId = models.IntegerField(default=0) from_date = models.DateTimeField(blank=True, null=True) to_date = models.DateTimeField(blank=True, null=True) patch = models.CharField(max_length=255, blank=True, null=True) patch_previous = models.CharField(max_length=255, blank=True, null=True) vv_count = models.IntegerField(default=0) vv_count_previous = models.IntegerField(default=0) vv_total_io = models.DecimalField(default=0, max_digits=15, decimal_places=3) port_total_io = models.DecimalField(default=0, max_digits=15, decimal_places=3) delayed_acks = models.IntegerField(default=0) delayed_acks_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_16s = models.IntegerField(default=0) writes_over_32ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_64ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_128ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_256ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_512ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_1024ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_2048ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_4096ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_and_0_62ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_62_and_0_125ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_125_and_0_25ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_25_and_0_5ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_5_and_1ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_1_and_2ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_2_and_4ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_4_and_8ms_pct = models.DecimalField(max_digits=6, decimal_places=3) … -
Django delete database record when HTML button is clicked
I'm trying to create a button located in an HTML table that when clicked will delete a record (article in this case) from the database. I pass the articles pk like I've done with other links, but I can't figure out how make the deletion happen. I've searched online and the help files, but I'm new and really need someone to lay it all out for me. What should the URL and View look? HTML: <a href="{% url 'remove_article', article_pk=articles.pk %}"><span class="glyphicon glyphicon-remove-circle"></span></a> URLS (second url): urlpatterns = [ url(r'^$', views.CompanyList.as_view(), name='company_list'), url(r'^company/(?P<pk>[0-9]+)/$', views.CompanyDetails.as_view(), name='company_details'), url(r'^company/(?P<pk>[0-9]+)/remove$', views.CompanyDetails.delete_article(), name='remove_article'), url(r'^company/transcript/(?P<transcript_id>[0-9]+)/$', views.TranscriptList.as_view(), name='transcript_details'), ] VIEW (for this page): class CompanyDetails(generic.DetailView): model = Company template_name = 'company_details.html' context_object_name = 'articles' def get_queryset(self): return Articles.objects.filter(company_id=self.kwargs.get('company_id')).order_by('-date') def get_context_data(self, **kwargs): pk = self.kwargs.get('pk') context = super(CompanyDetails, self).get_context_data(**kwargs) context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date') context['company'] = Company.objects.filter(id=pk) context['transcripts'] = Transcripts.objects.filter(company_id=pk) return context # Here is where I'm struggling... def delete_article(): article = Articles.objects.get(pk='article_pk') article.delete() -
MySQL encoding from Latin-1 to UTF-8
For a very long time i was suffering form the Latin-1 encoding in My Django web application DB causing this error when trying to select a matching string using LIKE : -- UnicodeEncodeError:'latin-1' codec can't encode character-- i've tried every solution from setting (charset='utf8') in the connection to applying cursor.execute("set names 'utf8'") before my actual query but nothing seams to work. Until i came across this blog post: https://www.whitesmith.co/blog/latin1-to-utf8/ about the encoding problem and it is the same problem that i have because when i looked in phpMyAdmin a saw that by default my DB i Latin-1 encoding: chatbot_brain=>utf8_general_ci information_schema=>utf8_general_ci Total: 2=> latin1_swedish_ci So, the solution is to dump the DB and change the description in the schema file: # Login into your future database host to create a new database with an UTF-8 charset $ mysql -h FUTURE_HOST -u FUTURE_USER -p mysql> CREATE DATABASE `FUTURE_DB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; # Flush the current database schema on the future host, replacing all CHARSET=latin1 occurrences along the way mysqldump -h CURRENT_HOST -u CURRENT_USER -p CURRENT_DB --no-data --skip-set-charset --default-character-set=latin1 \ | sed 's/CHARSET=latin1/CHARSET=utf8/g' \ | mysql -h FUTURE_HOST -u FUTURE_USER -p FUTURE_DB --default-character-set=utf8 # Flush the current database data on … -
Store boolean variable in url dispatching
The following url definition should pass whether results/ is present in the url: url(r'^(?P<question_id>[0-9]+)/(?P<results>(results/)?)shorten/$', views.shorten, name='shorten') Currently it passes results/ or None which is sufficient for a simple: if results: pass But it would be more elegant to have True and False. How could this be done?