Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use d3.queue() to load .tsvs when working within Django
I am trying to convert my old website to use Django. However, I don't know how to successfully load my data in d3 when working inside of Django frameworks. I know the D3 visualization works because it renders it on the old website frameworks. It appears to just be an issue of how do I properly call the pathing for the data files. I have tried various call methods to the files by making duplicate copies and placing them in different directories. But so far I can't figure out how to call the paths correct! Here is the original set of code: queue() .defer(d3.json, "../core/world_countries.json") .defer(d3.tsv, "worldData.tsv") .await(ready); Here are two different method calls I have tried queue() .defer(d3.json, "world_countries.json") .defer(d3.tsv, "{% static 'data/worldData.tsv' %}") .await(ready) 2 different errors occur: GET http://127.0.0.1:8000/web_app/world_countries.json 404 (Not Found) GET http://127.0.0.1:8000/web_app/%7B%%20static%20'data/worldData.tsv'%20%%7D 404 (Not Found) -
How to provide "add" option to a field in django admin?
In django admin i had one model named 'student', here it has three fields, NAME, ROLL NO. & SUBJECT. in models.py: from django.db import models class Student(models.Model): Name = models.CharField(max_length=255, blank = False) Roll_No = models.CharField(max_length=10, blank = False) Subject = models.CharField(max_length=20, blank = False) def __str__(self): return self.Name now i want this SUBJECT field to be Dynamic, like there will be "+" sign besides the SUBJECT field, by clicking that one more SUBJECT field will be added right after it and so on, but maximum 10 SUBJECT fields can be added like that. -
Will Xprinter - Xp-n160 || 80 mm OR Gprinter GP58L/UBL be compatible with my software in order to print the bill?
I have a billing web application that is built in React Js for front end and Django for backend (Django rest framework).I am setting up a new server, and want to support thermal POS printing in my web application. I want the application to print either from browser(Desktop) or browsers from mobile device. I have mentioned currently available printers. If these are not compatible, please suggest a compatible thermal printer. -
How send URL as response whenever user send post value in django rest framework?
Guys i want to return a URL of HTML page as response , when ever user send value by post method Actually the HTML page will contains data posted by user, But what actually happening is when user post data it opening that HTML page , code i tried class CoordView(viewsets.ModelViewSet): queryset = Coord.objects.all() renderer_classes = (TemplateHTMLRenderer,) serializer_class = CoordSerializer template_name = 'index.html' id = {'id':id } Response ('http://127.0.0.1:8000/detail/{{id}}') But I want to return that HTML page URL to user. -
Simple wagtail streamfield template not working
Its my template code: {% for post in page.get_children %} ONE {{ post.title }} <--- it shows correct, excepted title {% for block in post.body %} TWO <--- this is NEVER showen {% endfor %} {% endfor %} Its my BlogIndexPage: class BlogIndexPage(Page): body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] Its my BlogPage: class BlogPage(Page): date = models.DateField(auto_now=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), StreamFieldPanel('body'), ] I just cannot access to the block propeties, because post.body fells like empty array (I added BlogPage as child of BlogIndexPage, and I filled StreamField with some text, headings and pictures - it isn't empty) I am sure i am missing somehting obvious but I cannot see it myself. -
Django save object to db if condition met
I'm trying to use django pre_save signal to write the instance into db if a specific condition is met. How can I achieve this ? I'm having a function handler which is called by pre_save and I want to drop saving the instance if a condition is not met. I want to abort the whole save chain. Is it pre_save signal the proper way to do this ? -
Is it possible to save html2canvas image on page load automatically to directory without clicking a download button?
Guy i want to download html2canvas captured image automatically without pressing a download button manually , how to do ??? -
Where do I start
I am currently working as a Electrical Engineer for a mining company out of West Virginia. I have been given the task of creating a program that will do the following. Web Based User accounts and login Have a interactive mine map that allows objects to be placed on it and the map would be broke down into zones. The objects would be placed in these zones. They frequently move equipment from zone to zone. On this map we would be able to use a click and drag method to move the objects from one zone to the other. The objects should also be right clicked and show a menu that allows additional options such as electrical and hydraulic prints. These files are available in PDF. Finally, assign each member to a zone and have them complete the weekly exams on that equipment. A list will be available on their home page of what they are assigned. Using available sources, I have been able to create a basic web based application and a login server with python and Django. As far as everything else I don't know where to start. I spend more time searching for hours in one direction … -
How to get URL after form post request inside view.py function to use it in if else
I need to get current URL of the form post request and based on page URL return the corresponding template part In a views.py I just doubled the same function twice with a new name and it works but for the future when I have 5 or more URLs it will become a dirty code I have a two dirs / the main /dir/ the second and plan to add up to 10 new dirs I tried this, it works, but a lot of repetitive code #views.py def func_name(request): global context form = Form(request.POST or None) return render(request, 'home.html', context) def func_name_dir(request): global context form = Form(request.POST or None) return render(request, 'home.html', context) #urls.py urlpatterns = [ path('', func_name), path('ru/', func_name_dir), ] #I just want to use something like this to return right template #views.py def func_name(request): global context form = Form(request.POST or None) if url == '/dir/': return render(request, 'home-dir.html', context) elif url == '/dir1/': return render(request, 'home-dir1.html', context) else: return render(request, 'home.html', context) How to do this? -
Cannot add tags to frontend views Django queryset
I'm trying to add tags to my view from a query set column that looks like this for one observation like synonyms for great: ['fun, cool, awesome'] When I try to display as separated tags, it just prints as one block: 'fun, cool, awesome' This is what views.py looks like passing this data: class SynDetailView(generic.DetailView): model = Syn template_name = "synonoms/syn_detail.html" def get_context_data(self, **kwargs): context = super(SynDetailView, self).get_context_data(**kwargs) tags = Syn.objects.filter('synid'=self.kwargs.get('pk')).values_list('tags', flat=True) tags = str(tags) context['tags'] = [x.strip() for x in tags.split(',')] return context -
How can django channels communicate to other microservices?
We are developing microservices and communicating between them over rabbitmq. We would like to add a django app to the mix and currently are looking for elegant solutions. I have taken a look at django channels. While they are able to communicate over rabbitmq, I haven't found mentioning on how to send messages to specific exchange (and preferably with specific routing key as we are mostly using topic exchanges). asgi-rabbitmq seems to be the one translating between asgi (protocol used by channels) and amqp (protocol used by rabbitmq). From the docs, however, I only understood how to enable it - not how to actually use it to publish messages. Have I missed something? -
How to pass positional arguments to form submission on testing?
I have a signupView that shows 2 forms: SignUpForm and ProfileForm. Basically, SignUpForm collects data like first_name, last_name, user_name, email, password1, password2. And ProfileForm collects data like dni, birthdate, shipping_address, etc. ProfileForm also display 3 pre-populated fields that are list of options, this list of options depend on eachother and I make this work with AJAX. The fields are: department_list, province_list and district_list. The form collects the data collects, but I cannot replicate this behaviour with pre-defined values for these fields on my test. Test error: Says that the hardcoded values are not valid options. <ul class="errorlist"><li>shipping_province<ul class="errorlist"><li>Escoja una opción válida. Huánuco no es una de las opciones disponibles.</li></ul></li><li>shipping_district<ul class="errorlist"><li>Escoja una opción válida. Yacus no es una de las opciones disponibles.</li></ul></li></ul> test_forms.py def test_profile_form(self): call_command('ubigeo_peru') peru = Peru.objects.all() department_list = set() province_list = set() district_list = set() for p in peru: department_list.add(p.departamento) department_list = list(department_list) print("## DEPARTMENT LIST ###") print(type(department_list[0])) print(department_list[0]) if len(department_list): province_list = set(Peru.objects.filter(departamento=department_list[0]).values_list("provincia", flat=True)) province_list = list(province_list) print("### PROVINCE LIST ###") print(type(province_list[0])) print(province_list[0]) else: province_list = set() if len(province_list): district_list = set( Peru.objects.filter(departamento=department_list[0], provincia=province_list[0]).values_list("distrito", flat=True)) else: district_list = set() form_data = {'user': self.user, 'dni': 454545, 'phone_number': 96959495, 'birthdate': datetime.datetime.now(), 'shipping_address1': 'Urb. Los Leones', 'shipping_address2': 'Colegio X', 'shipping_department': … -
Adding an extra field and value to a django queryset's objects
Let the following Model: class Books(models.Model): b_name = models.CharField(max_length=10) b_page = models.IntegerField() What I want is to add an extra field with different values based on the logged user in the views and then render it to the templates, so that I can use it like following: {% for b in books_qs %} {{b.extra_field}} {% endfor %} May be in views like this: qs = Books.objects.filter(...) for q in qs: some_values = random_value_with_logged_user: q.add("some_field", random_value_with_logged_user) And because the values should be random and depending on user, so I can't use a model field for this task. So please help me with some solution. Please HELP!!!! -
How to fix "the model is used as in intermediate model but it does not have foreign key to a model"?
Error Message: blogs.Permission: (fields.E336) The model is used as an intermediate model by 'blogs.Category.permission', but it does not have a foreign key to 'Category' or 'Permission'. I have tried to add a Foreign Key to 'Category' under Permission model, same error still occurs. models.py: from django.db import models class Category(models.Model): name = models.CharField(max_length=50) permission = models.ManyToManyField('Permission', related_name='category_permissions', through='Permission' ) def __str__(self): return self.name class Permission(models.Model): HIGH = 'High' MEDIUM = 'Medium' LOW = 'Low' CLASSIFICATION_CHOICES = [ (HIGH, 'High'), (MEDIUM, 'Medium'), (LOW, 'Low') ] category_name = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_name') name = models.CharField(max_length=100) description = models.TextField() platform = models.CharField( max_length=10, choices=PLATFORM_CHOICES, default=BOTH, ) classification = models.CharField( max_length=10, choices=CLASSIFICATION_CHOICES, default=LOW, ) def __str__(self): return self.name class MobileApp(models.Model): name = models.CharField(max_length=200) icon = models.ImageField(upload_to='app_icons', blank=True, null=True) platform = models.CharField( max_length=10, choices=PLATFORM_CHOICES, default=IOS, ) category = models.ManyToManyField('Category') provider = models.CharField(max_length=200) identifier = models.CharField(max_length=200) permission = models.ManyToManyField(Permission, related_name='mobile_app_permission', ) def __str__(self): return self.name I am trying to use 'through' argument to include the description field of the permission m2m for MobileApp and Category -
Django get_total_topup() missing 1 required positional argument: 'request'
class IndexAjaxView(View): def get(self, request): param = request.GET.get('param') if param == 'get_total_topup': return self.get_total_topup() return JSONResponse({}, status=404) def get_total_topup(self, request): return JSONResponse({ 'value': 'Rp.{:,.0f},-'.format( TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum'] ) }) somebody can help me ? I want to get data via ajax, but the response is 500 with message get_total_topup() missing 1 required positional argument: 'request' -
I'm trying to implement blog app with django.In homepage of app there will be list of posts alongside i need show there profile picture?
I'm trying to implement blog app with django.In homepage of app there will be list of posts alongside i need show there profile picture.I don't know how to approach? models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title=models.CharField(max_length=100) desc=models.TextField() date=models.DateField(auto_now=True) author=models.ForeignKey(settings.AUTH_USER_MODEL, to_field="username",on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='pics') <!----Post------> {% for post in posts %} <div class="list"> <div class="con"> <div class='logo2'> {% for img in img %} <img src='' > {% endfor %} </div> <h3 style="color:DodgerBlue;">{{post.author}}</h3> <h6 style="font-family: montserrat,sans-serif;"> {{post.date}} </h6> <div class="line"></div> <a href="{% url 'post_detail' pk=post.pk %}"><h1><b> {{post.title}}</b></h1></a> <div style="font-size: 17px;"> <p>{{post.desc}}</p> </div> </div> </div> {% endfor %} I need to show profile picture of user corresponding to thier post.I tried but i didn't got. -
Invalid block tag on line 10: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag?
I am using Django 2.2, chrome and this is a snippet from the Web Browser's error page. Error during template rendering In template D:\Django Projects\mysite\blog\templates\registration\login.html, error at line 10 Invalid block tag on line 10: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag? 1 {% extends 'blog/base.html' %} 2 {% block content %} 3 <div class="jumbotron"> 4 <h1>Please Login:</h1> 5 {% if form.errors %} 6 <h3>Username or Password mismatch. Try again!</h3> 7 {% endif %} 8 <form action="{% url 'login' %}" method="POST" > 9 {% csrf_token %} 10 {% form.as_p %} 11 12 <input type="submit" class="btn btn-primary " value="Login"> 13 <input type="hidden" name="next" value="{{ next }}"> 14 </form> 15 </div> 16 {% endblock %} My project's url.py looks something like this from django.contrib import admin from django.urls import path,include from django.contrib.auth.views import LoginView,LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls')), path('accounts/login',LoginView.as_view(), name='login'), path('accounts/logout',LogoutView.as_view(), name='logout',kwargs={'next_page':'/'}), ] Why am I not able to go to login page? -
DRF end-point posting error for nested serialization
Get method working in browse-able api end-point but when i try to post using my end-point through browser, it fires me this error: (My serializers are nested) This is my serializers.py and it is Nested serilizers from rest_framework import serializers from . models import Author, Article, Category, Organization class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = '__all__' class AuthorSerializer(serializers.ModelSerializer): organization = OrganizationSerializer() class Meta: model = Author fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer() category = CategorySerializer() class Meta: model = Article fields = '__all__' and this is my models.py from django.db import models import uuid class Organization(models.Model): organization_name = models.CharField(max_length=50) contact = models.CharField(max_length=12, unique=True) def __str__(self): return self.organization_name class Author(models.Model): name = models.CharField(max_length=40) detail = models.TextField() organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and this is my views.py ( I am using APIView, not VIewset) class ArticleDeleteUpdate(DestroyAPIView, UpdateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'alias' and this is my urls.py path('api/v1/article', views.ArticleListCreateGet.as_view(), name='article2'), … -
Django save() method not saving to DB
What am I doing wrong? I have two tables, User and Entrepreneur. Objects are not saving in the Entrepreneur table. I even used the shell! I've deleted the DB and migration files and the error stays the same. I know similar questions have been asked but I found none fitting my situation. MY MODELS: class EntrepreneurProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=100, blank=True, null=True) location = CountryField(blank=True, null=True) email_notif_on = models.BooleanField(default=False) photo = models.ImageField(upload_to='photo/%Y/%m/%d', blank=True, null=True) skills = TaggableManager(blank=True) date_joined = models.DateField(auto_now_add=True) accomplishnment = models.ForeignKey(Accomplishment, on_delete=models.CASCADE, null=True, blank=True) portfolio = models.ManyToManyField(Portfolio, blank=True) date_of_birth = models.DateField(blank=True, null=True) url = models.SlugField(unique=True) def __str__(self): return f'{self.user}' def save(self, *args, **kwargs): if self.url: self.url = slugify(f'{self.user.first_name} {self.user.last_name} {str(uuid.uuid4()[:7])}') MY VIEWS: def signup(request): if request.method == 'POST': user_form = UserCreateForm(request.POST) if user_form.is_valid(): user = user_form.save(commit=False) user.set_password(user.password) user.save() entrep = EntrepreneurProfile.objects.create(user=user) entrep.save() print(entrep.id) return redirect('users:login') else: user_form = UserCreateForm() data = {'user_form': user_form} return render(request, 'users/signup.html', data) -
How to encrypt and store data into a database using django and pycrpytodome?
I created a database using django and created a html form to store the data into the database. Now, I want to encrypt using pycryptodome and store the ciphertext into the database. And I want the decrypted plaintext when I display the data from the database. I have tries some basic encryption examples and algorithms from pycrytodome documentation. Now, I want to encrypt and store the ciphertext into the database. #This is the function where I want to encrypt the data in the get_password variable and store it def add(request): get_name = request.POST["add_name"] get_password = request.POST["add_password"] print(type(get_name),type(get_password)) s = Student(student_name=get_name,student_password=get_password) context = { "astudent":s } s.save() return render(request,"sms_2/add.html",context) #This is the example I have tried from pycryptodome documentation. from Crypto.Cipher import AES key=b"Sixteen byte key" cipher=AES.new(key,AES.MODE_EAX) data=b"This is a secret@@!!" nonce = cipher.nonce ciphertext, tag = cipher.encrypt_and_digest(data) print(nonce) print(key) print(cipher) print(ciphertext) print(tag) cipher1 = AES.new(key, AES.MODE_EAX, nonce=nonce) plaintext = cipher1.decrypt(ciphertext) try: cipher1.verify(tag) print("The message is authentic:", plaintext) except ValueError: print("Key incorrect or message corrupted") I want to encrypt the plaintext I enter into the database using the html form and I want to ciphertext to be stored into the database. I want help with that. -
django-storage file upload SuspiciousOperation and the joined path is located outside of the base path component error
I am using the latest version of django and django-storage. I am trying to save an uploaded image and a locally generated resized image. When I tried to save a image I got this errors: Traceback: File "/home/..proj/.env/lib/python3.6/site-packages/storages/backends/s3boto3.py" in _normalize_name 431. return safe_join(self.location, name) File "/home/prism/Desktop/code/viper/.env/lib/python3.6/site-packages/storages/utils.py" in safe_join 75. raise ValueError('the joined path is located outside of the base path' During handling of the above exception (the joined path is located outside of the base path component), another exception occurred: File "/home/..proj/.env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/..proj/.env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/..proj/.env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/..proj/.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/..proj/admin/views.py" in product_update 578. image_model.image_thumbnail_index.save(a.name, File(a)) File "/home/..proj/.env/lib/python3.6/site-packages/django/db/models/fields/files.py" in save 87. self.name = self.storage.save(name, content, max_length=self.field.max_length) File "/home/..proj/.env/lib/python3.6/site-packages/django/core/files/storage.py" in save 51. name = self.get_available_name(name, max_length=max_length) File "/home/..proj/.env/lib/python3.6/site-packages/storages/backends/s3boto3.py" in get_available_name 633. return super(S3Boto3Storage, self).get_available_name(name, max_length) File "/home/..proj/.env/lib/python3.6/site-packages/django/core/files/storage.py" in get_available_name 75. while self.exists(name) or (max_length and len(name) > max_length): File "/home/..proj/.env/lib/python3.6/site-packages/storages/backends/s3boto3.py" in exists 528. name = self._normalize_name(self._clean_name(name)) File "/home/..proj/.env/lib/python3.6/site-packages/storages/backends/s3boto3.py" in _normalize_name 434. name) Exception Type: SuspiciousOperation at /admin/product/update/7/ Exception Value: Attempted access to '/home/..proj/convert/mqedpqL4tepvF4bT7wySMm/jo_308x412.webp' denied. Image model: class ProductImage(models.Model): image = models.ImageField(storage=ProductMediaStorage()) image_thumbnail_index = models.ImageField(storage=ProductMediaStorage()) … -
Anyone is able to delete or update other's post through url
Hy, I am developing a Django Blog application. In this application, I have a PostEdit view to edit the post, Delete post view to delete the post. These operations can only be performed by the user who has created that post. I used Delete view as a functional view and edit view as CBV. Now what is happening is that any user is able to delete or edit the others post through URL. In my delete post view since it is a functional based view, I have used if condition to prevent another user to prevent deleting someone else post. But since for post edit, I am using CBV, I am not able to find a way to prevent a user from editing someone else's post. So how can I prevent doing another user to edit someone else post? class PostUpdateView(LoginRequiredMixin ,UpdateView): model = Post template_name = 'blog/post_form.html' form_class = PostForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Update' return context def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) @login_required def post_delete(request, slug): post = get_object_or_404(Post, slug=slug) if (request.user == post.author): post.delete() return redirect('blog:post_list') else: return redirect('blog:post_detail', slug=slug) -
ValueError: server must be a Flask app or a boolean
I'm trying to work through the simplest dashboard example in the django-plotly-dash documentation, but I'm consistently getting the ValueError above. For the code below, assume the django project name is django_project and the django app name is dashboard. My ROOT_URLCONF at django_project/urls.py has the following relevant code: import dashboard.dash_app from dashboard.views import test_view urlpatterns = [ ... path('dashboard/', test_view, name='test_view'), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] My dashboard app view, located at dashboard/views.py is as follows: from django.shortcuts import render def test_view(request): return render(request, 'dashboard/main.html') The main.html template is as follows: from django.shortcuts import render def test_view(request): return render(request, 'dashboard/main.html') {% load plotly_dash %} {% plotly_app name="SimpleExample" %} Finally, the DjangoDash app instance is created in a file called dashboard/dash_app.py. As shown earlier, this module is imported in django_project/urls.py, as above. Code is as follows: import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample') app.layout = ... @app.callback(...) def callback_color(...): ... During the debugging process, the only other seemingly relevant information that I have is that the base_pathname is '/django_plotly_dash/app/SimpleExample/' Any other ideas? -
Display a fixed-length subset of a list in a Django template
I'd like to display a fixed-length subset of a set of related objects in a Django template. For example, imagine that I have a Car, which has related object Owner. I would like to display the four most recent owners, but also always display three entries even if there are fewer. So Ford Fiesta AA11 1AA 1. John Smith 2. Jane Smith 3. Jenny Smith Aston Martin DB9 1. Richard Rich 2. 3. even if the Fiesta has had 10 owners (and the DB9 has had only one). The naive way to do this would be <h1>{{car.name}}</h1> <ol> {% for owner in car.owner_set|slice:":3" %} <li>{{owner.name</li> {% endfor %} </ol> but this will only display one list item if there has only been one owner. I could also add lines like {% if car.owner_set|length < 2 %}<li></li>{% endif %} {% if car.owner_set|length < 3 %}<li></li>{% endif %} but that's terrible. Is there a nicer way to do this? -
When starting new django process during testing it uses the wrong database
If I start a new process in a django test case, it uses the normal database instead of the testing database. class ClientManagerTest(TestCase): def setUp(self): self.clientprocess = Process(target=run).start() Now If I do e.g. def run(): User.objects.all() it queries the standard database instead of the testing database. How to fix this?