Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Difficulty in saving data in Crispy forms usung ModelForm in djangoSaving data in django on a formn rendered by {{ form|crispy}} works fine but when I render the template using {{ form.ShowStatus|as_crispy_field}} nothing gets saved. Data is initially loaded into form with no problems, this is an update issue. Am I missing something? Django==3.0, django-crispy-forms==1.9.2, Bootstrap version 4.3.1, Python 3.8.5 Am I missing something? This works.... loads existing data into Show_form.html {% extends "fungi/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Filter</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-primary" type="submit">Create filter</button> </div> </form> </div>loads {% endblock content %} Traceback for working code [24/Mar/2021 19:57:01] "GET /testform/show/3/ HTTP/1.1" 200 5065 [24/Mar/2021 19:57:06] "GET /testform/show/3/update/ HTTP/1.1" 200 11845 [24/Mar/2021 19:57:14] "POST /testform/show/3/update/ HTTP/1.1" 302 0 [24/Mar/2021 19:57:14] "GET /testform/show/3/ HTTP/1.1" 200 5062 This doesn't work.... loads existing data but doesn't save when submit button clicked Show_form.html {% extends "fungi/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.ShowAll|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.ShowFungi|as_crispy_field}} </div> <div class="form-group col-md-4 mb-0"> {{ form.ShowHabitat|as_crispy_field}} </div> <div class="form-group col-md-4 mb-0"> {{ form.ShowStatus|as_crispy_field }} …
- 
        How to use inner join on Subquery() Dajngo ORM?I have to models class FirstModel(models.Model(): some_fields... class SecondModel(models.Model): date = models.DateTimeField() value = models.IntegerField() first_model = models.ForeignKey(to="FirstModel", on_delete=models.CASCADE) and I need query select sum(value) from second_model inner join ( select max(date) as max_date, id from second_model where date < NOW() group by id ) as subquery on date = max_date and id = subquery.id I think I can do it using Subquery Subquery(SecondModel.objects.values("first_model") .annotate(max_date=Max("date")) .filter(date__lt=Func(function="NOW"))) and F() expressions but it only can resolve model fields, not subquery Question is it possible to implement using django ORM only? also evaluate sum of values from secondModel for all values in first model by annotate this value?
- 
        How to rewrite similar functions in DjangoI have a python/django view function where it returns items from a model. I am creating a view with filters to see the data I want. Most of the time it only means changing one word in the function to get the filtered data I need. Is this best practice or should I be using some other programming construct? Here is an example of the function, in this case I have to create 3 functions/views and 3 urls to one for risk=high, risk=medium, risk=low, yada yada yada def Criticals(request): # YOU CAN NEGATE THE Q WITH THE TILDA#### items = ScanData.objects.filter(Q(Project_Assigned__icontains="Hooli") & (Q(Risk__icontains="Critical"))) numberIPs = items.count() Criticals = ScanData.objects.filter(Q(Risk="Critical") & (Q(Project_Assigned__icontains="Hooli"))) Highs = ScanData.objects.filter(Q(Risk="High") & (Q(Project_Assigned__icontains="Hooli"))) Mediums = ScanData.objects.filter(Q(Risk="Medium") & (Q(Project_Assigned__icontains="Hooli"))) Lows = ScanData.objects.filter(Q(Risk="Low") & (Q(Project_Assigned__icontains="Hooli"))) numberCriticals = Criticals.count() numberHighs = Highs.count() numberMediums = Mediums.count() numberLows = Lows.count() context = { 'items': items, 'header': 'The Hooli Project', 'numberIPs': numberIPs, 'numberCriticals': numberCriticals, 'numberHighs': numberHighs, 'numberMediums': numberMediums, 'numberLows': numberLows, } return render(request, 'index.html', context)
- 
        Flatten Django Queryset that is using select_related() and full joinmy goal is to union two querysets, however, they only match columns after the first queryset has been joined with it's foreign key table. Let me explain. Say I have three models like this: Models.py class Data(models.Model): name = models.TextField() extra_data = models.OneToOneField(Extra, on_delete=models.CASCADE) class Extra(models.Model): age = models.IntegerField() class FullData(models.Model): name = models.TextField() age = models.IntegerField() Then I am trying to do something like this: data = Data.objects.select_related() fullData = FullData.objects.all() queryset = data.union(fullData) This returns an error of: django.db.utils.OperationalError: SELECTs to the left and right of UNION do not have the same number of result columns The two issues here are: data does not get the columns if there is no related row in the Extra table The columns from select_related are only accessible by doing data.extra_data.age, meaning the left side of the union won't have the same number of columns. I want to utilize django, but it's not giving me the same results as a query like: SELECT * FROM Data LEFT JOIN Extra on Data.extra_data = Extra.id Please note I am using sqlite which is why the above query is written with a LEFT JOIN. Any thoughts on how I can get select_related() to return null …
- 
        How to counting time in djangoI have table like this: id | name | time | 1 | aaaa | 00:36:00 | 2 | aaaa | 01:00:00 | 3 | cccc | 00:10:00 | 4 | bbbb | 00:30:00 | 5 | cccc | 00:30:00 | How can I count the time grouped for each name in Django like this: name | time | aaaa | 01:36:00 | bbbb | 00:30:00 | cccc | 00:40:00 | It is possible in Django ?? Thanks for any help!
- 
        Django SQL - query returns AttributeError module '__main__' has no attribute 'df'The above error is returned when I run the code below. views.py import pandas as pd import sqldf import numpy as np from django.http import HttpResponse def test(request): # Create a dummy pd.Dataframe df = pd.DataFrame({'col_1': ['A', 'B', np.NaN, 'C', 'D'], 'col_2': ['F', np.NaN, 'G', 'H', 'I']}) # Define a SQL (SQLite3) query query = """ SELECT * FROM df WHERE col_1 IS NOT NULL; """ # Run the query print(sqldf.run(query)) return HttpResponse('Success!') urls.py from django.urls import path from .views import test urlpatterns = [ path('test/', test), ] However, the following script returns the expected response without errors: import pandas as pd import sqldf import numpy as np df = pd.DataFrame({'col_1': ['A', 'B', np.NaN, 'C', 'D'], 'col_2': ['F', np.NaN, 'G', 'H', 'I']}) query = """ SELECT * FROM df WHERE col_1 IS NOT NULL; """ # Run the query df_view = sqldf.run(query) print(df_view) How come there is an error when I execute the above script through my django website but not when I execute the script by running it on the terminal?
- 
        Difference between two values in choices tupleBelow I have a Car class, I have a tuple for choosing from a list of brands. My question is what is the difference between the two values? In ('DODGE', 'Dodge') can I just name both Dodge or does one need to be uppercase? class Car(models.Model): BRAND_CHOICES = ( ('DODGE', 'Dodge'), ('CHEVROLET', 'Chevrolet') ) title = models.CharField(max_length=255) brand = models.CharField(max_length=255, choices=BRAND_CHOICES) def __str__(self): return self.title
- 
        Python: asynchronically ssh to multiple servers and execute commands, then save result into databaseI've searched extensively on Google and stackOverflow but cannot find relevant answer. So asking here. Hope you can kindly demo how to do it. My use case is as follows: User put in ip addresses in a django form field (e.g. 12.12.12.12, 13.13.13.13, 14.14.14.14) django take ips and ssh to those machines and execute predefined script if script runs successfully, then django saves the result to database django display each server's execution results (successful, failed) I can achieve the above function using sync methods, but the wait time is unbearably long. Trying to use asyncio.run to improve it but tried and failed repetatively. :S Here is my code: in views.py def create_record(request): record_form = RecordForm() if request.method == 'POST': record_form = RecordForm(request.POST) if record_form.is_valid(): ips = record_form.cleaned_data['ip'].split(',') start_time = time.time() for ip in ips: record_form = RecordForm(request.POST) record = record_form.save(commit=False) record.ip = ip record = asyncio.run(run_script(record)) # this function ssh to server and execute commands if record is correct: record.save() messages.success(request, ip + ' execution success') else: messages.error(request, ip + ' execution failed') total = time.time() - start_time print('total:', total) return redirect('create_record') context = {'record_form': record_form} return render(request, 'record-form.html', context) in install_script.py async def run_script(record): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) …
- 
        Django: Integrityerror unique constraint failed user.idCan somebody help me? I have a problem with save my data in db.I have relate OneToOne and always get this error. I'm trying edit models if it already belongs to some user and create if it doesnt. I cant fix this error already so mutch time. I'll thanks if somebody help me. Models.py def register(request): form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): for u in User.objects.all(): instance, created = Profile.objects.get_or_create(u=user) if created: form = UserForm(request.POST, instance=instance) profile_form = ProfileForm(request.POST, instance=instance) instance.save() user = form.save() profile_form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) login(request, user) return redirect('/') else: print('не выполнилось') form = UserForm() profile_form = ProfileForm() context = { 'form':form, 'profile_form':profile_form } return render(request, 'registration.html', context) Forms.py class UserForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ['username', 'password1', 'password2', 'email', 'first_name', 'last_name'] def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.email = self.cleaned_data['last_name'] if commit: user.save() return user class ProfileForm(ModelForm): Meta: model = Profile fields = ['avatar', 'gender', 'phone_number','age', 'interests'] Views.py def register(request): form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): for u in User.objects.all(): instance, created = …
- 
        Send a dictionary through HTML form to DjangoI have a form in HTML where I have an input called "csvModified", this is initialized with an empty value and I give it the following data. <input type="hidden" name="csvModified" id="csvModified" value="" /> ... var dict_separators = {}; dict_separators["column"] = separator_columns; (String) dict_separators["thousand"] = separator_thousands; (String) dict_separators["decimal"] = separator_decimals; (String) dict_separators["children"] = final_data; (Array [Strings]) ... document.getElementById('csvModified').value = dict_separators; on Django I am recieving this as data = request.POST.get('csvModified') print(data) However the output is the following [object Object] Am I sending the data correctly from the HTML Form? Is the problem in Python? How can I get the data and iterate over it
- 
        Django - i want to view this plot into BrowserI'm new to Django for now i can pass variables but i don't know how to render dynamic plots from datetime import datetime from matplotlib import pyplot from matplotlib.animation import FuncAnimation from random import randrange x_data, y_data = [], [] figure = pyplot.figure() line, = pyplot.plot_date(x_data, y_data, '-') def update(frame): x_data.append(datetime.now()) y_data.append(randrange(0, 100)) line.set_data(x_data, y_data) figure.gca().relim() figure.gca().autoscale_view() return line, animation = FuncAnimation(figure, update, interval=200) pyplot.show()
- 
        Is using javascript to reassign parents an appropriate way to assign items into flex columns?I am trying to show a bunch of images in a website, created in django, and I want to be organised into three columns. Since the images can be of different vertical dimensions, I have decided to create 3 divs, one for each column, whose display mode is flex as I do not want to enforce them being in a grid but let the images vary in height. The code below is my solution to this and does what I want it to but, as I'm very inexperienced when it comes to django+css+etc I am wondering if there is a nicer solution to this. Here is the css for the columns and their parent div .display_wrapper { grid-column: 2 / 2; display: grid; grid-template-columns: repeat(3,minmax(100px,400px)); text-align: center; justify-content: center; grid-column-gap: 10px; } .displaycol{display: flex; flex-direction: column; height: 100%;} I add the items to the html using a django for loop, as below {% for object in object_list %} <div class="displaycol" id="col1"> </div> <div class="displaycol" id="col2"> </div> <div class="displaycol" id="col3"> </div> <div class={% cycle "incol1" "incol2" "incol3" %} > <a class="link" href="{% url 'view_object' object_title=object.title %}"> <img class="object_image" src={{ object.photo1.url }} > <h3>{{object.title}}</h3> <p>paragraph</p> </a> </div> {% empty %} {% endfor …
- 
        Using Snowpack to transpile Web Components and package dependenciesI am using Django to build a SSR website and using Django to serve static files. I also built some Web Components using lit-element and Typescript. I would like to avoid the complexity of Webpack and use Snowpack instead. Components are stored at /static/js/components. To use the components, I need to (1) transpile them to Javascript, (2) make available their dependencies (e.g. lit-element) and (3) move the transpired files as well as the _snowpack folder to Django's /static/ folder. Using just snowpack build does both but creates a build folder with a complete copy of the application. It is my understanding that buildOptions.out only moves the output folder (thereby overwriting static/ altogether if buildOptions.clean===true). I guess it would be possible to script the copying of the necessary files and delete the rest of the build folder immediately, but that strikes me as quite inelegant. Is there a configuration to only create _snowpack and the transpiled files to a specific directory?
- 
        Image does not save using Create View Base class in djangoI am trying to create my first Website and I encountered some difficulties when I am trying to create a new entry for database using Create View class base. views.py class ProductCreate(CreateView, PermissionRequiredMixin): permission_required = ("mainpages.can_create",) model = Products template_name = "product_create.html" context_object_name = "product" fields = "__all__" def form_valid(self, form): form.save() return redirect("product_view") urls.py ........ path("product-create", views.ProductCreate.as_view(), name="product_create"), ....... models.py class Products(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) resealed = models.BooleanField(blank=True, null=True) category = models.ForeignKey(to=ComputerScienceCategory, on_delete=models.CASCADE, blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name = "Product" verbose_name_plural = "Products" permissions = ( ("can_view", "Can view the product"), ("can_create", "Can create a product"), ("can_delete", "Can delete a product"), ("can_update", "Can update a product"), ) html {% extends 'index.html' %} {% block content %} <div style="margin-top:200px;"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Create"> </form> </div> {% endblock %} When I press the submit button, redirects me to the view template, but there the following error is being thrown ValueError at /product-view The 'img' attribute has no file associated with it. I checked my database and I realized that after I …
- 
        Django custom QuerySet with custom filterThe elements that are stored in Django model is as following class Transcript(models.Model): text = models.CharField(max_length=10000, default="") confidence = models.FloatField(default=0) And example data is as following : Word1(1.00-1.50) Word2(1.50-2.15) Word3(2.40-2.80) Word4(3.10-3.25) Word5(3.44-4.12) Word6(4.55-5.12) Word7(6.00-7.00) Word8(7.34-8.00) . Transcript.objects.filter(text = "Word2 Word3") Result : Word2(1.50-2.15) Word3(2.40-2.80) Transcript.objects.filter(text = "Word5 Word6 Word7 Word8") Result : Word5(3.44-4.12) Word6(4.55-5.12) Word7(6.00-7.00) Word8(7.34-8.00) Transcript.objects.filter(text = "Word3 Word5") Result : Word3(2.40-2.80) Word4(3.10-3.25) Word5(3.44-4.12) How can I make these queries using filters and possibly using regex ?
- 
        Unicode-objects must be encoded before hashing while rendering gravtar in a django templateI have installed django-simple-gravatar and added that in my installed apps in the project. And i am now trying to render the gravtar associated with user email: {% load gravatar %} {% gravatar_url user.email 40 %} This is my profile view: def Profile(request, pk): template = 'events/profile.html' user = User.objects.get(id=pk) posts = Post.objects.filter(owner=user) liked_posts = Fav.objects.filter(user=user) ctx = {'user': user, 'posts': posts, 'liked_posts': liked_posts} return render(request, template, ctx) But i get the following error Unicode-objects must be encoded before hashing I tried {% gravatar_url user.email.lower().encode("utf-8") 40 %} But then i get Could not parse the remainder: '().encode("utf-8")' from 'user.email.lower().encode("utf-8")' Please tell me what do i do to render the gravtar image
- 
        where will i get the uid and token to reset the password?My url: path("rest-auth/", include("rest_auth.urls")) When i request password reset with this endpoitn: http://127.0.0.1:8000/rest-auth/password/reset/ it sends me an email with an url which is working well to reset password but i don't need need like this way. I am using http://127.0.0.1:8000/rest-auth/password/reset/confirm/ to confirm the password reset and it expect following data { "new_password1": "", "new_password2": "", "uid": "", "token": "" } I dont receive uid and token in the mail, only i receive an url to reset password, anyone there know how can make confirm password reset?
- 
        Dynamic HTML to PDF using Python or JavascriptI am trying to add "Download PDF" link on my webapp. At the moment, I call a django function which gets a queryset and passes the context to a html file. However, I would like users to be able to download this html file as a pdf with watermark in the center. I have tried jspdf html2canvas but nothing works with. I have tried xhtmlpdf but its too slow in rendering the html. Any help would be appreciated.
- 
        Creating REST API in Django REST Framework for fetching record from one table in JSON formatI am using Django REST Framework for creating REST APIs. I am working with MySql Database where one table named questionsModel is there. In that table I am storing Course(JEE, IEEE), Subjects(Phy, Chem, Math), Topics, SubTopics, Questions etc which are already mapped with another tables like coursesModel, subjectsModel etc. I am showing my Model Class here : models.py : class questionsModel(models.Model): course_id = models.ForeignKey(coursesModel, max_length=20, null=True, on_delete=models.CASCADE) subject_id = models.ForeignKey(subjectsModel, max_length=20, null=True, on_delete=models.CASCADE) topic_id = models.ForeignKey(topicsModel, max_length=200, null=True, on_delete=models.CASCADE) subTopic_id = models.ForeignKey(subTopicsModel, max_length=20, null=True, on_delete=models.CASCADE) type_id = models.ForeignKey(questionTypesModel, max_length=20, null=True, on_delete=models.CASCADE) # Numerical or Multiple Choice Question = models.CharField(max_length=1000, blank=False, null=True) choice = (('c1','c1'), ('c2','c2'), ('c3','c3'), ('c4','c4')) answer = MultiSelectField(choices=choice) numericAnswer = models.CharField(max_length=1000, blank=False, null=True) marks = models.PositiveIntegerField(default=0) easy = models.PositiveIntegerField() average = models.PositiveIntegerField() tough = models.PositiveIntegerField() very_tough = models.PositiveIntegerField() def __str__(self): return self.Question Here, I am storing n number of Questions in this table. Now my requirement is to fetch lets say 50 random Questions depending on Complexity of the Questions like 10 easy, 20 average, 5 tough etc. I am putting my code here : serializers.py : class questionPaperSerializer(serializers.ModelSerializer): class Meta: model = questionPaperModel fields = '__all__' Can anyone please explain or provide me the code for ````Class …
- 
        Django obj.save() creating duplicate profile instead of updatingI have created a rest API that i want to be able to use to update a users profile information, however instead of updating the profile it creates a new one for that user with the updated fields. so in signaly.py when the instance user is saved it also saves the users profile with instance.profile.save() which is meant to update the profile but instead creates another profile object for the user meaning they now have 2 profiles I have tried, in the serializer, to obtain the profile created first for the user and delete it but you cannot delete an obj that doesn't have a primary key. would appreciate it if anyone could help out, thanks models.py class Profile(TimestampedModel): user = models.OneToOneField( 'User', on_delete=models.CASCADE ) TEAM_CHOICES = ( [...] ) image = models.URLField(blank=True) location = models.CharField(max_length=50, blank=True) fav_team = models.PositiveSmallIntegerField(choices=TEAM_CHOICES, blank=True, null=True) points = models.PositiveIntegerField(default=0) def __str__(self): return self.user.username serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) profile = ProfileSerializer(write_only=True) location = serializers.CharField(source='profile.location', read_only=True) image = serializers.CharField(source='profile.image', read_only=True) fav_team = serializers.CharField(source='profile.fav_team', read_only=True) points = serializers.CharField(source='profile.points', read_only=True) class Meta: model = User fields = ('email', 'username', 'password', 'token', 'profile', 'location', 'image', 'fav_team', 'points',) read_only_fields = ('token',) def update(self, instance, …
- 
        Django Admin for Multi-Table Inheritance ModelsI've got the following models for a user set up using multi-table inheritance: class MyBaseUser(AbstractBaseUser): # model fields.... class Meta: verbose_name_plural = 'Users' class SubUser(User): # model fields Now in terminal, everything seems to be working as expected, when creating a SubUser it returns a SubUser instance and creates a MyBaseUser in the db. If I query the MyBaseUser class for the id of the created SubUser it returns and I can do my_base_user_instance.subuser.<sub_user_field> - all behaving as I'd expect. How should I set up a ModelAdmin for the SubUser class though? I've got: @admin.register(SubUser) class SubUserAdmin(admin.ModelAdmin): # fields... but none of the SubUser instances are showing up, which I think makes sense given how the multi-table inheritance works, but how do I set up the admin to display/update the subclasses? I've not run into this before, thanks.
- 
        How can I consolidate multiple entries in my data dictionary into only a single entry in my Django View class?I am working on a Django site that allows a data dictionary to be generated using by analyzing an uploaded metadata set. Each metadata set contains a set of tables, and within those tables, each field and unique value associated with the field. Because some of the fields and/or values have meanings that are not always clear, a data dictionary can be generated which takes each field and/or value and allows users to enter in definition or explanation of field/value in question. It should also be noted here that there is additional information that users can add to each field in the Django site, which are: Is the field a person ID number? Should the field be ignored in the further analysis and data dictionary generation? Should the values in the fields be passed "as is" into further analysis? If the first two questions are marked as true, then the given field is excluded from the data dictionary generation and other analysis. If the last question is marked as true, then when that field is included in further analysis, its values are given without any additional transformation. However, I still want those fields to be included in the further analysis, …
- 
        Django: ModelForm get ManyToMany Field in clean Functioni have a Model called Order and it's it has manytomanyfield to ProductModel i want to get the values of selected products in clean function to make some calculations but i cannot find product field this is the modelform code class OrderForm(ModelForm): class Meta: model = Order fields = "__all__" def clean_points(self): products = self.cleaned_data["Product"] print(self.cleaned_data.get( 'product', None)) points = 20 self.set_customer_points(self.cleaned_data["customer"], points=points) return points def set_customer_points(self, customer, points=0): customer.points = customer.points + points customer.save() and this is OrderModel class Order(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True) description = models.TextField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100, ) discount = models.DecimalField(decimal_places=2, max_digits=100) order_state = models.ForeignKey( 'OrderState', on_delete=models.DO_NOTHING, null=True) points = models.IntegerField(default=0) product = models.ManyToManyField( "product.Product", ) def __str__(self): return self.customer.name class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) discount = models.DecimalField(decimal_places=2, max_digits=100) image = models.ImageField(upload_to="products",) points = models.IntegerField(default=0) def __str__(self): return self.name
- 
        How total amount on cart be added to paystack/flatterwave paymentsso I want to add the total amount on my shopping cart to the Paystack Inline and flutterwave inline module as well as the user email. How can I do this? I do not want a fixed amount like in the documentation.. Which is easier to do, in flutterwave inline or paystack inline? And how can I do it?
- 
        Error With Django URL When Passing ParameterI am setting up a new URL path but I keep getting a page not found. This is my URL that isn't working: url(r'^collections/(?P<collection_name>\d+)$', collections.home, name='collections'), This is the function in my view: def home(request, collection_name, slug=None): collection_data = Collections.objects.get(collection_name=collection_name) try: logged_id = request.GET.get('admin_id') except: logged_id = "" return render(request, 'collections.html', {'collection_data':collection_data,'logged_id':logged_id}) If I turn it into a simple URL and remove the parameter from the URL and view function as follows, it works fine so I know I'm pointing to the right view: url(r'^collections$', collections.home, name='collections'), In the same file I have another URL as follows, and it also works fine: url(r'^store/(?P<seller_id>\d+)$', store.home, name='store'), This leads me to believe that I have a simple typo or something really basic that I am overlooking. Can anyone help me spot the error here? Thank you!