Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding time limits in celery base task class
I've a class like below. from celery import Task from mycroft.core.alerts import slack_error class MycroftTask(Task): abstract = True def on_failure(self, exc, task_id, args, kwargs, einfo): #dosomething Now I'm extending this class to every other classes. Now I want to add a hard time limit and soft time limit. I've tried below way will this work. from celery import Task from mycroft.core.alerts import slack_error class MycroftTask(Task): abstract = True def __init__(self): self.time_limit = settings.CELERY_TIME_LIMIT self.soft_time_limit = settings.CELERY_SOFT_TIME_LIMIT def on_failure(self, exc, task_id, args, kwargs, einfo): -
'NoReverseMatch at' django mistake
Mistake appeared when I added url to another app. I added <a class="navbar-brand" href="{% url 'posts:listofposts' %}">Home</a> My root.urls: urlpatterns = [ url(r'^', include('posts.urls', namespace= 'posts')) ] posts.urls: urlpatterns = [ url(r'^create/', create_post , name='create_post'), url(r'^(?P<slug>[-\w]+)/edit/$', update_post, name = 'update_post'), url(r'^category/(?P<slug>[-\w]+)/$', category, name='category'), url(r'^(?P<slug>[-\w]+)/$', detail, name = 'detail'), url(r'^$', listofposts , name='listofposts'), ] and my view in post.views: def listofposts(request, category_slug = None): html = 'base.html' Category_all = Category.objects.all() query_set_list = Post.objects.all() query = request.GET.get("q") if query: query_set_list = query_set_list.filter(title__icontains=query) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Post.filter(category=category) context = { "title" : 'Записки', "list" : query_set_list, 'category_all' : Category_all, } return render(request, html, context) def detail(request, slug): Category_all = Category.objects.all() html = 'post_detail.html' query_set = Post.objects.all() instance = get_object_or_404(Post, slug = slug) context = { "title" : instance.title, "instance" : instance, "list": query_set, 'category_all' : Category_all, } return render(request, html, context) And I got the next mistake Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. <a href="{{ x.get_absolute_url }}"><p>{{ x.title }}</p></a> Everything worked fine untill I added url link to another app. If I delete url link to another view everithing will be okay. Thx a lot if you … -
Django REST Framework AutoSchema parameters list in ViewSet action
I want to generate swagger (OpenAPI) schema for my DRF project. How can I add query parameters specification to the generated schema? Take a look at FileViewSet.list method. Here request.GET parameter project should be documented, but automatic schema generation misses it. Here is example api project: # views.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ('name', 'id', 'project') class FileViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer def list(self, request): project = request.GET.get("project", None) qs = self.get_queryset().filter(project=project) router = routers.DefaultRouter(trailing_slash=False) router.register(r'^file$', FileViewSet) # OpenAPI Schema generation class SwaggerRenderer(renderers.BaseRenderer): media_type = 'application/openapi+json' format = 'swagger' def render(self, data, media_type=None, renderer_context=None): codec = OpenAPICodec() return codec.dump(data) schema_view = get_schema_view( title='API', public=True, renderer_classes=[SwaggerRenderer], authentication_classes=[], permission_classes=[AllowAny], patterns=router.urls, ) api_urls = router.urls + [url(r'^schema$', schema_view, name="schema")] And then inluding api_urls in the urls.py: # urls .py from .views import api_urls urlpatterns = [ url(r'^v1/', include(api_urls, namespace="v1")), ] -
Issue with timezones in Django Application
I am working on leave system in which manager has employees from different countries and I am displaying who is out of office today.But all the leaves stored in database are in UTC.At now I am comparing today=datetime.datetime.now(pytz.utc).date() with DateField in Database leave_today=leave.objects.filter(status='A',start_date__lte=today, end_date__gte=today,employee_id=request.user.username) With the above query written in views I am fetching who are Out of office. But I now I want to display according to employee time zones. So I can query today as today=datetime.datetime.now(pytz.timezone('Asia/Calcutta')).date() But start_date and end_date in leave_today query are in UTC.How can I change respective start_date and end_date to their timezone within the query of employee and compare it? -
Download pandas generated csv from django response
I'm trying to convert json into csv. Csv file is generate but now I want to return this file with django HttpResponse. Here is my views @is_login_valid def convert_json_to_csv(request): params = request.GET response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=filename.csv' response = get_data_from_server(params.get('graph_id')) df = pd.io.json.json_normalize(response['data']) df.to_csv('data.csv') return response How I pass this csv file to django response without saving file. -
Django local server error
I started learning django and just deployed my first app when this showed up. Any suggestions would be useful. (https://i.stack.imgur.com/GgMjG.png) -
How can I associate story_author name with request.user?
My first problem is once I save a story, the story.author will not associate with request.user. So it brings to another problem, I have to add story_author from user list, and then select an author for the story manually. Here is my damin looks like models.py class StoryAuthor(models.Model): """ Model representing a author. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def get_absolute_url(self): """ Returns the url to access a particular story_author instance. """ return reverse('stories_by_author', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return self.user.username class Story(models.Model): author = models.ForeignKey(StoryAuthor,related_name='stories',null=True) sb_thing = models.CharField(max_length=30,null=True) sb_story = models.CharField(max_length=30,null=True) sb_name = models.CharField(max_length=30,null=True) views.py def story_new(request): if request.method == "POST": form = StoryForm(request.POST) #form.StoryAuthor = request.user if form.is_valid(): story = form.save(commit=False) StoryAuthor = request.user story.published_date = timezone.now() story.save() return redirect('story_detail', pk=story.pk) else: form = StoryForm() return render(request, 'story/story_create.html', {'form': form}) -
Django Model - Charfield with choices from a row in another model?
I have created a settings table in Django as per the below:- class Settings(models.Model): name = models.CharField(max_length=200) class Meta: verbose_name = "Settings" verbose_name_plural = "Settings" def __str__(self): return self.name class SettingChoices(models.Model): setting = models.ForeignKey(Settings, on_delete=models.PROTECT) choice = models.CharField(max_length=200) class Meta: verbose_name = "Setting Choices" verbose_name_plural = "Setting Choices" def __str__(self): return '{0} - {1}'.format(self.setting, self.choice) and a sample use of this would be:- Setting = Circuit Type: Choices: DSL 4G Fibre then in another model I want to be able to reference this as set of choices class Circuits(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT) order_no = models.CharField(max_length=200, verbose_name="Order No") expected_install_date = models.DateField() install_date = models.DateField(blank=True, null=True) circuit_type = models.CharField(max_length=100, choices=*** here I would get model settings - Circuit Type - Choices ***) currently I use a list in settings.py but its not fluid, I need my users to be able to alter these settings not for me to manually edit a list in settings.py and push changes each time I attempted the below: functions.py def settings_circuit_types(): from home.models import SettingChoices type_data = SettingChoices.objects.filter(setting__name='CIRCUIT_TYPES') circuit_types = [] for c in type_data: circuit_types.append(c.choice) return circuit_types models.py from app.functions import settings_circuit_types CIRCUIT_CHOICES = settings_circuit_types() ... circuit_type = models.CharField(max_length=100, choices= CIRCUIT_CHOICES) but this has … -
Django management command without working db connection
I have a number of projects that use the following configuration model: settings.py includes default configuration and config specifications, mainly used for development purposes. The default settings (including db settings) can be overridden by external configuration files, usually defined by admins for the various environments they manage. In order to ease the admins, I have written a management command and packaged separately, which adds the option to create example configuration files based on the default configuration in settings.py Trying to run the command without the possibility for successful db connection, however, raises django.db.utils.OperationalError. How can I make the command work without db connection, as it does not need one and normally when the command is needed, most probably the db connection is not configured properly. settings.DATABASES != {} as there are the default db settings. Django 1.10.6, Python 3.5.3 -
How to dynamically and conditionally add a list of fields to a queryset in Django?
I want to be able to dynamically add computed fields to my django model from the view. What I have: Foo = Bar.objects.all() FooList = ['E','F','G'] The current output is something like: A | B | C 1 | 1 | 1 2 | 5 | 6 The goal is: A | B | C | E | F | G 1 | 1 | 1 | - | 0 | 5 2 | 5 | 6 | 1 | - | 8 The trouble is that not all values of E, F, G have a value, so filter won't work here. I think I have to combine conditional annotation and dictionary unpacking, so something like: for FL in FooList: Foo = Foo.annotate(**{FL: Sum(When(some_Barvar=FL, then='Other_Barvar'))}) The trouble is, when I add an output_field, it cannot resolve it, and when I do not I get a syntax error near WHEN. I am not sure what I am doing wrong. From the documentation I think it is possible to use a dynamic value for then, in my case that being 'Other_BarVar', but I cannot seem to get it to work in conjuncture with Sum. Anyone have an idea of what I'm doing … -
Django collecting static from virtualenv app on apache wgsi
I'm using autocomplete-light 3 in Django project. I publish production with an virtualenv. Autocomplete-light come with some static file in. I added in settings: STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), '/......../........../myapp/static', '/home/myuser/.virtualenv/prd_vrt/lib/python2.7/site-packages/dal/static', '/home/myuser/.virtualenv/prd_vrt/lib/python2.7/site-packages/dal_select2/static', ) but it was not enough to publish the static files. If I include the file in my static folder it works. I don't think this is the best solution ( not easy maintenance). May I add some permission to apache? Or what is the best way to archive this situation? -
Multiple django model values depend on choice field value
My Django model has a pricing_plan choice field. There are 12 fields whose value depends on the pricing_plan value. class Organisation(models.Model): PRICING_CHOICES = ( ('basic', 'Basic'), ('team', 'Team'), ('super', 'Super') ) # some fields... pricing_plan = models.CharField(max_length=50, default='basic') max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) # more fields whose value depends on pricing_plan value For every different pricing_plan these fields get specific values. In code that could be described like: if pricing_plan == 'basic': max_host_accounts = 1 max_admin_accounts = 1 max_guests = 10 ... elif pricing_plan == 'team': max_host_accounts = 10 max_admin_accounts = 3 max_guests = 25 ... However, there might be more pricing plans in the future and more options and I am afraid that an if/elif/else statement will be huge and not-easily readable. What would be the best/idiomatic way to implement that in a Django model? Use more CHOICE tuples with constant values for every pricing plan? Use Enum classes with constant values for every pricing plan? Use Organisation as parent class and create subclasses like: . class BasicOrganisation(Organisation): max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) class TeamOrganisation(Organisation): max_host_accounts = models.IntegerField(default=10) max_admin_accounts = models.IntegerField(default=3) max_guests = models.IntegerField(default=25) Anything else? -
How I select any elements with same id in javascript in django
I have a table in Django where all the answers of a test are stored, but when I select them to compare with the response provided by the user, all the answers are the same as the first question. I know this has to do with getElementsById, which only selects the first element. But how do I select all elements of the same id in HTML? {% for resposta in questao.resposta_set.all %} <input type="hidden" id="resposta" name="resposta" value="{{resposta.resposta}}"> <script type="text/javascript"> function mostrarSel(){ if (getRadioValor('opcao_escolhida') == document.getElementById("resposta").value){ alert('Resposta Correta'); } else{ alert('Resposta Incorreta'); } } function getRadioValor(name){ var rads = document.getElementsByName(name); for(var i = 0; i < rads.length; i++){ if(rads[i].checked){ return rads[i].value; } } return null; } </script> {% endfor %} -
How to improve time of python code with database queries
I have some database queries in Django 1.11 which takes about 40 seconds and I want to improve the speed, but my ideas are going out. I want to create a Chart with 6 graphs with the data without having to wait 40 seconds. This is The Model: from django.db import models class MinutenReserveLastYear(models.Model): datum = models.DateField() produkt = models.CharField(max_length=100) grenz_lp = models.FloatField() mittl_lp = models.FloatField() class Meta: indexes = [ models.Index(fields=['datum', 'produkt']), ] I make an Ajax request to get the Data: var neg_last_year = $.ajax({ method: "POST", url: "/prognose/minutenreserve/data/", data: { "produkt": "NEG", "zeitraum": "last_year" }, dataType: "json", context: this }); The view function to get the Data from database: def minutenreserve_data(request): if request.method == "POST": produkt_group = request.POST.get("produkt") zeitraum = request.POST.get("zeitraum") datum_list = {} grenz_lp = {} mittl_lp = {} if zeitraum == "last_year": if produkt_group == "NEG": produkt_list = ["NEG_00_04", "NEG_04_08", "NEG_08_12", "NEG_12_16", "NEG_16_20", "NEG_20_24"] dataset = MinutenReserveLastYear.objects last_year = datetime.date.fromtimestamp(datetime.datetime.timestamp( datetime.datetime.now() - datetime.timedelta(weeks=52))).year days = (datetime.date(last_year, 12, 31) - datetime.date(last_year, 1, 1)).days for j in range(6): grenz_lp[j] = [] mittl_lp[j] = [] datum_list[j] = [] produkt = produkt_list[j] for i in range(days+1): datum = datetime.date(last_year, 1, 1) + datetime.timedelta(days=i) datum_list[j] += [datum.strftime('%d.%m.%Y')] grenz_lp[j] += [dataset.filter(datum=datum, … -
How can I ensure changes to my Celery countdown wont break anything?
I have a number of celery tasks in my Django application that are currently being tested synchronously using CELERY_ALWAYS_EAGER. However this option means that I can't test that changes to the countdown value in apply_async won't break anything. How can I test that nothing else in my application was depending on the longer countdown now that I suspect I no longer need it? I'm using Django 1.10 and Celery 3.1 with Python 3.5. -
Convert flask application to django Blueprint() function
I'm converting this flask application, we use the blueprint function in 3 '.py' files. In the demosite.py file we register using - app.register_blueprint(app_name) and then in 2 '.py' files we use the blueprint function as: some_name = Blueprint('some_name', name)(the double underscore is not shown on either sides of name as it "name" becomes in Bold letters! -_-). Moving over, Now in flask we use the Blueprint() function. I have to covert this flask application to django application. How can I implement the same function? This image shows 1st one is the demosite where the registration is done and the rest two are login.py and uma.py where Blueprint() is used. -
Elastic beanstalk Django admin css not loading
Using Django 1.11.6, python 3.6.2 Short summary: static files are collected correctly on server but only one app's sub directory is served, the admin's static files return as 404. Running the local development server everything works as expected. After deploying to my EB instance none of the static files for the admin app load. If i run eb ssh and look around on the server I can see the collected static folder, along with all the different app's subfolders. The files are all there where I'd expect. The links produced on the django front-end map in a sensible way to these paths, it's just that anything in static/admin returns a 404, while the files in static/entities work fine. Testing paths on the front end: /static/admin/css/base.css (404) /static/entities/style.css (works) On server, all collected files in static look fine: /opt/python/current/app/static/admin/css /opt/python/current/app/static/entities No idea why one sub directory is server fine but the others return 404s. From my django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "spf.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: spf/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" ... 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" Running the collectstatic command locally produces the correct static folder with the same subdirectories for each … -
Django queryset, order by dynamic criteria based on external value
I need to scramble order of a queryset, based on an external value. The order must be replicable. For example (with sorted, but if it's possible inside the queryset is better): value = 1 sorted(MyModel.objects.all(), lambda n, value: < what to put here?>) For example, If MyModel has 5 objects, I think something like: value | order 1 | 1, 4, 2, 5, 3 2 | 4, 1, 5, 3, 2 3 | 5, 1, 3, 2, 4 -
Django prefetch_related and select_related
I am wondering about the behaviour of prefetch_related() and select_related(). If I do something like Model.objects.filter(...).prefetch_related(), I notice that there are much less database queries occurring. So my initial guess is that, if one does not specify the needed look-ups in prefetch_related(), it will automatically go through all of the model fields and do the needed job. However, I cannot find any reference to it on the web, which seems pretty strange to me. Is my guess correct or am I missing something? -
DRF: Creating a list in a field
I am new to DRF and I want to create a field that can take multiple value. I tried using StringListField as: in my serializers.py,: class StringListField(serializers.ListField): child = serializers.CharField() class XYZSerializer(serializers.ModelSerializer): branch = StringListField(max_length=20) class Meta: model = Api fields = ('id', 'notice_name', 'notice_desc', 'notice_author', 'notice_valid_till', 'notice_publish_date','year', 'branch') views.py class AddNotice(APIView): permission_class = (IsAuthenticated,) serializer_class = AddNoticeSerializer def post(self, request, format=None): data = request.data serializer = AddNoticeSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) But as soon as I post it gives something like this error: File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "/home/yathartha/Desktop/Desktop/notices-api/api/views.py", line 28, in post serializer.save() File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save self.instance = self.create(validated_data) File "/home/yathartha/Desktop/Desktop/notices-api/api/Serializers.py", line 19, in create return Api.objects.create(**validated_data) File "/home/yathartha/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
How to get extension of file
I am trying to get mimetype from decoded string. I sent base64 string of a xls file, This is my code: def save_file(request_data, id=None): """ """ data = base64.b64decode(request_data.get('file')) mime = magic.Magic(mime=True) content_type = mime.from_buffer(data) print(content_type) print(guess_extension(content_type.decode("utf-8"))) Output: b'application/octet-stream' Unable to get file extensions. Does anyone know how to get file extension from base64 string. -
Generating single hash of CSV file
I have a service that received CSV files with size ranging from MBs to GBs and I need to generate a single hash against all contents of a file. Is there an optimized solution for this that doesn't require me to read the file line by line and concatenate each line in a string and then generate a hash of that string? That method would take too much time for a file that can contain millions of rows. Any help will be appreciated. By the way, I will be using SHA256 from hashlib for hashing. -
Datatables uncaught reference error with django
Hi i'm using datatable in a django/python app, i have an index page that load a list from a DB and put it in a datatable. Since this morning i have an error that start with : TypeError : C is undefined (that seem to point on the line where i define the datatable) and then of course this error pop everytime the setInterval is called on this tab : ReferenceError : oTable is undefined My view : def index(request): listOPT = [] Data = [] fluxManagerState = settings.FLUX_MANAGER_STATE cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = dictfetchall(cursor) finally: cursor.close() return render(request, 'index.html', locals()) Function that works with ajax to refresh the datatable : def listMVTinit(request): cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") data = dictfetchall(cursor) finally: cursor.close() return HttpResponse(json.dumps(data), content_type = "application/json") My template : {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Liste Mouvement initiaux</title> <meta name="generator" content="WYSIWYG Web Builder 12 - http://www.wysiwygwebbuilder.com"> <link href="{% static 'css/Gestion_Mouvements.css' %}" rel="stylesheet"> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <link href="{% static 'css/base/jquery-ui.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/jquery.dataTables.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'css//bootstrap-datetimepicker.min.css' %}" media="all" rel="stylesheet"> <script src="{% static 'js/jquery-1.12.4.min.js' … -
NoReverseMatch django template url
Sory for my english. I can understand why my code doesnt work. Before it work, but now, i run server, test, and this code not work. I have url when user is registration, i send him activation email, like this: def send_activation_email(serializer, request, user): current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your blog account.' to_email = serializer.data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() acc_active_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} and my url file . . url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate_account, name='activate'), . . but i have error: Exception Type: NoReverseMatch Exception Value: Reverse for 'activate' with keyword arguments '{'uidb64': b'NDM', 'token': '4qz-8f770502bd8b02786da9'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] highlights this line http://{{ domain }}{% url 'activate' uidb64=uid token=token %} -
One view for multiple sub-domains using django-hosts
I need to have multiple sub domains for my project. Each sub domain represents some company. For example: company1.myproject.io, company2.myproject.io. I used django-hosts library to set up sub domains. hosts file: 127.0.0.1 localhost 127.0.0.1 myproject.io 127.0.0.1 www.myproject.io 127.0.0.1 company1.myproject.io 127.0.0.1 company2.myproject.io settings.py: ROOT_URLCONF = 'core.urls' ROOT_HOSTCONF = 'core.hosts' DEFAULT_HOST = 'www' DEFAULT_REDIRECT_URL = "http://www.myproject.io:8000" core/hosts.py: from hostsconf import urls as redirect_urls host_patterns = [ host(r'www', settings.ROOT_URLCONF, name='www'), host(r'(?!www).*', redirect_urls, name='wildcard'), ] hostsconf/urls.py: from .views import wildcard_redirect urlpatterns = [ url(r'^(?P<path>.*)', wildcard_redirect) ] hostsconf/views.py: DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.myproject.io:8000") def wildcard_redirect(request, path=None): new_url = DEFAULT_REDIRECT_URL if path is not None: new_url = DEFAULT_REDIRECT_URL + "/" + path return HttpResponseRedirect(new_url) I have a few problems now: When I go to myproject.io it succesfully redirects me to the www.myproject.io. But when I go to company1.myproject.io I got an Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong? How to implement a single view for all sub-domains where will by dynamic context for each company. Basically I need to make queries into the db by sub domain name. …