Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin keeps returning 504 timeout ( nginx +uWSGI )
This is my nginx configuration: server { listen 80; listen [::]:80; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name www.nameOfSite.id nameOfSite.id; access_log off; error_log /var/www/log_nginx/error.log; gzip on; gzip_disable "msie6"; client_header_timeout 180s; client_body_timeout 180s; client_max_body_size 100m; proxy_connect_timeout 120s; proxy_send_timeout 180s; proxy_read_timeout 180s; send_timeout 600s; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; location /static { alias /var/www/django/static; } location /media { alias /var/www/django/media; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; include uwsgi_params; uwsgi_read_timeout 500; uwsgi_send_timeout 500; uwsgi_pass unix:/var/www/uwsgi_texas.sock; } } This is my uWSGI ini file in /var/www/texas_uwsgi.ini: [uwsgi] socket = /var/www/uwsgi_texas.sock chdir = /var/www/django/ wsgi-file = /var/www/django/django/wsgi.py processes = 8 threads = 1 master = true harakiri = 900 chmod-socket = 777 vacuum = true This is my service file in /etc/systemd/system/texas.service: [Unit] Description=TEXAS After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --ini /var/www/texas_uwsgi.ini Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=main [Install] WantedBy=multi-user.target The problem is when i enter the Django admin for one Model object that have a lot of inline objects and fields, it keeps returning 504 timeout because it takes more than 60 seconds to process. I checked my NGINX, uWSGI configurations, i cannot find the solution on how to … -
pip wont install anything getting numerous erros etc
So I have python 2.7 have pip installed pip is upgraded cant install anything i get all kinds of errors and have tried all kinds of solutions. why do i have to type: C:\Users\kingj>python -m pip install instead of pip install without getting: C:\Users\kingj>pip install 'pip' is not recognized as an internal or external command, operable program or batch file. everyone else seems to just type pip install etc... i have to do python -m pip install then when i do do it like that i get this:C:\Users\kingj>python -m pip install django-json Collecting django-json Could not fetch URL https://pypi.python.org/simple/django-json/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) - skipping Could not find a version that satisfies the requirement django-json (from versions: ) No matching distribution found for django-json even though i have tried multiple packages by name and i get only that message?! -
Django - Building a comment system, should I use formsets?
I'm building the comment section of a Q&A page, where users can either leave full replies or just comments (identical to Stack Overflow's system). There is a 'Add Comment' attached to every entry on the page. I read up on formsets and from my understanding so far, formsets don't seem to be the optimal solution for this problem. I believe the best way of building this system is to add a comment_form in each entry. {% for a in answers %} {{ a }} <form method="post"> {{ comment_form }} </form> {% endfor %} Should I use formsets? Or use the method I wrote above? -
moved app to another app dropped tables can't migrate in Django
As the title says I moved some models from an existing app into another app. Then I deleted the old app ran DROP TABLE for all old app tables prepended with oldapp_model... and ran makemigrations on an existing database. It says there are no migrations to apply and when hitting the newer migrations it says there is: no relation newapp_model How can I get it to pick this up and create the new model in the new app? -
creating expiry in django cause received a naive datetime
In my Django app, I have in my model set for expiry this way: expiry = models.DateTimeField(default=datetime.now()+timedelta(days=5)) And when i did makemigration and migrate Applying ../lib/python3.6/site-packages/django/db/models/fields/__init__.py:1451: RuntimeWarning: DateTimeField AuthEmployeeSessionToken.expiry received a naive datetime (2017-12-09 00:03:20.106930) while time zone support is active. RuntimeWarning) ../lib/python3.6/site-packages/django/db/models/fields/__init__.py:1451: RuntimeWarning: DateTimeField AuthEmployeeSessionToken.expiry received a naive datetime (2017-12-09 03:11:20.274318) while time zone support is active. RuntimeWarning) OK what would be the right way to solve this problem ? I saw like timezone.now(), is that right since Im using DateTime field ? Would like a definite way of setting expiry in the model automatically when created. -
Perform update query after delete in django cbv
I'm trying to update other table after successful delete of of data. Below is my views.py class AttendeeDeleteView(DeleteView): model = Attendee success_url = reverse_lazy('index') def get_form_kwargs(self): id = self.kwargs['id'] # get value of enr Payment.objects.filter(pk=id).update(registered=0) In my urls.py url(r'^delete/(?P<pk>\d+)$', AttendeeDeleteView.as_view(template_name="includes/attendee_delete.html"), name='attendee_delete',), My Current code successfully delete the item but failed to update the other table. -
cookiecutter-django docker-compose local ERROR: yaml.scanner.ScannerError
From following the instructions from the docs to build docker locally here: https://cookiecutter-django.readthedocs.io/en/latest/developing-locally-docker.html#build-the-stack $ docker-compose -f local.yml build give the following error: mmooring@C02V61LSHTDD ~/Documents/MDM/projects/MDM-Projects/cookiecutter-django/{{cookiecutter.project_slug}} [21:18:48] > $ docker-compose -f local.yml build [±master ●●▴] ERROR: yaml.scanner.ScannerError: mapping values are not allowed here in "./local.yml", line 9, column 10 I'm running on Docker 17.09.0-ce-mac35 (19611) -
I'm customizing django forms using widget tweaks, but keep getting ModuleNotFoundError: No module named 'widget_tweaks'
I am trying to use django widget tweaks for an app I'm building with a group and I keep getting an error: ModuleNotFoundError: No module named 'widget_tweaks' I don't understand why. I installed the module on my mac with $ pip install django-widget-tweaks and placed 'widget_tweaks' in the INSTALLED_APPS = [...] part of my apps settings.py file. Those were the only 2 things I saw that I needed to do after reading the documentation for how to use widget tweaks. Please help. -
Gcloud app deploy not working
After upgrading my gcloud components using gcloud components update My gcloud app stopped deploying using gcloud app deploy The error log is always about timing out. Please help. Thanks note: it's a Django app -
show category and sub-categories in hierarchy
I am using django-mptt for category model. I want to show a list of categories and sub-categories as in the screenshot. The way I could show is all the list without any structure like below BEDROOM ITEMS ALMIRAH 2 PIECE ALMIRAH 3 PIECE ALMIRAH BED DOUBLE SIZE LOW BED QUEEN SIZE LOW BED This way its hard to know which one is parent category and which one is child category and grand-child category etc. I could either show the above way or show only the parent category using Category.objects.root_nodes() here is my model, views and template class Category(MPTTModel): name = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(null=True, blank=True, upload_to=upload_furniture_image_path) slug = models.SlugField(max_length=200, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) def furniture(request, slug): instance = get_object_or_404(Furniture, slug = slug) cart_obj, new_obj = Cart.objects.new_or_get(request) categories = Category.objects.all() context = { 'furniture': instance, 'cart': cart_obj, 'categories': categories } return render(request, 'furnitures/furniture.html', context) <div class="panel-body"> <ul class="nav nav-pills nav-stacked category-menu"> {% for category in categories %} <li>{{category.name}}</li> {% endfor %} </ul> </div> So my question is how could I separate Parent Category and child category so I can show as in screenshot? -
How do I fix this error in Python Django involving request.user.is_authenticated() and bool object not callable?
I am trying to make profile pages for each user. I added a code that checks if the user is logged in and does a redirect (see line 12 of the code below). from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect, HttpResponse from .models import Account, ForSale, WTB from mysite.forms import MyRegistrationForm def signup(request): if request.user.is_authenticated(): return HttpResponseRedirect('/user/') else: if request.method == 'POST': form = MyRegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/user/') context = {} context.update(csrf(request)) context['form'] = MyRegistrationForm() return render(request, 'signup.html', context) def index(request): return render(request, 'index.html') However, upon accessing /signup/ on the site I get the following debug message: -
how to pass extra field for mutation? django-graphene
I am learning to use django-graphene for graphql purpose. I learned through a few tutorials and got some ideas on how to work and made them work. I got mutation to work for create and update BUT that's only if using all available fields that already exists in models. I am wondering what IF I am passing in fields that's not included in a model. For example, if there is a token to be passed for authentication purpose or whichever fields need to be passed. I have these codes class ProductType(DjangoObjectType): class Meta: model = Product filter_fields = {'description': ['icontains']} interfaces = (graphene.relay.Node,) class ProductInput(graphene.InputObjectType): token = graphene.String() # this would be some token to check for authentication title = graphene.String() barcode = graphene.String(required=True) class CreateProduct(graphene.Mutation): class Arguments: product_input = ProductInput() # form_errors = graphene.String() product = graphene.Field(ProductType) def mutate(self, info, product_input=None): if product_input.get('token'): # do something here pass product = Product.objects.create(barcode=product_input.barcode, title=product_input.title) return CreateProduct(product=product) class ProductMutation(graphene.ObjectType): create_product = CreateProduct.Field() I have my query for graphql as mutation ProductMutation { createProduct(productInput:{token:"sometoken", title:"hello", barcode:"codes"}){ product{ id, title, barcode } } } which of course doesn't work that's why I am wondering if anyone can give me a hand. Thanks in advance -
Django error creating object with many to many field
There are a few questions already mentioning this error but I couldn't find an answer in any of them. File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/rest_framework/serializers.py", line 214, in save self.instance = self.create(validated_data) File "/home/joao/Code/projects/courty/courty-django/apps/matching/serializers.py", line 19, in create return MatchFinder.objects.create(**validated_data) File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/query.py", line 392, in create obj = self.model(**kwargs) File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/base.py", line 568, in __init__ _setattr(self, prop, kwargs[prop]) File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__ manager = self.__get__(instance) File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__ return self.related_manager_cls(instance) File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__ (instance, self.pk_field_names[self.source_field_name])) ValueError: "<MatchFinder: MatchFinder object>" needs to have a value for field "id" before this many-to-many relationship can be used. Model class MatchFinder(models.Model): player = models.ForeignKey(Player) start_datetime = models.DateTimeField(null=False) venues = models.ManyToManyField(Venue, help_text='Pitches preferred by this player', blank=True) View class MatchFinderView(views.APIView): def post(self, request, format=None): serializer = MatchFinderSerialzer(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) Serializer class MatchFinderSerialzer(BaseModelSerializer): class Meta: model = MatchFinder fields = ('start_datetime', 'venues') def create(self, validated_data): return MatchFinder.objects.create(**validated_data) Request c = Client() data = { 'start_datetime': now, } response = c.post('/matches/findmatch/', data) Passing a list of 2 Venue objects in the venues on the post request results in the same error. -
Django modelformset_factory deleting objects
Hello I have got question I have made modelformset_factory and in options I have choosen can_delete = True and now I don't know how to delete marked objects as 'DELETE' : True to delete them from database. I was trying to do this in some ways and it didnt work. I was looking for it also in django formsetmodels documentation but this didnt help me. With this option can_delete = True I get additional checkbox in my html page Delete and marking him only prints me in console on print: {'username': 'sw', 'email': 'a@gmail.com', 'city': 'ss', 'code': 12345, 'id': , 'DELETE': False} Saving forms to database is working but I dont know how to delete marked forms from database. I would be very thankful for every help. I have made modelformset_factory from model in models.py class TestModel(models.Model): username = models.CharField(max_length=120) email = models.EmailField() city = models.CharField(max_length=120) code = models.IntegerField() #W admin panelu za miast TestModel object bedzie username def __str__(self): return self.username Then I have added in my views.py function: def django_modelformset(request): TestModelFormset = modelformset_factory(TestModel, fields=['username', 'email', "city", "code"], extra=1, can_delete=True) formset = TestModelFormset(request.POST or None) if formset.is_valid(): for form in formset: print(form) print(form.cleaned_data) form.save() context = {"formset": formset} return … -
AttributeError: 'float' object has no attribute '_values'
Tring to run chatbot based on seq2seq github repo: https://github.com/Conchylicultor/DeepQA after executing main.py getting this error. (main.py trains the model on given corpus) S-MBP:joey fdf$ python3 main.py /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.7 return f(*args, **kwds) Welcome to DeepQA v0.1 ! TensorFlow detected: v1.4.0 Loading dataset from /Users/fdf/Desktop/joey/data/samples/... Loaded cornell: 34988 words, 139979 QA Model creation... Traceback (most recent call last): File "main.py", line 29, in <module> chatbot.main() File "/Users/fdf/Desktop/joey/chatbot/chatbot.py", line 166, in main self.model = Model(self.args, self.textData) File "/Users/fdf/Desktop/joey/chatbot/model.py", line 103, in __init__ self.buildNetwork() File "/Users/fdf/Desktop/joey/chatbot/model.py", line 144, in buildNetwork encoDecoCell = tf.nn.rnn_cell.DropoutWrapper(encoDecoCell, input_keep_prob=1. 0, output_keep_prob=0.5) # TODO: Custom values File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/ops/rnn_cell_impl.py", line 769, in __init__ tensor_prob, const_prob = tensor_and_const_value(prob) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/ops/rnn_cell_impl.py", line 763, in tensor_and_const_value tensor_value = ops.convert_to_tensor(v) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 836, in convert_to_tensor as_ref=False) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 926, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 229, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 208, in constant value, dtype=dtype, shape=shape, verify_shape=verify_shape)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py", line 483, in make_tensor_proto append_fn(tensor_proto, proto_values) File "tensorflow/python/framework/fast_tensor_util.pyx", line 15, in tensorflow.python.framework.fast_tensor_util.AppendFloat32ArrayToTensorProto File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/google/protobuf/internal/containers.py", line 251, in append self._values.append(self._type_checker.CheckValue(value)) AttributeError: 'float' object has no attribute '_values' -
How can I send invitation email using django allauth
I know how to email verification using Django-allauth. But I want to send invite email to users using Django-allauth. I think there is a easy way to do this using Django-allauth. Can anyone help me with this? -
django 3.6.3 runs in Windows development but hangs in Linux production
python 3.3.6 django 1.11 I am lost, I am working on what I think is a fairly simple first django site. I am doing development on a windows machine. I deploy to a Linux machine. Both are running python 3.6.3. The local/windows version can be run with the built-in server. When I deploy the site to the production machine thought I get an unhelpful message: Web application could not be started An error occurred while starting the web application: it did not write a startup response in time. Please read this article for more information about this problem. Raw process output: (empty) I've done some googling about debugging in production but since my code is not actually throwing an exception nothing is caught and here I sit. I have put diagnostic print statements in my vires.py and apps.py files. They do not drop anything in either the access.log or error.log. I'm open to ideas here. Again, the app seems to work on the dev PC but gives the Web application could not be started error in Linux production. -
Render the fields dynamically based on user group type of django forms
Working with Django users and group and I need to display the form fields based on user group type. There are two types of users. 1. Writer 2. Editor The writer will write an article and submit for a review to the editors. The user type is separated using group. If the user is in the Editors display the approved form field which if the user is not in the Editors group hide the approved form field. class Article(models.Model): choices = (("review", "Review")) title = models.CharField("Article title", max_length=200) body = models.TextField() writer = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField( max_length=20, choices=( ('reivew', 'review'), ('published', 'published') ) ) def get_absolute_url(self): reverse('article-detail', kwargs={ "pk": self.id }) views.py class ArticleCreate(CreateView): model = Article # Don't need to define inside meta class fields = ("title", "body") # Override the form_valid method to populate your data. def form_valid(self, form): form.instance.writer = self.request.user form.instance.status = "published" return super(ArticleCreate, self).form_valid(form) # Don't need success url # get_absolute_url is already defined in model Q. Where to write a logic to hide and display the status field based on user group type if u.groups.filter(name="Editors").exists(): #display status field else: # hide status field. I know I could do thisn using django … -
Django Query Group with Calculations
I am wondering if it is possible to do more advanced calculations in a query? Here I am getting the data fine and want to add the profit which is the Sum(credit) - Sum(debit). my error: Cannot compute Sum('credit'): 'credit' is an aggregate trd = Trades.objects.all ().filter ( acct_id = acct.id ) .values ( 'issue' ) .annotate ( cnt = Count ( 'issue' ), debit = Sum ( 'debit' ), credit = Sum ( 'credit' ), shrs = Sum ( 'shares' ), profit = Sum ( 'credit' ) - Sum ( 'debit' ) ) .order_by ( 'issue' ) Thanks. -
Filtering queryset by number of many-to-one relationships with a raw SQL query
I am creating a resources page, and I have the following models: class Tag(models.Model): title = models.CharField(max_length=50, blank=False, unique=True, error_messages={'unique':"THis tag already exists."}) class Link(models.Model): title = models.CharField(max_length=100, blank=False) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=False, blank=False) Which have more fields but they are irrelevant to this matter. The problem with this resources page was that Tags with no Link establishing relationship with them were still appearing, and I wanted only for tags with at least one Link under them to appear. Now, I have managed to do this with this queryset filtering: tags = Tag.objects.all().filter(link__isnull=False).order_by("title").distinct() Which works alright in my views.py, and what I want is done already. Note that the "distinct" is necessary so that it doesn't return duplicate queries. I have had very little experience with MySQL and only have built very simple applications with it and PHP. I have now idea how it would function under SQLite, nor would I even know how to this with MySQL. Under my (very informal) logic, it would function something like this (please, forgive my killing the language): SELECT * FROM Tags WHERE NUMBER_OF_RELATIONSHIPS IS GREATER THAN 1 My question is actually how could this be achieved through a Raw SQL query, … -
Filtering queryset by number of many to one relationships
I'm creating a resources page, and there are a few Tags with foreign key relationships to Links. These are my models (having left out irrelevant, to this issue, parts of the code): class Tag(models.Model): title = models.CharField(max_length=50, blank=False, unique=True, error_messages={'unique':"Esta tag já existe."}) class Link(models.Model): title = models.CharField(max_length=100, blank=False) url = models.URLField(blank=False) language = models.CharField(max_length=10, blank=False) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=False, blank=False) There is a page with several links, which appear under the tags. The problem is, if the tags have no links related to them, they will still appear. I believe the solution for this is to leave out of the queryset the tags with no relationships. I believe there is one way through this, which is the following logic: SELECT * FROM Tag WHERE NUMBER OF RELATIONSHIPS IS GREATER THAN OR EQUAL TO 1 And this would be done through a Raw SQL query, I believe, but I don't know that much SQL. Maybe that is also possible through filtering? How could I proceed to do this? -
Django Error: 'myproject.wsgi.application' could not be loaded
I'm currently trying to test my Django application, which will eventually be deployed to Heroku. When testing locally, I'm running into the error: django.core.exceptions.ImproperlyConfigured: WSGI application 'foodForThought.wsgi.application' could not be loaded; Error importing module. My wgsi.py file is configured as: import os import signal import sys import traceback import time from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foodForThought.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) and my settings.py file is configured as: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... # Application definition INSTALLED_APPS = [ 'recipe.apps.RecipeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'foodForThought' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'foodForThought.urls' ... WSGI_APPLICATION = 'foodForThought.wsgi.application' ... I'm currently using Django 1.11.7 and testing in a venv. What's causing this issue to occur? -
Calculate a form field in Django based on another field
I have this scenario: a customer wants to know the equivalent of a sum in his local currency. He fills a form (ModelForm) where he indicates the amount and the country and I need to calculate the equivalent amount in local currency. I created : 1- A model with the countries and their currency exchanges 2- A model with the initial amount in dollars, the country of exchange(ForeignKey from the first model) and the equivalent amount in local currency 3- A form (Modelform) from the second model 4- A function that takes the initial amount and the country and calculates the equivalent amount in local currency My question is: how can I update the local amount field of the form and save it in the database based on the first 2 fields of the form? I tried this: if form.is_valid(): conversion = form.save(commit=False) conversion.converted_amount=calculate(conversion.initial_amount,conversion.country) conversion.save() but I got this error: invalid literal for int() with base 10: 'India' What am I missing? Thanks in advance -
Django search or filter depending on the url
I have a site with Django which contains multiple blogs. I am trying to make filters by categories from the menu depending on the url: If I'm in the home - get all the entries of a category that belong to any blog. url example: www.site.com/category_path/ If I'm in a blog - get all the entries of a category that belong to the current blog. url example: www.site.com/blog_slug/category_path/ I can solve this by changing the urls I call in the menu. Example: <a href="{% url 'blogosphere:categories:detail' category_path='music' %}">Music</a> Example: <a href="{% url 'blogosphere:blogs:categories:detail' blog_slug=blog.slug category_path='music' %}">Music</a> But I would like to see if there is a more elegant way to do it. Thank! PD: I want to solve this for the search also. -
Using Django in a multithreading code
I am running a python script using django ORM to handle calls to the database. I have the following code: with ThreadPoolExecutor(max_workers=2) as executor: executor.submit(process, 2) executor.submit(process, 1) @transaction.atomic def process(counter) MyModel.objects.filter(user_id=counter).delete() users = <create User object) MyModel.objects.bulk_create(users) I am using django default behavior which sets the auto-commit to True. When I debug the code, it looks that django uses the same connection among the application, and therefore, the last process that will exit process method, will commit all the transactions that are using the connection. How can I prevent it to happen? I would like django to close (and commit) the connection at the end of each method so each thread could be handled separately.