Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ensure HTML elements have unique ids when repeated in a layout
I have a piece of HTML that looks like this {% for job in work_experience %} <div class="work-exp-item"> <h4 id="exp-title" class="body-text">{{ job.title }}</h4> <h5 id="exp-company" class="body-text">{{ job.company }}</h5> <p id="exp-date" class="body-text">{{ job.start_date|date:'Y' }} - {% if not job.end_date%} Present {% else %} {{ job.end_date| date:'Y' }} {% endif %} </p> <p id="exp-location" class="body-text">{{ job.city }}</p> <p id="exp-description" class="body-text">{{ job.description }}</p> </div> {% endfor %} As you can see this HTML code is inside a DTL for loop and if I have multiple work_experience objects I want to the same HTML to be laid out for different instance of the data. I have ids for the elements, but found that in the final HTML that's produced the ids are not unique. Is there a way in Django to ensure uniqueness like some sort of postfix on each id? Thanks -
Django request.method automatically set to GET and not POST
I'd like to setup an LDAP Authentication Backend in Django, and I've already used ldap3 to confirm a bind, with success. I'm now realising that writing a class for my LDAP Backend with just ldap3 is not so straightforward, and that installing django_auth_ldap could be another route to explore. I've tested already some code to create a bind to the LDAP "server", and then perform a simple search. All okay. This method I tested is outside of my Django framework. When implementing the same method into my Django framework, I encounter an issue when the method gets called. Because of the print statements, I know the view is getting called as exptected, but the part of the code whereby the first "if" statement should be executed, does not get called unless I change from "POST" to "GET". But then this seems to create the next issue (when I set to "GET", so to force the next lines to be executed), because I'd like that a login page then gets called, where I can then input my LDAP credentials, ultimately confirming the LDAP connection. Here is my code: views.py def login_ldap(request): LDAP_SERVER = '10.222.4.88' searchFilter='random' print (request) print (LDAP_SERVER) print ("request.method:{0}".format(request.method)) … -
Django Many to Many Relationship on both models
I am building a small web application where people will be able to join shows and for it to show that they joined it on a template. However, my current problem is that on my User Profile model I have added a couple of shows but the Show model object doesn't show that the User Profile is apart of it. How can I achieve this in Django? models.py: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name='user') bio = models.TextField(max_length=500, blank=True) image = models.ImageField(blank=True, upload_to="uploads/profile") show = models.ManyToManyField('Show', blank=True) def __str__(self): return str(self.user) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) class Show(models.Model): user = models.ForeignKey(User, null=True, blank=True) name = models.CharField(max_length=120, null=True, blank=True) description = models.TextField(max_length=500, null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to="uploads/show") venue = models.CharField(max_length=120, null=True, blank=True) date = models.DateField(null=True, blank=True) genre = models.CharField(max_length=120, null=True, blank=True) def __str__(self): return self.name -
Formatting the Django slacker-log-handler
I am using Django to log errors from my views.py file in my website. When using the slacker handler from: https://pypi.python.org/pypi/slacker-log-handler, the formatter variable in the slack handler does not affect the message in slack. Thanks a lot. -
Django: How to write clean method to crop photo in blog PostForm?
I want to write a clean method for a blog post form. I want the clean method to open uploaded image and create a newly cropped image and save both. My Post model is: class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200, blank=False, null=False) photo = models.ImageField(upload_to='Post', default='placeholder/placeholder.png') small_photo = models.ImageField(upload_to='Post/small') text = models.TextField(blank=False, null=False) create_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True,null=True) tags = TaggableManager() def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return revers("post_detail",kwargs={'pk':self.pk} def __str__(self): return self.title Here is my half finished admin.py: class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('author', 'title', 'photo', 'text', 'tags') If it is the correct way to do things, how would I implement the clean_photo method to save the full size photo and create a newly cropped photo to save as different name (or maybe into different field?) -
Use django to do a forum, in the user login function a little trouble
I would like to judge if the user login is successful to show the user name if not successful to show the registration login button, but the results are somewhat different, when I log on successfully return to the index page can be successfully displayed, when I click on "webgis" back to index Can not be displayed correctly index.html <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="/bbs" style="font-size: 30px;color: #0A7FFC;font-weight: bold">WebGis</a> </div> <ul class="nav navbar-nav "> <li><a href="/bbs_pub"><span class="glyphicon glyphicon-pencil"></span> 添加文章</a></li> <li><a href="login.html"><span class="glyphicon glyphicon-plus"></span> 个人中心</a></li> </ul> {% if request.user.is_authenticated %} <ul class="nav navbar-nav navbar-right"> <li><a><span class="glyphicon glyphicon-user"></span>{{ user }}</a></li> <li><a href="/login"><span class="glyphicon glyphicon-log-in"></span> 退出登陆</a></li> </ul> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="/register"><span class="glyphicon glyphicon-user"></span> REGISTER</a></li> <li><a href="/login"><span class="glyphicon glyphicon-log-in"></span> LOGIN</a></li> </ul> {% endif %} </div> urls: urlpatterns = [ url(r'^xadmin/', xadmin.site.urls), url(r'^$', index,), url(r'^bbs/', index,), url(r'^details/(\d+)/$', get_details), url(r'^bbs_pub/$', bbs_pub,name='publish'), url(r'^bbs_sub/$', bbs_sub,name='sub'), url(r'^bbs_login/$', login_view,name='bbs_login'), url(r'^login/', login_in,name='login'), ] views: def login_view(request): user_name = request.POST.get('username') pass_word = request.POST.get('password') user = authenticate(username=user_name, password=pass_word) if user is not None: login(request, user) bbs_list = models.BBS.objects.all() return render(request, "index.html",{'bbs_list':bbs_list},) else: return render(request, "login.html", {"msg": "用户名或密码错误!"},) login.html <form action="/bbs_login/" method="post" class="login" id="formlogin"> {% csrf_token %} <input type='hidden' name='csrfmiddlewaretoken' value='mymQDzHWl2REXIfPMg2mJaLqDfaS1sD5' /> <h1> 请您直接登录 </h1> <label> <span>邮箱 :</span> … -
executing raw sql in django error: relation does not exist
I am attempting to execute a raw sql query and I am getting the following error: relation "venue" does not exist the query is as follows: cityList = Venue.objects.raw("SELECT DISTINCT city FROM Venue") the model I am grabbing from looks like this: class Venue(models.Model): name = models.CharField(max_length=150, blank=False) description = models.CharField(max_length=1000) image = models.ImageField(upload_to=imgUnique('venueMedia/venueImages')) streetAddress= models.CharField(max_length=100) city = models.CharField(max_length=100, blank=False) state = models.CharField(max_length=100, blank=False) This is a syntax error, and I am having a hard time finding the right documentation regarding the proper syntax. There seems to be alot on curser queries but I am not ready to give up on this yet -
Django rest framework add model method to serializer twice
I understand that it is possible to add a models method or property to a serializer, like this: class Order(models.Model): ... def tax_status(self, check_item_bought=True): ... So, to add total_tax to an OrderSerializer, it is as simple as this: class OrderSerializer(serializers.ModelSerializer): tax_status = serializers.CharField(required=False) class Meta: model = Order fields = ["tax_status", ...] The above works well. However, I need to add another tax_status_all field to the serializer that points to the same method but setting the arg check_item_boughtto False. How can I do this? Any advice will help. -
Django Test Client client.post() sends GET request?
I am new to Python and Django. I did a experiment on enforcing request method (e.g. for certain url you can only use GET). Here is my code. tests.py from django.test import TestCase, Client client = Client() class MyTests(TestCase): def test_request_method: """ Sending wrong request methods should result in 405 error """ self.assertEqual(client.post('/mytest', follow = True).status_code, 405) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^mytest/', views.mytest, name = 'mytest'), ] views.py from django.http import HttpResponse def mytest(request): if request.method == 'GET': return HttpResponse("Not implemented", status = 500) else: return HttpResponse("Only GET method allowed", status = 405) But the test always returns status 500. I saw here that this may be related to using follow=True in the client.post() call. However if I use follow=False I will get status 301 instead. Any ideas? Thank you! -
Python programmatically define variables in class body
I have two django models, model Person and model PersonTemplate that have the exact same field names & types, with the exception being that some of the fields are required in Person, whereas they are not in PersonTemplate. It's easy enough to just copy paste the models into both of these classes, but that involves a lot of hard-coding and if I edit one model and forget the other, stuff might break. The solution I have in mind is to define the django model fields in a function that takes a boolean argument, whether or not the fields are required. Something like def get_fields(is_required=True): first_name = models.CharField(max_length=128, verbose_name=_("First Name"), blank=is_required, null=is_required) last_name = models.CharField(max_length=128, verbose_name=_("Last Name"), blank=is_required, null=is_required) return locals() class Person(models.Model): vars = get_fields(True) class PersonTemplate(models.Model): vars = get_fields(False) What I don't know how to do is get the local variables from get_fields into the class body of the models. Anybody have any ideas, or suggestions for a better way to implement these models? -
Retrieve ImageField on Many-To-Many relationship
I have two apps related with a Many-To-Many relationship, Recipes and Tags, and I'm having trouble at retrieving a query of Tags having image != null and the Recipes that are currently PUBLISHED. Recipe app: recipes/models.py from django.db import models from django.contrib.auth.models import User from tags.models import Tag DRAFT = 'D' PUBLISHED = 'P' RECIPE_STATES = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) class Recipe(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, unique=True) date_created = models.DateField(auto_now_add=True) date_modified = models.DateField(auto_now=True) state = models.CharField(max_length=1, choices=RECIPE_STATES) ingredients = models.TextField(blank=True) introduction = models.TextField(blank=True) preparation = models.TextField(blank=True) tip = models.TextField(blank=True) rating = models.IntegerField(blank=True) diners = models.IntegerField(blank=True) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title And the Tag app: tags/models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=50, unique=True) image = models.ImageField(blank=True, null=True, upload_to='categories') def __str__(self): return self.name recipes/views.py: class HomeView(View): def get(self, request): queryset = Recipe.objects.filter(state=PUBLISHED) last_recipes = queryset.order_by('-date_created') top_recipes = queryset.order_by('-rating') categories = Tag.objects.exclude(image__isnull=True, recipe__state=PUBLISHED) context = { 'last_recipes': last_recipes[:4], 'top_recipes': top_recipes[:4], 'categories': categories } return render(request, 'recipes/home.html', context) When I try to retrieve that query from the views.py in home.html: <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> {% for category in categories %} <a href="{% url 'category_recipes' category.name %}"> <div class="col-xs-6 col-sm-4 col-md-3 text-center"> … -
Raspberry Django: django.db.utils.OperationalError: attempt to write a readonly database
I'm running a Django app in my raspberry, But when I try to login in the admin page I get this error below. I don't know why this is going on and what this error is. There are other topics like this, But none helped me, and I guess it's because I'm running my app in a raspberry. Internal Server Error: /admin/login/ Traceback (most recent call last): File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: attempt to write a readonly database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/channels/handler.py", line 243, in process_exception_by_middleware return super(AsgiHandler, self).process_exception_by_middleware(exception, request) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 377, in login return login(request, **defaults) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/contrib/auth/views.py", line 47, in inner return func(*args, **kwargs) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/pi/Dev/djcity/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File … -
Django annotation through multiple has-many relationships with filtering
I need to annotate across multiple has-many relationships. The SQL query that would accomplish what I need is the following: SELECT dm.id, count(trt.id) AS passed, count(trf.id) AS failed, count(trn.id) AS not_calculated FROM device_models AS dm LEFT JOIN devices AS d ON d.model_id = dm.id LEFT JOIN test_runs AS tr ON tr.dut_id = d.id LEFT JOIN tests AS t ON t.test_run_id = tr.id LEFT JOIN (SELECT id, test_id FROM test_results WHERE passed_all IS TRUE) AS trt ON trt.test_id = t.id LEFT JOIN (SELECT id, test_id FROM test_results WHERE passed_all IS FALSE) AS trf ON trf.test_id = t.id LEFT JOIN (SELECT id, test_id FROM test_results WHERE passed_all IS NULL) AS trn ON trn.test_id = t.id GROUP BY dm.id One device model has many devices One device has many test runs One test run has many tests One test has many results I am able to accomplish this by looping through device models and querying for TestResult.objects.filter(test__test_run__device__model=device_model), but is there a way to accomplish this through the ORM with a single query? The best I can come up with is DeviceModel.objects.annotate(num_passes=Count(Case(When(device__test_run__test__result__passed_all=True)))), but I'm getting an error: django.core.exceptions.FieldError: Related Field got invalid lookup: test_run -
Logout system in django
I want to logout with defualt system I visit : https://docs.djangoproject.com/en/1.11/topics/auth/default/ Can you show me a project or a code for logout in defualt system? Code or project in github or stackoverflow **note : **i want to know : what it return ? What i need? It will destroye session? It will unset session? Or waht? All answers will help me 💛💛💛💛 -
Compiling a django project to exe with Python 3.6 for Windows users
I have a django project I am working on (64-bit Ubunu with Python 3.6) and I need to compile it into an exe that Windows (32- and 64-bit) users can run and via localhost through their browser. For my project I need to import common packages such as numpy, pandas, matplotlib. Is this possible? From what I've found so far, is that each of the tools I've come across does not work for one reason or another: bbFreeze: doesn't support Python 3 py2exe: doesn't support importing packages (although heard it is very good for wrapping everything up into a single exe file PyInstaller: Looked promising but only works up to Python 3.5 (unfortunate as I also found this for Django -> exe) -
How do I find the end date from a start date and an interval in Django?
This is related to the question I asked here: My form in Python Django is not submitting Here is the relevant code #choices.py INTERVAL_CHOICES = (('one_day', '1 Day'), ('two_days', '2 Days'), ('three_days', '3 Days'), ('four_days', '4 Days'), ('five_days', '5 Days'), ('six_days', '6 Days'), ('one-week', '1 Week'), ('two_weeks', '2 Weeks'), ('three_weeks', '3 Weeks'), ('four_weeks', '4 Weeks'), ('five_weeks', '5 Weeks'), ('six_weeks', '6 Weeks'), ('eight_weeks', '8 Weeks'), ('twelve_weeks', '12 Weeks') ) #models.py class Schedules(models.Model): start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today) interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='one_day') #views.py def schedule_List(request): schedule_list = Schedules.objects.all() context_dict = {'schedules': schedule_list} return render(request, "schedule/schedule_list.html", context_dict) I need to find an end date from the start date and the interval and then be able to put that end date into the template. I assume I need to somehow convert the second part of the tuple in the interval choices into an integer and then multiply any choices that have 'week' or 'weeks' in them by 7, and then add that to the start date somehow. Does anyone have an idea on this, as well as how to post the end date into the template? Thanks. -
Django CustomUser redefine password field
Suddenly I had the need to use one of my existing models for authentication. I know that there are several approaches how I can do that, but here I'm wondering is it possible to redefine password field with a way I choosed? To be more specific: I want django to know that my access_key field is a User password field. But current code presupposes that I gonna add another field password to Company model. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.db import models from django_extensions.db.fields.encrypted import EncryptedCharField class CompanyManager(BaseUserManager): def create_user(self, name, email, access_key=None): if not email: raise ValueError('Company must have an email address') company = self.model( email=CompanyManager.normalize_email(email), ) if access_key is not None: company.access_key = access_key company.save(using=self._db) return company def create_superuser(self, name, email, access_key): company = self.create_user(name, email, access_key) company.is_admin = True company.save() return company class Company(AbstractBaseUser): name = models.CharField(max_length=64, blank=False, null=False, unique=True) email = models.CharField(max_length=254, blank=False, null=False, unique=True) access_key = EncryptedCharField(max_length=18) verification_key = EncryptedCharField(max_length=20, blank=True, null=True) is_confirmed = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) callback_url = models.URLField(blank=False, null=True) objects = CompanyManager() USERNAME_FIELD = 'name' REQUIRED_FIELDS = ['email'] -
Django message error
The following error is being thrown by my Django code on my VPS when I try to use messages: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware Exception Type: MessageFailure Exception Value: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware I do have all the appropriate settings in my settings.py file. My VPS is running Django 1.9.6. The same error is not thrown when I run the code locally on my laptop. On my laptop, I have Django 1.10.3 running. Are there any differences in the treatment of messages between Django 1.9.6 and 1.10.3 that would cause this to happen? It seems that on Django 1.9.6 my settings in settings.py are being ignored. Any help would be greatly appreciated. Thanks. -
Django REST framework: how to create an object and related images
I have these two Django models, a Product and ProductImage. A Product may have multiple ProductImages. class Product(models.Model): product_name = models.CharField() class ProductImage(models.Model): img = models.ImageField() product = models.ForeignKey(Product) I would like to create an API endpoint that would create a Product and its ProductImages from a POST request. How should the serializer and view look like? -
Using the django authentication system
I want to login with handler. I have a code use session but i want to use handler: I have visit : https://docs.djangoproject.com/en/1.11/topics/auth/default/ But i don't understand complete. I want to log user (with username or email and password) Do you have a code for example or project in stackoverflow or github or . . . ??? -
In Django, how to use a list from html checkboxes to loop through elements, and go to element specific page
I want to obtain a list from a HTML form with specific IDs in it: search.html: <form method='POST' action='/report/'> {% for o in obj %} <tbody> <tr> <td>{{o.sample}}</td> <td><input type="checkbox" name="Samples" value="{{o.sample}}</td> </tr> </tbody> {% endfor %} <input type="submit" value="Submit"> </form> This gives me a list of samples to my report view which takes me to /report/ in my URLs i have defined a regex so that it would be able to take me to a sample specific report URL: url(r'^report/Sam\d{1,5}_\d{2}/$', views.report), What I want is to be able to loop through this list sample IDs, so when I click the initial submit, it takes me to the first sample ID at: localhost:8000/report/H1_1/ then I process and make a report for this sample, I submit and it takes me to the next sample ID in my list: localhost:8000/report/H2_1/ etc. I have been racking my brain on how to do this and the only thing I came up with was: search.html: {% for o in obj %} <form method='POST' action='/report/{{o.sample}}'> <tbody> <tr> <td>{{o.sample}}</td> <td><input type="checkbox" name="Samples" value="{{o.sample}}</td> </tr> </tbody> {% endfor %} <input type="submit" value="Submit"> </form> but I cant work how to get to the next sample in the sample specific … -
Django with Bootstrap 2nd Modal (or subsequent modals) not working
Using the Django for loop It am generating a paginated list from the database. This works. The generated list has a delete button to the right of each entry. At the same page load I an using the the django for loop to generate individual Modal windows that match each delete button. So the button will call modal ID=### and there is a modal ### that matches. The HTML appears to render perfectly. When I delete the TOP(First entry on the page) it works like a charm, I can do that all day long, with entries moving up and being deleted. THE PROBLEM: When I choose a 2nd position or lower button the screen goes grey and freezes it needs a reload to respond again. This pattern is repeatable. HTML: {% load static %} {% block content %} <link rel="stylesheet" href="{% static "css/cabinet_table.css"%}"> <div class="col-lg-2"> </div> <div class="col-lg-8"> <div class="table-responsive"> <table class="table table-hover"> <th colspan="3"style="text-align: center;"><h2>{{ user.username|capfirst }} Notes</h2></th> {% for note in note_list %} <tr> <td ><a href="{% url "cabinet:note_edit" note.id %}">{{ note.title }}</a></td> <td>{{ note.text|truncatewords:15 }}</td> <td><button type="button" class="btn btn-info btn-success" data-toggle="modal" data-target="#deleteModal{{ note.id }}">Delete</button></td> </tr> {% endfor %} </table> </div> <!-- Pagination below --> {% if note_list.has_other_pages … -
Redirecting Angular routes to Django
Question: What is best way to serve routes when you need to serve some URLs from Angular, and some from Django Templates Details: We are planning to move from Django Templates to Angular. We are planning to migrate feature by feature rather than at one go. Initially, the plan is: Hit Angular routes Angular check whether it is part of Angular route Else, it passes the URL to Django which returns the result. Here, 3rd point seems tricky to me and may result in recursion, since any redirect I write may simply start from step 1. Other plans which we consider: Route all URLs through the proxy server, which matches routes and then decides whether to redirect to Django and Angular. I am not very keen on it since we need to duplicate (and then maintain) either Angular or Django URLs. We would need to remember and update the URL scheme at two places Change URL scheme to differentiate between Angular and Django apps, for example: www.example.com/angular/ vs www.example.com/rest-of-url. Then use Gateway API which serves the page on basis of URL. The reason we don't like it is that it breaks existing URLs. Customers who are using www.example.com/home now may … -
Day difference in Django annotation
I want to do something equivalent to the following: MyModel.objects.all().annotate( days_since_start = ExpressionWrapper( (F(date) - start_date).days, output_field=IntegerField() ) ) Of course, this won't work, as F(date) - start_date ends up as SQL, and .days does not work as it requires a timedelta object. Is this annotation possible some other way? I'd rather not pull all the data out of the database and calculate this value row by row. -
not able to add product in admin site?
Using the URLconf defined in myshop.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^admin/ ^login/$ [name='login'] ^admin/ ^logout/$ [name='logout'] ^admin/ ^password_change/$ [name='password_change'] ^admin/ ^password_change/done/$ [name='password_change_done'] ^admin/ ^jsi18n/$ [name='jsi18n'] ^admin/ ^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$ [name='view_on_site'] ^admin/ ^auth/group/ ^admin/ ^auth/user/ ^admin/ ^sites/site/ ^admin/ ^(?P<app_label>auth|sites)/$ [name='app_list'] The current path, admin/myshop/Product/add/, didn't match any of these. i am basically a beginner to django and creating my django shop app. i get this error by typing the url http://127.0.0.1:8000/admin/myshop/Product/add/ My admin.py looks like this from django.contrib import admin from .models import Category, Product class CategoryAdmin(admin.ModelAdmin): list_display=['name','slug'] prepopulated_fields={'slug':('name',)} admin.site.register(Category, CategoryAdmin) class ProductAdmin(admin.modelAdmin): list_display=['name','slug','category','price','stock','avialable','created','updated'] list_filter=['available','created','updated','category'] list_editable=['price','stock','available'] prepopulated_fields=['slug':('name',)} admin.site.register(Product, ProductAdmin) This is my models.py file from django.db import models # Create your models here. from django.core.urlresolvers import reverse class Category(models.Model): name = models.Charfield(max_length=200, db_index=True) slug = models.Slugfield(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def__str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) Class product(models.Model): category=models.ForeignKey(Category, related_name='products') name=models.CharField(max_length=200, db_index=True) slug=models.SlugField(max_length=200, db_index=True) image=models.ImageField(upload_to'product/%Y/%m/%d',blank=True) description=models.TextField(blank=True) price=models.DecimalField(max_digits=10, decimal_places=2) stock=models.PositiveIntegerField() available=models.BooleanField(default=True) created=models.Datetimefield(auto_now_add=True) updated=models.DatetimeField(auto_now=True) Class Meta: ordering=('-created',) index_togetther=(('id','slug'),) def__str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id,self.slug) I tried to check everything but everything looks ok to me