Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form validation failing - pytz and choices
I am trying to let the user set which timezone they are in, however form validation .is_valid() is failing and cannot figure out why. The timezone value for a user is stored in a Profile model. Using ChoiceField and pytz.common_timezones to fill the form field This would be appear to be quite simple to do, the only thing thats different to my usual way is that the data filling the combo/select box is the use of a ChoiceField and the data is coming from pytz. I may switch to django-timezone-field to solve this, but I would like to understand why it is failing. I have included all relevant (I think) code below. Any suggestions? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) timezone = models.CharField( max_length=255, blank=True, ) forms.py class ProfileEditForm(forms.Form): profile_timezone = forms.ChoiceField(choices=[(x, x) for x in pytz.common_timezones]) views.py @login_required def userprofile_edit(request): if request.method == "POST": profile_edit_form = ProfileEditForm() if profile_edit_form.is_valid(): cd = profile_edit_form.cleaned_data user = User.objects.get(id=request.user.id) user.profile.timezone = cd['timezone'] user.profile.save() messages.success(request, "Profile updated successfully", fail_silently=True) return redirect('coremgr:userprofile', request.user.id) else: messages.error(request, "Error occured. Contact your administrator", fail_silently=True) print "error: form not valid" else: profile_edit_form = ProfileEditForm() context = … -
How do I set the same session variable for all views programmatically?
I want to create a "Sign up for our newsletter" pop up that has a "No thanks" button. I want Django to remember that the user clicked the "No thanks" button. What I know is that sessions/cookies are set in their respective views. I see examples on StackOverflow of them set in the home/index view. What if the user visits a different page? Then the session variable won't be set unless they visit that one page. I'd like for the same variable set regardless of what page they view. -
Should I use PostgreSQL or MongoDB for my chatbot?
Where the database will store certain words along the response for those words. I'm using Django (Python) -
tastypie: How to get a queryset with request.user as an argument?
I use django_vote to handle the voting job in my website. It has an API like Entry.votes.all(request.user.id) and it will return all votes by the request.user. But how to use it in tastypie to get the corresponding entries by the current request user? #api.py class EntryResource(ModelResource): class Meta: queryset = Entry.objects.all() resource_name = 'entry' -
How to get the aws s3 object key using django-storages and boto3
I am using django-storage and boto3 for media and static files using aws s3. I need to get the object key of aws s3 bucket, so that I can generate a url for that object. client = boto3.client('s3') bucket_name = 'kakar-django' key = ??? u = client.generate_presigned_url('get_object', Params = {'Bucket': bucket_name, 'Key': key,'ResponseContentType':'image/jpeg', 'ResponseContentDisposition': 'attachment; filename="your-filename.jpeg"'}, ExpiresIn = 1000) These are in my settings: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' STATICFILES_STORAGE = 'myproject.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'myproject.custom_storages.MediaStorage' AWS_ACCESS_KEY_ID = "my_access_key_id" AWS_SECRET_ACCESS_KEY = "my_secret_access_key" AWS_STORAGE_BUCKET_NAME = "django-bucket" AWS_QUERYSTRING_AUTH = False AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com" # static media settings STATIC_URL = "https://" + AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com/" MEDIA_URL = STATIC_URL + "media/" ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/" I can get the file path of the image file ui = UserImage.objects.get(user=user_id, image=image_id) url = ui.image.url 'https://my-bucket-django.s3.amazonaws.com/media/user_image/1497598249_49.jpeg' But I don't know how to get the s3 object key so that I can generate a url for that object. -
django-fsm: Permissions not raising exception
I've got source and target rule-based transition decorators working well in django-fsm (Finite State Machine). Now I'm trying to add permissions handling. This seems straightforward, but it seems that no matter what I do, the transition is executed, regardless the user's permissions or lack thereof. I've tried with Django permission strings, and I've tried with lambda, per the documentation. Finally, I tried this: @transition(field=state, source='prog', target='appr', permission=False) def approve(self): Which should raise a TransitionNotAllowed for all users when accessing the transition. But nope - even basic users with no permissions can still execute the transition (claim.approve()). I am doing validation as follows (works for source/target): class ClaimEditForm(forms.ModelForm): ''' Some users can transition claims through allowable states ''' def clean_state(self): state = self.cleaned_data['state'] if state == 'appr': try: self.instance.approve() except TransitionNotAllowed: raise forms.ValidationError("Claim could not be approved") return state class Meta: model = Claim fields = ( 'state', ) and the view handler is the standard: if request.method == "POST": claim_edit_form = ClaimEditForm(request.POST, instance=claim) if claim_edit_form.is_valid(): # Validate transition rules What am I missing? Thanks. -
Scrapyd only - No module name django_project.settings
This error only happens on the command scrapyd-deploy. Packing version r240-master Deploying to project "foo_bot" in http://localhost:6802/addversion.json Server response (200): { "status": "error", "message": "Traceback (most recent call last): File \"/usr/lib/python2.7/runpy.py\", line 174, in _run_module_as_main \"__main__\", fname, loader, pkg_name) File \"/usr/lib/python2.7/runpy.py\", line 72, in _run_code exec code in run_globals File \"/usr/local/lib/python2.7/dist-packages/scrapyd/runner.py\", line 40, in <module> main() File \"/usr/local/lib/python2.7/dist-packages/scrapyd/runner.py\", line 37, in main execute() File \"/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py\", line 109, in execute settings = get_project_settings() File \"/usr/local/lib/python2.7/dist-packages/scrapy/utils/project.py\", line 68, in get_project_settings settings.setmodule(settings_module_path, priority='project') File \"/usr/local/lib/python2.7/dist-packages/scrapy/settings/__init__.py\", line 292, in setmodule module = import_module(module) File \"/usr/lib/python2.7/importlib/__init__.py\", line 37, in import_module __import__(name) File \"build/bdist.linux-x86_64/egg/foo_bot/settings.py\", line 21, in <module> File \"/usr/local/lib/python2.7/dist-packages/django/__init__.py\", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File \"/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py\", line 56, in __getattr__ self._setup(name) File \"/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py\", line 41, in _setup self._wrapped = Settings(settings_module) File \"/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py\", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File \"/usr/lib/python2.7/importlib/__init__.py\", line 37, in import_module __import__(name) ImportError: No module named foo_project.settings ", "node_name": "ubuntu" } The project structure is as follow: /home/dev/workspace/fufu |--dev_venv/bin/activate | |--foo_bot | |--scrapy.cfg | | | |--foo_bot | |--settings.py | |--settings_dev.py | |--settings_deploy.py | |--items.py and blablabla | |--spiders | |--blablablaspider.py | |--foo_project |--manage.py | |--app | |--models.py and blablabla | |--foo_bot |--settings.py |--settings_dev.py |--settings_deploy.py |--wsgi.py and blablabla scrapy.cfg [settings] … -
Is there a way to make share a database between a php website and a django website?
I am on a school project to build an e-learning website, i used to write in django and a my team mate needs php.So we decided to build some pages with php and some apps with django. Is there a way to connect the student databse between the two websites? -
dj-stripe and "Intervals between charges"
I have a test site that has dj-stripe (Python 3.5 and Djang0 1.10) set up to collect payments for subscriptions. The test payments appear to be collected and the user is assigned a subscription of 3, 6 or 12 months in length. However, when I open dj-stripe in the django-admin, and confirm the subscription the "Intervals between charges" which should be 3, 6 or 12 (months) is always 1, which means that the "current period end" is always 1 month from the date of the start of the subscription. Displayed below is an example of a 3 month subscription showing a 1 month difference between start and finish dates, but should be 3 months. Here is the related dj-stripe plan from django-admin: And just for reference, here is the dj-stripe plan code with the interval count and month duration added: DJSTRIPE_PLANS = OrderedDict() DJSTRIPE_PLANS["3months_40"] = { "stripe_plan_id": "3months_40", "title": _('3 Months'), "name": _('3 Months - USD$40'), "description": "3 months subscription", "price": 4000, # $40.00 "currency": "usd", "interval": "month", "interval_count": 3, "duration_months": 3, "css_class": "service-block-dark", "languages_limit": 2, "show_to_user": True, } I have read the docs, but cannot work out the issue. Has anyone else encountered this issue? -
How to use Django with Celery on Docker?
I'm trying to use docker with django & celery, I'm having a problem starting the worker when using docker-compose up because I get this error : ModuleNotFoundError: No module named 'oqtor' The issue is on my docker-compose.yml : version: '2' services: nginx: ... web: ... db: ... redis: ... celery: build: . container_name: celery command: 'python -m celery -A oqtor worker -l info' <--- Here volumes: - ..:/src links: - db - redis On celery's documentation I found that I had to use : celery -A proj worker -l info but I'm unsure if it's the correct piece of code, if you need to take a look to any other file I put the project on Github. Structure of folders : any suggestion ? -
Django and querying many tables to supply to mobile
I'm currently in the process of creating an android app for work, but have run into a problem I am not exactly sure how to go about resolving. I currently have an android app, and a django/mysql backend. Up until now I've used 1 query = 1 table, the user requests something, the app sends a request to the server, and the server responds with all the data in json format that the app then parses. My problem now is, I have lots of data that I need to be able to separate somehow, but query all at one time. My first thought was to put it all in one big table and assign each Item/sub-item a category, ex with vehicles. F150 | Category = 300 F150 Tires = 300 F250 | Category = 301 F250 Radiator Cap = 301 F350 | Category = 302 F350 Air Filter = 302 Camaro | Category = 400 Camaro Oil Filter = 400 Volt | Category = 401 And then when the table is queried, have the android app sort it out by its category. This way feels very cumbersome and wrong. My next thought was to separate each category into its own … -
Getting current user in django rest framework
I'm having a lot of trouble over getting the current user that is uploading image in django rest framework. Django rest framework is an app inside the pure django that is used for webpage. Im using django rest framework so that users can upload files on our server... Everything works great except we need to know who was the user that uploaded it. I really tried many solutions that this site and google has to offer but just can't make it work. Here is the code from the app. What do we have to do? viewset.py from rest_framework import viewsets, filters from api.serializers import UploadedImageSerializer # import our serializer from api.models import UploadedImage # import our model class UploadedImagesViewSet(viewsets.ModelViewSet): queryset = UploadedImage.objects.order_by('-id')[:1] serializer_class = UploadedImageSerializer serializer.py from rest_framework import serializers from api.models import UploadedImage # Import our UploadedImage model class UploadedImageSerializer(serializers.ModelSerializer): # Create a custom method field # current_user = serializers.SerializerMethodField('_user') class Meta: model = UploadedImage fields = ('id', 'image','name','Tip','curent_user') # only serialize the primary key and the image field models.py from django.db import models import uuid,os import sqlite3 import Function1 import Function2 from django.contrib.auth.models import User def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] # print ("gdje uploda","{}.{}".format(uuid.uuid4(), extension)) return "{}.{}".format(uuid.uuid4(), … -
How do I set up a parent-child relation with GenericForeignKey in django?
I have the following models: class Blog(models.Model): name=models.CharField(max_length=200) class Topic(models.Model): name=models.CharField(max_length=200) class Article(models.Model): name=models.CharField(max_length=200) class Post(models.Model): name=models.CharField(max_length=200) A blog or topic can be a parent for one or more articles or posts. I want to add a parent field to Article and Post such that I can call the following: article.parent # returns parent (blog or post) of the article blog.children.all() to get all articles and posts under the blog, ordered by name One approach (approach A) is to use a parent GenericForeignKey: class ParentMixin(models.Model): content_type = models.ForeignKey( ContentType, related_name='%(app_label)s_%(class)ss' ) object_id = models.PositiveIntegerField() parent = GenericForeignKey() class Meta: abstract = True class Article(ParentMixin): ... class Post(ParentMixin): ... The trouble here is that I cannot get the related_name to be abstract (like children) - I have to specify %(app_label)s_%(class)s which means I can call blog.appname_articles and blog.appname_posts, but I cannot call blog.children - this also means I cannot get all children of a blog ordered by name. Another approach (approach B) I considered is to create a ParentChild model with two GFKs, and use it to navigate between parent and child objects: class ParentChild(models.Model): parent_content_type = models.ForeignKey(ContentType) parent_object_id = models.PositiveIntegerField() parent = GenericForeignKey('parent_content_type', 'parent_object_id') child_content_type = models.ForeignKey(ContentType) child_object_id = models.PositiveIntegerField() … -
What does request.GET.get means?
What does request.GET.get means? I see something like this in Django page = request.GET.get('page', 1) which I think is connected to something like <li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li> How do they work? -
Ajax get request with Django ListView Page Reload
I'm using a js calendar picker plugin to pass the date value to django view, and base on the date it should render the a new view to the same web page. Since in this view I'm pulling tons of data from different table, I use the ListView. Question is, when I use the get function in listview, I'm able to capture the data passed from ajax. How do I pass that data to get_context_data to regenerate the context and reload the page? Thx Here is my js: <script type="text/javascript"> $(function() { var start = moment().subtract(29, 'days'); var end = moment(); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); $.ajax({ type: 'GET', url: "/csr/summary/", data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), from_date: from_date, to_date: to_date, }, success: function (response) { } }); console.log("done here"); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], } }, cb); cb(start, end); }); </script> And here is my view: class CsrView(generic.ListView): template_name = 'dash/csr.html' context_object_name = 'csr_list' from_date = "" to_date = "" def get(self, request, *args, **kwargs): self.from_date = self.request.GET.get("from_date", "") self.to_date = self.request.GET.get("to_date", "") … -
django ImageField not displaying, throws ImportError
I have a model where Ihave an image name, image description, and an image. I want to use these fields to display a div with the image description and name with the thumbnail for each row in my model. Right now when I am trying to render the template I am getting: ImportError: No module named 'backends' Code: Models.py class PictureType(models.Model): name = models.CharField(max_length = 150) description = models.CharField(max_length = 1000) image = models.ImageField(upload_to='AppName/images/') views.py class indexView(generic.ListView): model = PictureType template_name = 'index.html' index.html {% for visual in object_list %} <div class="col-sm-4"> <div class="thumbnail"> <a href="#" class=""> <div align="center" class={{ visual.name }}> <h4 class="">{{ visual.name }}</h4> <p class="">{{ visual.description }} </p> </div> <img src= "{{ visual.image.url }}" alt="..." class=""> </a> </div> </div> {% endfor %} settings.py MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', indexView.as_view(), name = 'index'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django ajax delete sending wrong id and not refreshing
I'm trying to use django and ajax to edit user's profiles from my listview. Everything seemed to be working correctly except for ajax refreshing the page. However, I just noticed that my delete function is sending the logged in users ID instead of the selected user. Can someone help me with both the refresh issue and the delete issue, please. Here is my code: view for delete fucnction: def employee_delete(request, pk): employee = get_object_or_404(UserProfile, pk=pk) data = dict() if request.method == 'POST': employee.delete() data['form_is_valid'] = True # This is just to play along with the existing code employees = UserProfile.objects.all() data['html_employee_list'] = render_to_string('pages/employees.html', { 'employees': employees }) else: context = {'employees': employee} data['html_form'] = render_to_string('partials/employee_delete.html', context, request=request, ) return JsonResponse(data) table in listview: <tbody> {% for profile in user_profile_list %} <tr> <td><a href="{% url 'dispatch:profile_detail' pk=profile.user_id %}">{{ profile.user.get_full_name }}</a></td> <td>{{ profile.user.username }}</td> <td> {% if profile.user.is_superuser %} <div class="tag tag-danger">Super User</div> {% else %} {% for g in profile.user.groups.all %} <div class="tag tag-default">{{ g.name|split:'_'|title }}</div> {% endfor %} {% endif %} </td> <td>{{ profile.user.email }}</td> <td>{{ profile.mobile_phone|phone_number }}</td> <td> <button class="btn btn-warning btn-sm js-update-employee" data-url="{% url 'dispatch:employee_update' pk=profile.user_id %}"><i class="fa fa-pencil"></i></button>&nbsp;&nbsp; <a href="#" alt="Assign"><i class="fa fa-link"></i></a>&nbsp;&nbsp; <button class="btn btn-warning btn-sm … -
Django GenericIPAddress como hacer que no sea campo requerido
Buenas tengo una consulta intento montar un sitio de encuesta pero los usuarios que tendran acceso No estaran registrados, la forma de validar que no respondan mas de una vez la encuesta sera por medio de su Ip entonces encontre este tipo de campo pero quiero especificar que ese campo no sea requerido si no que mas bien exista un metodo que lo capture al momento que se quiera hacer la encuesta y asi validar que sea otro usuario. Gracias espero de su ayuda -
Celery worker goes into infinite startup and shutdown cycle
I've been using celery (the async task queue in python) in a Django project with Redis as a results backend and broker for a few years now - today I tried switching the backend / broker to AWS's ElastiCache Redis, but the celery worker goes into an infinite startup and shutdown cycle as seen below in the log file. I have also successfully connected to the Redis instance from the same machine running celery and done some basic SET and GET operations successfully. My current setup is: OS: Ubuntu 14.04 Python 2.7.6 Celery 3.1.17 Kombu 3.0.37 Billiard 3.3.0.23 command: celery worker --concurrency=3 --queues=general --events --loglevel=DEBUG --beat --schedule=/tmp/celerybeat-schedule --pidfile=/tmp/celery.main.pid --config=celeryconfig celerconfig.py: import os from django.conf import settings from celery import Celery, Task, chain os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') celery = Celery() celery.config_from_object("celeryconfig") celery.autodiscover_tasks(settings.INSTALLED_APPS, related_name='tasks') BROKER_URL = "redis://staging-redis.abcde.clustercfg.use1.cache.amazonaws.com:6379/0" CELERY_TIMEZONE = u'America/Los_Angeles' CELERYD_HIJACK_ROOT_LOGGER = True CELERY_IMPORTS = ( "app.tasks" ) CELERYD_TASK_TIME_LIMIT = 35 # seconds CELERYD_TASK_SOFT_TIME_LIMIT = 25 # seconds DJANGO_SETTINGS_MODULE = "settings" CELERY_RESULT_BACKEND = BROKER_URL CELERY_ROUTES = { 'app.tasks.my_task': {'queue': 'general'} } celery.log: -------------- celery@ip-10-20-21-9 v3.1.24 (Cipater) ---- **** ----- --- * *** * -- Linux-3.13.0-74-generic-x86_64-with-Ubuntu-14.04-trusty -- * - **** --- - ** ---------- [config] - ** ---------- .> app: default:0x7f7dc6d71650 (.default.Loader) - ** ---------- … -
locking some special rows of a database table n django
I have a model in Django like follows: class A(models.Model): STATUS_DEFAULT = "default" STATUS_ACCEPTED = "accepted" STATUS_REJECTED = "rejected" STATUS_CHOICES = ( (STATUS_DEFAULT, 'Just Asked'), (STATUS_ACCEPTED, 'Accepted'), (STATUS_REJECTED, 'Rejected'), ) status = models.CharField(choices=STATUS_CHOICES, max_length=20, default=STATUS_DEFAULT) question = models.ForeignKey(Question) Notice that Question is another model in my project. I have a constraint on the A model. Between rows with the same question only one of them can has status=STATUS_ACCEPTED and at the first all of them have status=STATUS_DEFAULT. I want to write a function that does the following : def accept(self): self.status = STATUS_ACCEPTED self.save() A.objects.filter(question=self.question).update(status=STATUS_REJECTED) But if two instances of A with same question call this function maybe a race condition will happen. So the one who calls this function sooner should lock other instances with same question to prevent race condition. How should I do this? -
How to serve static files using Nginx and Django on Docker?
I've read some posts about this issue on StackOverflow already but couldn't fix my issue with them, as the title says I'm trying to serve static using django, nginx on docker. At first I was getting an error saying PermissionError: [Errno 13] Permission denied: '/static/admin'. I've figured out that I had to change STATIC_ROOT from STATIC_ROOT = '/static' to STATIC_ROOT = os.path.join(BASE_DIR, 'static'). Now collectstatic works on the Docker's Terminal but my webapp's static is still not working, I would like to understand why and fix it. I've put the project on Github if you need any more infos. oqtor.conf upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /static/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } docker-compose.yml version: '2' services: nginx: image: nginx:latest container_name: nz01 ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /static:/static depends_on: - web web: build: . container_name: dz01 command: bash -c 'python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate && gunicorn oqtor.wsgi -b 0.0.0.0:8000' depends_on: - db volumes: - ./src:/src - /static:/static expose: - "8000" links: - redis ... ... Dockerfile : FROM python:latest ENV PYTHONUNBUFFERED 1 #ENV C_FORCE_ROOT … -
Get preferred language of a user in a Django managment command
I am using Djangos management commands to send user notification emails, which I would like to send them in their preferred language. I guess I will have to store the preferred language in their profile. Or is there any other way how I could avoid that? I don't want to add a "select your language" option in the user profile, but instead use the latest language the user was browsing the website with. What would be the way to update his language setting? -
Call webhook at specific times for millions of events
Suppose you are designing a birthday app that will send an email to users on the exact date and time of their birthday. Suppose also that there is webhook that will handle the delivery of the email. In this system, birthday emails can be scheduled months in advance and the system must be able to support millions of users. This is a reasonable approximation of the problem I'm trying to solve, except with the events happening much more frequently than once a year for each user. What I'd like to do is schedule a webhook call when a user enters their birthday. Is there a particular technology or service that does this? We have a Django app on AWS. I looked into SQS and SNS, but these don't seem to be the right tools for the job. -
Django - Models Class Shopping Cart Issue
Working on a dashboard done in Django. The Product class has multiple orders and each order can sell more than one product (for example: order 1 can have 2 tacos (product)) Trying to count the top selling by getting the aggregate number of products sold for all orders. What is the best way to do this? Create a dictionary? class Product(models.Model): name = models.CharField(max_length=200) # Name of the product or dish. (e.g. chicken alfredo) price = models.FloatField(default=0) # Price of the product (e.g. $10) quantity = models.IntegerField(default=0) # Number of chicken alfredos the customer ordered sku = models.CharField(max_length=20) # SKU of the chicken alfredo dish. customer_order = models.ForeignKey(CustomerOrder) # Foreign key linking one-to-many from order-has-many-products created_at = models.DateTimeField(auto_now_add=True) # When the order entry was saved into database updated_at = models.DateTimeField(auto_now=True) # When the order was last updated in database def str(self): return self.name + " $" + self.price -
Django URL Conf/Reverse Lookup: Introducing new kwarg to left side of url
I am trying to introduce a new kwarg to the front/left of a set of namespaced urls in django. Basically I want to go from this: domain.com/products/kwarg1/kwarg2/etc to this: domain.com/kwarg0/products/kwarg1/kwarg2/etc Thanks to django's urlconf and namespacing, actually changing the urls is easy. However, I am working on a codebase that has a significant number of reverse() url lookups. Ex: url = reverse('product:category', kwargs={'kwarg1': self.get_full_path(ancestors), 'kwarg2': self.id}) Does anyone know if there is a canonical way of introducing kwarg0 into my urls without finding every single reverse() url lookup and inserting an appropriate argument for kwarg0?