Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RegexValidator doesn't work on CharField
I use python 3.5 and django 1.10. For my form I use crispy-forms. My form: class MyForm(forms.Form): text = forms.CharField( max_length=140, widget=forms.Textarea, validators=[ RegexValidator( r"^[A-Za-z\s]*$", message='You must use english language!', code='invalid_language'), ] ) My view: def myview: if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): text = request.POST.get('text') output = text return render(request, 'myapp/base.html', {'form': form, 'output': output}) When I post my form (with non-valid input) I get ValueError at /myview The view myapp.views.myview didn't return an HttpResponse object. It returned None instead. Why don't I get my message from validator? -
How can we receive Emails using django?
i'm fairly new to django .im trying to write a program in which i wanna receive my emails and then store them in a database i tried some packages like mailbox but no luck. i hope someone can help me out with this. Thanks in advance -
django- my form has attrubute 'password_confirm' but in view not known
in my form i added a variable named 'password_confirm'. but in view, django does not know it. in the html file, i created a form manually. my form code: class UserRegisterForm(forms.Form): name = forms.CharField(required=True,) family = forms.CharField(required=True) username = forms.CharField(required=True) email = forms.EmailField(required=True) password = forms.CharField(required=True, widget=forms.PasswordInput()) password_confirm = forms.CharField(required=True, widget=forms.PasswordInput()) type = forms.CharField(max_length=1) def clean_password(self, *args, **kwargs): pas1 = self.cleaned_data.get('password') pas2 = self.cleaned_data.get('password_confirm') if pas1 != pas2: raise forms.ValidationError("password and confirmation not matched!") return super(UserRegisterForm, self).clean() def clean_email(self): email_qs = User.objects.filter(email=self.cleaned_data['email']) if email_qs.exists(): raise forms.ValidationError("this email already exists!") this is my form element: <input type="password" name="password_confirm" id="confirm-password" tabindex="8" class="form-control" placeholder="confirm" dir="rtl"/> and this is the my view: def register_view(request): if request.user.is_authenticated: return HttpResponseRedirect('/') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data['password'] user.set_password(password) user.save() profile = Profile() profile.name = form.cleaned_data['name'] profile.family = form.cleaned_data['family'] profile.name = form.cleaned_data['email'] profile.type = form.cleaned_data['type'] profile.save() login(request, user) return HttpResponseRedirect('/') return render(request, 'accounts/signup.html', {'form': form}) this is the error: KeyError at /register/ 'password_confirm' what's the problem? -
Django forms.Form widgets and Jquery UI autocomplete
I am trying to integrate Jquery UI's Autocomplete but I am not having any luck. I have been successful in implementing datepicker so i decided to use the same approach. form.py from django import forms from asset_db.models import Profiles class SubmitJob(forms.Form): material_id = forms.CharField(max_length=8, widget=forms.TextInput(attrs={'class': 'autocomplete'})) workflow = forms.ModelChoiceField(queryset=Profiles.objects.distinct('name'), to_field_name='name') start_datepicker = forms.CharField(max_length=12, widget=forms.DateInput(attrs={'class': 'datepicker'})) end_datepicker = forms.CharField(max_length=12, widget=forms.DateInput(attrs={'class': 'datepicker'})) submit.html {% extends 'website/header.html' %} {% block content %} <p><b>Submit Job</b></p> <form action="{% url 'job' %}" method="post">{% csrf_token %} <script> $(document).ready(function() { $('.datepicker').datepicker(); }); </script> <script> $( function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", ]; $( "#material_id" ).autocomplete({ source: availableTags }); } ); </script> <p>{{ message }}</p> <b>Select Asset to transcode</b> {{form.as_p}} <p> <input type="submit" name="submit" /> </p> </form> {% endblock %} The goal is to get it working with the default values, then i will change them to data in a model. Any idea why it's not working? -
Django mocking storage on model with update() throws error
I have a small project and I'm working on some tests. Recently I asked a question: django-test-mocked-imagefield-prevent-upload-or-clean-after-test. I've made some progress in mocking the storage, but currently I'm running into an issue with mocking storage on a model with an update() in the save() method. Current situation: <..crop..> import mock current_storage = 'django.core.files.storage.default_storage._wrapped' def _mock_storage(): return mock.MagicMock(spec=Storage, name="StorageMock") class ProjectsTest(TestCase): fixtures = ['projects'] @mock.patch(current_storage, _mock_storage()) def _create_project(self, name): return Project.objects.create( name=name, short_description="Short description A", full_description="Full description A", url="http://test-project-url.com/", is_published=True) @mock.patch(current_storage, _mock_storage()) def _create_project_image(self, project, name): return ProjectImage.objects.create( project=project, name=name, description="Description", image=self._create_mock_image(name="Mocked Image"), is_primary=True, is_published=True) Creating a new object with _create_project() works fine. Creating a new object in _create_project_image() throws me an error (stacktrace on the bottom of post): ValueError: Failed to insert expression "<MagicMock name='StorageMock.save().width.resolve_expression()' id='140674024419280'>" on projects.ProjectImage.image_width. F() expressions can only be used to update, not to insert. This is because I have an update() in the save of the model (some fields are removed since they are not interesting to the question): class ProjectImage(models.Model): project = models.ForeignKey( 'projects.Project') name = models.CharField( _("Image name"), max_length=35) image = models.ImageField( _("Project image"), upload_to=project_image_upload_location, width_field='image_width', height_field='image_height') image_width = models.IntegerField( default=0) image_height = models.IntegerField( default=0) is_primary = models.BooleanField( _("Primary project image?"), default=False) def … -
Django: how allow_tags and short_description is work?
Basic way to do it in the models.py, an example: class Foo(models.Model): title = models.CharField(max_length=200) ... def custom_tag(self): return ('custom: %s' % self.title) custom_tag.allow_tags = True custom_tag.short_description = _("Custom Tag") or, if inside file of admin.py; class FooAdmin(admin.ModelAdmin): list_display = ['title', ...] ... def custom_tag(self, instance): return ('custom: %s' % instance.title) custom_tag.allow_tags = True custom_tag.short_description = _("Custom Tag") admin.site.register(Foo, FooAdmin) My question is, how actually allow_tags and short_description is work? I can't found it at the documentation or also at source code -
Django Override Custom Login Redirect Url
I want to redirect user to the main page after login. In my template, I have this, <a href="{% url 'auth_login' %}?next={% url 'main_page' %}">Login and Work</a> The problem is the user won't be redirected to the main page after login, the settings.LOGIN_REDIRECT_URL will take over and redirect the user to the url I specified in the settings file. How can I make Django make use of my ?next url set in the template instead of forcefully using settings.LOGIN_REDIRECT_URL? -
Submit Data from a HTML form to a Database in Django
What I'm trying to do is to allow a user to enter any text in a form and have the data stored in a database. However, it is not being saved when I test it. I'm sure it's probably something stupid, but any help will be appreciated. I'm also pretty new to using Django. Below is what I have currently have. Any help will be appreciated. models.py: from __future__ import unicode_literals from django.db import models class TEST(models.Model): test_name = models.CharField(max_length=100) forms.py: from django import forms class Test_Form(forms.Form): test_name = forms.CharField(max_length=100) views.py: from django.shortcuts import render from Test.forms import Test_Form from Test.models import Test from django.http import HttpResponseRedirect def index(request): return render(request, 'Test/Test.html') def Test_View(request): if request.method == 'POST': form = Test_Form(request.POST) if form.is_valid(): test_name = request.POST.get('test_name', '') return HttpResponseRedirect(reverse('Test:IOC')) else: form = Test_Form() return render(request, 'Test/Test.html', {'form': form}) Snippet from test.html <form action="/Test/" method="POST" id="Test" class="form-horizontal form-groups-bordered" role="form"> {% csrf_token %} <div class="form-group"> <div class="row"> <label class="col-lg-2 control-label" for="test_title">Full Name of Test</label> <div class="col-lg-8"> <input id="ioc_name" class="form-control" name="test_name" type="CharField" data-validate="required" placeholder="ex: This is a test"> </div> <div class="col-lg-1 col-lg-offset-9"> <a class="btn btn-success btn-icon"> Submit <input type="submit" /> <i class="entypo-check"></i> </a> </div> </form> -
django: url routing to hardcoded static and html files
I have a legacy project with a bunch of html files and static files (css, images, js, videos ...). All links in those html files are relative and hardcoded: "css/main.css" or "img/my_img.jpg" etc. I need to run that project using django. I cannot change all those links to kind of {% load static %} <link rel="stylesheet" href="{% static 'css/main.css' %}"> but all recipes I found in internet suggest using exactly that method. How can I: 1) route hardcoded urls like "css/main.css" 2) route hardcoded urls like "another.html" ? -
How to send file using ajax post request in django
I want the user to upload a file in a form which can be sent via post request using ajax .But I am getting 500: MultiValueDictKeyError at /uploaded/ "'files'" error when I try this code.THANKS in advance. view.py def uploaded(request): upl=job(jobtitle=request.POST.get('jt'),jobdes=request.POST.get('tag')) upl.save() fil=resume(job=upl,resume=request.FILES['files']) fil.save() return redirect(selected) form html <form method="post" id="upload" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="JobTitile">Job Title</label> <input type="text" class="form-control" id="JobTitle" name="jt" placeholder="Job Title" required> </div> <div class="form-group"> <label for="FileInput">Select Resumes</label> <input type="file" name="files" id="FileInput" required> </div> <div class="control-group"> <label class="control-label">Sections to look for</label> <div class=""> <input id="tags_1" type="text" class="tags form-control" name="tag" value="" required style="height:1px !important;"> <div id="suggestions-container" style="position: relative; float: left; width: 250px; margin: 10px;"></div> </div> </div><br/> <button type="submit" class="btn btn-default">Submit</button> </form> ajax ` $('#upload').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check create_post();}); function create_post() { var files = $('#FileInput').get(0).files[0]; console.log("create post is working!") console.log(files) $.ajax({ url : "/uploaded/", // the endpoint type : "POST", // http method data : { jt: $('#JobTitle').val(), file: files.name, tag: $('#tags_1').val(), 'csrfmiddlewaretoken': '{{ csrf_token }}' }, // data sent with the post request // handle a successful response success : function(json) { $('#JobTitle').val(''); // remove the value from the input $('#FileInput').val(''); $('#tags_1').html("<div class='alert alert-success alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong> Your … -
Translate string in template with dynamic value
In my template file I have something like this: {% blocktrans %}There are {{news|length}} news{% endblocktrans %} But translation always misses the {{news|length}} in it (prints out 'There are news'). My django.po file is auto generated via django-admin.py makemessages --all msgid "There are %(news|length)s news" msgstr "%(news|length)s tane haber var" I know that I can try to pass this string in views.py but is there any way to it in templates or what am I doing wrong? -
Rewrite form with django forms
I want to rewrite the vote form of the django tutorial polls application. But I can't figure out how to make a radio list for all choices of a question: {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> -
Something about Django
enter image description here enter image description here Something about Django Just as the photo show I don't know why there is has a AttributeError -
Django set permissions per model field
I have gone through the question, best way to implement privacy on each field in model django and Its answers doesn't seem solve my problem so I am asking some what related question here, well, I have a User model. I want the user to make possible to control the privacy of each and every field of their profile (may be gender, education, interests etc . ..). The privacy options must not to be limited to just private or public, but as descriptive as public friends only me friend List 1 (User.friendlist.one) friend List 2 (User.friendlist.two) friend List 3 (User.friendlist.three) another infinte lists that user may create. I also don't want these privacy options to be saved on another model, but the same so that with one query I could get the user object along with the privacy options. so If I have the UserModel, class User(models.Model): name = models.CharField() email = models.EmailField() phone = models.CharField() How do I setup a privacy setting here? I am using postgres, can I map a JSON field or Hstore even an ArrayField? what is the best solution that people used to do with Django with same problem? -
Django - A user with that name already exists
I am currently learning Django framework and im doing a little project for learning purposes. I have a model class named "Conta" and it has a foreign key to the User model (the default django User). What happens is this: Whenever i try to add a new row to the model "Conta", it throws an error saying that the user already exists, even though i am not trying to create a new user. I will post my code: SERIALIZER for the model Conta and User: class ContaDetailsSerializer (serializers.ModelSerializer): """Lists the details of a conta""" tipo_moeda = TipoMoedaSerializer() tipo_conta = TipoDeContaSerializer() user = UserSerializer() # user = UserSerializer() class Meta: model = Conta fields = ['id','user','nome','balanco','numero','tipo_moeda','tipo_conta','notas'] def create(self, validated_data): tipoConta_data = validated_data.pop('tipo_conta') tipoMoeda_data = validated_data.pop('tipo_moeda') user_data = validated_data.pop('user') print(tipoMoeda_data['id']) tipo_conta = get_object_or_404(TipoConta,pk=tipoConta_data['id']) tipo_moeda = get_object_or_404(TipoMoeda,pk=tipoMoeda_data['id']) user = get_object_or_404(User,pk=user_data['id']) conta = Conta.objects.create(**validated_data,tipo_conta=tipo_conta,tipo_moeda=tipo_moeda,user=user) return conta class UserSerializer(serializers.ModelSerializer): """Lists a user""" id = serializers.IntegerField() class Meta: model = User fields = ['id','username '] View for the creating of a new "Conta": class ContaList(APIView): def post(self,request): """Creates a Conta""" serializer = ContaDetailsSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) This is using the Django REST Framework. What am i doing wrong ? The TipoConta and … -
How to run django project again on 127.0.0.1:8000? no pg_hba.conf entry for host
I haven't ran project for long time, so there possibly happened some kind of conflict. When I am trying to run the django + postgresql localhost server by python manage.py runserver get this in response: django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "172.17.0.1", user "thekotik", database "fuck3", SSL off Normally it should run on 127.0.0.1:8000, but it seems that because of different project that ran on 127.0.0.1:5000, it's now somehow broken. So how to fix this error? How to run it again on 127.0.0.1:8000? -
How can I show model data's contents in html file?
I wrote in results.html, <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Score</title> </head> <body> <h1>Score</h1> <h2>Your score is {{ user.result }}</h2> </body> </html> But now, this part {{ user.result }} of <h2>Your score is {{ user.result }} </h2> is blank in my browser. I wrote in models.py from django.db import models from django.contrib.auth.models import User class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") result = models.CharField(max_length=64, null=True) def __str__(self): return '{} {}'.format(self.user,self.id) So,ImageAndUser model has result data. I cannot understand how to designate ImageAndUser model in results.html. Furthermore, I wrote in serializer.py from .forms import UserImageForm from rest_framework import serializers from .models import ImageAndUser class ImageSerializer(serializers.ModelSerializer): class Meta: model = ImageAndUser fields =( 'image', 'result', 'user', 'id', ) read_only_fields = ( 'user', ) def create(self, attrs): attrs['user'] = self.context.get('request').user print(attrs) return super(ImageSerializer,self).create(attrs) So,how can I fix this? -
ORM filter has no results
I have a view: def PeopleView(request): ... parameters = copy.deepcopy(request.GET) for parameter in request.GET: if not request.GET.get(parameter): del parameters[parameter] people = Person.objects.filter(**parameters) search_form = PersonSearchForm() return render(request, 'persons/people.html', { 'people': people, 'search_form': search_form, ... }) However filter always has no results. What's wrong? -
refer to ModelField property in template
There is a possibility in Django templates to refer to attributes of the field directly in a template. For example to .help_text or .label. Like that: {% for field in form %} {{field.label|safe}} {{field}} {% endfor %} What is the right way to refer to a custom defined field property? For example: {{field.myproperty}} I use ModelForm and in models.py I use my own ModelField. Everything works perfectly but any attempts to add my own property fail. In a sense that everything is ok but if I refer to this property in a template it just doesn't get it :-( Models.py: class MyFormField(forms.IntegerField): MyProperty = 'whatever' def __init__(self,active1='default',*args, **kwargs): self.MyProperty = 'whatever' super(MyFormField, self).__init__(*args, **kwargs) class MyOwnField(models.IntegerField): def __init__(self, active1='asdf',*args, **kwargs): super(MyOwnField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'form_class': MyFormField} defaults.update(kwargs) return super().formfield(**defaults) class MyModel(Model): ns6_1 = MyOwnField() -
vagrant ssh does not automatically activates the virtualenv
I am following Cadasta's (an open source organisation) Installation guide. Firstly they require you to install: VirtualBox Vagrant Ansible (version 2 or above using pip). So I installed it using sudo pip install ansible==2.1.2.0 Then, you have to clone their repository from github and enter that directory. Now, Provision the Virtual Machine (VM): vagrant up --provision and, SSH into the VM (this automatically activates the virtual machine, acoording to: Run for development. So, vagrant ssh I am following all the instructions exactly the same way, however, doing vagrant ssh doesn't activate any virtualenv. Although it makes me enter the virtual machine (ubuntu-trusty-64). After following the rest of the instructions, i.e, entering into the project directory cd vagrant/cadasta and doing ./runserver, I get the following ImportError: I am very new to Virtualbox, Vagrant and Ansible. I am totally stuck here. Maybe the problem is with the virtualenv not being activated, or Django not being installed (which is included in the requirements.txt file and which I am supposed to install only inside the virtualenv, so again I need the virtualenv to be actiavted on the very first place). In the documentation they have written: All requirements are installed in a virtual environment … -
how to add filter to a queryset in django where the values come from the URL?
views.py class ListPosts(generic.ListView): template_name = 'posts/list_posts.html' context_object_name = 'list_posts' def get_queryset(self): #kwargs={ "slug": user.slug } qs = Post.objects.all().filter(user=self.request.user) return qs here the filter is added so the the queryset only filters the posts of the logged-in user. My question is how can i show posts of the user's value coming from the slug in the URL urls.py url(r'^(?P<slug>[\w.@+-]+)/Posts/$', ListPosts.as_view(), name='user_posts'), example: username/posts i know it can be done by passing kwargs from the URL. but how can i use two different models in the same view? -
Add a conditional foreign key field in a DJANGO model
Models.py is shown below. The Release table has a foreign key system_requirements_id that points to the SystemRequirement table but I want that the user should fill the system_requirements_id only when there is no text in the system_requirements field in the Release table. Otherwise, the system_requirements_id can be left blank. How do I implement that? class SystemRequirement(TimeStampedModel): code_name = models.TextField(blank=True) content = models.TextField() creation_date = models.DateField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.code_name class Release(TimeStampedModel): system_requirements = models.TextField(blank=True) system_requirements_id = models.ForeignKey(SystemRequirement, blank=True, null=True) -
DRF oneToOneField Create Serializer
trying to do some nested model creation with drf/create serizlizer. what i'm trying to serialize is 'TradePost' model, which has post, and ProductItem in it. i already have 'ProductItemSerializer', and 'PostSerializer' by using this.. how can i serialize them?? with creation? not by telling existing record with pk value. models.py class ProductItem(models.Model): baseProduct = models.ForeignKey(Product, related_name='baseProduct') seller = models.ForeignKey(User) price = models.DecimalField(max_digits=6, decimal_places=2) isOrderClosed = models.BooleanField() isTradeCompleted = models.BooleanField() def __str__(self): return '[seller = '+self.seller.username+']' + '[product = '+(str)(self.baseProduct)+']' + '[id = '+(str)(self.id)+']' class TradePost(models.Model): basePost = models.OneToOneField(Post) baseProductItem = models.OneToOneField(ProductItem) def __str__(self): return '[post = ' + (str)(self.basePost) + ']' + '[product = ' + (str)(self.baseProductItem) + ']' + '[id = ' + (str)(self.id) + ']' in serialziers.py class ProductItemCreateSerializer(serializers.ModelSerializer): class Meta: model = ProductItem fields = ('baseProduct', 'price') #??? class TradePostCreateSerializer(serializers.ModelSerializer): class Meta: model = TradePost fields = ('basePost', 'baseProductItem',) def create(self, validated_data): post = -
Leafletjs Routing machine button collapse button not loading
I am using django 1.10.5, booststrap 4.0 and LeafletJs 1.0.3 with routing machine plugin and geocoder. Now I have the following problem, the collapse button of the control pannel for routing machine is not loading (its not showing up in the html code) when the map is bigger than 600 x 600px when the page is loaded the first time. there are no problems when I make the map bigger with chrome dev tools after the page is fully loaded with the map size set in css to 600x600px or smaller. I have a version of that works the way it should, but this is without django and bootstrap and I need it to work with both. css code .map-add-size{ position: relative; width: 500px; height:500px; } .html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block css %} <link href="{% static 'routes/css/add.css' %}" rel="stylesheet"> {{block.super}} <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"> <link href="{% static 'routes/css/leaflet-routing-machine.css' %}" rel="stylesheet" > <link href="{% static 'routes/css/Control.Geocoder.css' %}" rel="stylesheet"> {% endblock %} {% block content %} <h3>Add a new route</h3> <div class="row"> <div class="route-edit"> <div class="col-xs-6"> <p>Route page information</p> <form id="mainForm" method="post" class="form"> {% csrf_token %} {{ routeAddForm|crispy }} <div class="row route-edit"> <button … -
don't read my correct url django
I created this urls in my urls.py from django.conf.urls import url,include from django.contrib import admin from myapp import views from mysite import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), ) urlpatterns += [ url(r'^admin/', admin.site.urls), url(r'^$',views.index,name='index'), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^content/(?P<slug>[-\w]+)/$', views.custom, name='custom'), url(r'^branches/$', views.branches_fa, name='branches_view_fa'), url(r'^services/$', views.services_fa, name='services_view_fa'), url(r'^branches/(?P<slug>[-\w]+)/$', views.branch_fa, name='branch_view_fa'), url(r'^services/(?P<slug>[-\w]+)/$', views.service_fa, name='service_view_fa'), url(r'^compare/', views.compare_fa, name='compare_view_fa'), url(r'^catalog/', views.catalog_fa, name='catalog_view_fa'), url(r'^videos/page/(?P<page>\d+)/$', views.Videos_list_fa, name='video_list_view_fa'), url(r'^videos/(?P<slug>[-\w]+)/$', views.Video_content_fa, name='video_content_view_fa'), url(r'^news/page/(?P<page>\d+)/$', views.News_list_fa, name='News_list_view_fa'), url(r'^news/tag/(?P<tag>\w+)/page/(?P<page>\d+)/$', views.News_list_tag_fa, name='News_list_view_tag_fa'), url(r'^news/date/(?P<year>\d{4})-(?P<month>\d+)/page/(?P<page>\d+)/$', views.News_list_date_fa, name='News_list_view_date_fa'), url(r'^news/(?P<slug>[-\w]+)/$', views.News_detail_fa, name='News_detail_view_fa'), url(r'^product/(?P<category>[-\w]+)/page/(?P<page>\d+)/$', views.Product_list_fa, name='prudoct_list_view_fa'), url(r'^product/(?P<category>[-\w]+)/(?P<slug>[-\w]+)/$', views.Product_content_fa, name='prudoct_content_view_fa'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and work fine on my localhost but when i upload mysite on shared host i get this error Page not found (404) Request Method: GET Request URL: http://mysite/branches/%25d8%25aa%25d9%2587%25d8%25b1%25d8%25a7%25d9%2586/ Using the URLconf defined in farsauto.urls, Django tried these URL patterns, in this order: ^en/ ^admin/ ^$ [name='index'] ^ckeditor/ ^content/(?P[-\w]+)/$ [name='custom'] ^branches/$ [name='branches_view_fa'] ^services/$ [name='services_view_fa'] ^branches/(?P[-\w]+)/$ [name='branch_view_fa'] ^services/(?P[-\w]+)/$ [name='service_view_fa'] ^compare/ [name='compare_view_fa'] ^catalog/ [name='catalog_view_fa'] ^videos/page/(?P\d+)/$ [name='video_list_view_fa'] ^videos/(?P[-\w]+)/$ [name='video_content_view_fa'] ^news/page/(?P\d+)/$ [name='News_list_view_fa'] ^news/tag/(?P\w+)/page/(?P\d+)/$ [name='News_list_view_tag_fa'] ^news/date/(?P\d{4})-(?P\d+)/page/(?P\d+)/$ [name='News_list_view_date_fa'] ^news/(?P[-\w]+)/$ [name='News_detail_view_fa'] ^product/(?P[-\w]+)/page/(?P\d+)/$ [name='prudoct_list_view_fa'] ^product/(?P[-\w]+)/(?P[-\w]+)/$ [name='prudoct_content_view_fa'] ^media/(?P.)$ ^static/(?P.)$ ^static/(?P.*)$ The current URL, branches/%d8%aa%d9%87%d8%b1%d8%a7%d9%86/, didn't match any of these. You're seeing this error because …