Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's .annotate generates an SQL operation per instance in queryset
I have a problem where my annotation for lowest related gross_price seems to be causing n+1 amount of queries. I have two models Product and ProductOption, which looks like: class Product(models.Model): ... class ProductOption(models.Model): product = models.ForeignKey(Product, related_name="options", ...) gross_price = models.DecimalField(...) In my manager queryset method, which lists all products i have the following code: def annotate_lowest_price(self) -> QuerySet["models.Product"]: return self.prefetch_related("options").annotate(lowest_price=Min("options__gross_price") And it's used in the code like this: def get_products_list(): products = Product.objects.filter(...).annotate_lowest_price() ... The method outputs as expected, but doing a .explain() shows that it generates a SELECT MIN operation per instance in the queryset. E.g if you have 10 products, it will do 10 queries: SELECT "products_product"."id", ... SELECT "products_productoption"."id", ... SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 666 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 668 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 681 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 672 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 685 AND "products_productoption"."status" = 3) SELECT MIN("products_productoption"."gross_price") AS "gross_price__min" FROM "products_productoption" WHERE ("products_productoption"."product_id" = 671 AND "products_productoption"."status" = 3) SELECT … -
ImportError: cannot import name 'djongo_access_url' from 'djongo'
I am getting the following error using Djongo with Mongodb in a django server: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/cchilders/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/cchilders/.local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/cchilders/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/cchilders/.local/lib/python3.10/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/cchilders/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed … -
Django not migrating after makemigrations
I'm working on a Django project with some apps, but from the beginning, I had problems with 'makemigrations' and 'migrate'. These two are giving me some non-sens errors that I can't find solutions to. And from yesterday when I copied someones else code and replaced it with mine, 'makemigrations' works but 'migrate' doesn't. Here are my models.py: from django.db import models from django.utils.translation import gettext_lazy as _ # third party apps from mptt.models import MPTTModel, TreeForeignKey from ckeditor.fields import RichTextField # Local apps from account.models import User from extentions.utils import jalali_converter class Category(MPTTModel): title = models.CharField(max_length=100, verbose_name=_('عنوان')) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children", verbose_name=_('فرزند')) is_child = models.BooleanField(default=False, verbose_name=_('فرزند است؟')) slug = models.SlugField(unique=True, null=True, blank=True, allow_unicode=True) created = models.DateTimeField(auto_now_add=True, verbose_name=_('زمان ساخت')) updated = models.DateTimeField(auto_now=True, verbose_name=_('زمان بروزرسانی')) class Meta: verbose_name = _('دسته بندی') verbose_name_plural = _('دسته بندی ها') def __str__(self): return self.title class Video(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='videos', verbose_name=_('بارگذار')) title = models.CharField(max_length=100, unique=True, verbose_name=_('عنوان ویدئو')) slug = models.SlugField(unique=True, null=True, blank=True, allow_unicode=True) category = models.ManyToManyField(Category, related_name='cvideos', verbose_name=_('دسته بندی ها')) about_video = RichTextField(verbose_name=_('درباره ویدئو')) views = models.PositiveBigIntegerField(default=1, verbose_name=_('بازدید')) video = models.FileField(upload_to='videos/video_files', verbose_name=_('ویدئو')) image = models.ImageField(upload_to='videos/pictures/', verbose_name=_('عکس نمایشی')) time = models.IntegerField(default=1, verbose_name=_('مدت زمان ویدئو')) created = models.DateTimeField(auto_now_add=True, verbose_name=_('تاریخ ساخت')) updated = models.DateTimeField(auto_now=True, verbose_name=_('تاریخ … -
Should I learn Django or Node js in 2022? [closed]
I know Python, so should I learn Django as a backend framework or should I learn JavaScript so that I can go with Node js as a backend framework?? Which is worth learning in 2022? -
'dict' object has no attribute 'encode' in AES django
so i want encrypt file using key i was input. but there's error message: 'dict' object has no attribute 'encode' and the line that's error like this. i already read another website, i must add encode('utf8'), but it not works on me. i was copy the code using this by tweaksp aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr.encode('utf8')) if you need full code, here's: # AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256). key_bytes = 16 # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testpass): assert len(key) == key_bytes print(testpass) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr.encode('utf8')) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testpass) print(iv) print(ciphertext) return (iv, ciphertext) i called that function like this enkripsi = encrypt("testingtesting11", testpass) -
How to update fields on import Django?
I need to update fields on import for ManyToMany bulk editing. When importing, now I can only add products, because when I try to add already existing fields, I get a message about already existing IDs. How can I update products using import? admin.py class ProductResource(resources.ModelResource): class Meta: model = Part class PartAdmin(ImportExportActionModelAdmin): resource_class = ProductResource filter_horizontal = ('analog',) admin.site.register(Part, PartAdmin) models.py class Part(models.Model): brand = models.CharField('Производитель', max_length=100) number = models.CharField('Артикул', max_length=100, unique=True) name = models.CharField('Название', max_length=100) description = models.TextField('Комментарий', blank=True, max_length=5000) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True) images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) def __str__(self): return str(self.brand + " " + self.number + " " + self.name) return self.name -
how to show a button in admin panel with a particular link format
I have an order field in my models class Order(models.Model): STATUS = ( ('Unpaid', 'Unpaid'), ('Paid', 'Paid'), ('Accepted', 'Accepted'), ('Completed', 'Completed'), ('Cancelled', 'Cancelled'), ) user = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) payment_method = models.CharField(max_length=100,blank=True,null=True) order_number = models.CharField(max_length=20,blank=True, null=True) first_name = models.CharField(max_length=50,blank=True, null=True) last_name = models.CharField(max_length=50,blank=True, null=True) phone = models.CharField(max_length=15,blank=True, null=True) email = models.EmailField(max_length=50,blank=True, null=True) address_line_1 = models.CharField(max_length=50,blank=True, null=True) address_line_2 = models.CharField(max_length=50, blank=True, null=True) country = models.CharField(max_length=50,blank=True, null=True) state = models.CharField(max_length=50,blank=True, null=True) city = models.CharField(max_length=50,blank=True, null=True) order_note = models.CharField(max_length=100, blank=True, null=True) order_total = models.FloatField(blank=True, null=True) tax = models.FloatField(blank=True, null=True) status = models.CharField(max_length=10, choices=STATUS, default='New') ip = models.CharField(blank=True, null=True, max_length=20) is_ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pin_code = models.CharField(max_length=7,blank=True,null=True) bill_url = models.CharField(max_length=100,blank=True,null=True,) def full_name(self): return f'{self.first_name} {self.last_name}' def full_address(self): return f'{self.address_line_1} {self.address_line_2}' def __str__(self): return self.order_number based on the id of the url i have an endpoint /order/download-bill/{order.id} So what i want in my admin panel i want the admin have a button on which he click and the url trigger which will automatically download the bill -
How to get all entries of the item if it has one specific value
I have a Car Model something like below: id | car_name | test_type 1 | carA | P 2 | carB | Q 3 | carC | Q 4 | carA | Q I want to query it in such a way if carA has 'P' as its test_type then result must also contains all the entries for carA. Expected result for carA: id | car_name | test_type 1 | carA | P 4 | carA | Q Is there a way to do this in Django? -
The annotation x conflicts with a field on the model
I want to remove/replace some properties from list() call on Django rest framework call. e.g. I have ip_address on the db table, also adds ip_address when perform_create() called, but it should not be shown/included on list() and retrieve() calls. On retrieve calls, I can make it simply overriding the method then by adding instance.ip_address = None. But the problem now I have is on list() calls, I need to modify properties of a queryset object. I tried the following, o = ThreadedComment.objects.all() o.annotate(ip_address=Value('', output_field=CharField())).all() but I got an error: The annotation 'ip_address' conflicts with a field on the model. Is there a way to remove/override/replace an properly on queryset in Django? Thanks -
How can I fix django error? "template does not exist"
I started Django few days ago and I am stuck now. I got error like this. django.template.exceptions.TemplateDoesNotExist: home.html but I don't know how to fix it. views.py from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, "main/base.html", {"name":ls.name}) def home(response): return render(response, "main/home.html", {'name':'test'}) base.html <html> <head> <title>Website</title> </head> <body> <p>{{name}}</p> </body> </html> home.html {% extends 'main/base.html' %} Both html files are in file named templates I thought template might have something to do with it and checked it. setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Does someone help me out? -
Celery receives tasks from rabbitmq, but not executing them
I have a Django project and have setup Celery + RabbitMQ to do heavy tasks asynchronously. When I call the task, RabbitMQ admin shows the task, Celery prints that the task is received, but the task is not executed. Here is the task's code: @app.task def dummy_task(): print("I'm Here") User.objects.create(username="User1") return "User1 Created!" In this view I send the task to celery: def task_view(request): result = dummy_task.delay() return render(request, 'display_progress.html', context={'task_id': result.task_id}) I run celery with this command: $ celery -A Snappshop worker -l info --concurrency=2 --without-gossip This is output of running Celery: -------------- celery@DESKTOP-8CHJOEG v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.19044-SP0 2022-08-22 10:10:04 *** --- * --- ** ---------- [config] ** ---------- .> app: proj:0x23322847880 ** ---------- .> transport: amqp://navid:**@localhost:5672// ** ---------- .> results: *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] .proj.celery.debug_task . entitymatching.tasks.create_and_learn_machine . entitymatching.tasks.dummy_task [2022-08-22 10:10:04,068: INFO/MainProcess] Connected to amqp://navid:**@127.0.0.1:5672// [2022-08-22 10:10:04,096: INFO/MainProcess] mingle: searching for neighbors [2022-08-22 10:10:04,334: INFO/SpawnPoolWorker-1] child process 6864 calling self.run() [2022-08-22 10:10:04,335: INFO/SpawnPoolWorker-2] child process 12420 calling self.run() [2022-08-22 10:10:05,134: INFO/MainProcess] mingle: all alone … -
django-allauth + django-invitations: IntegrityError at /accounts/signup/, duplicate username
I am using django-allauth + django-invitations. When I access the url in the emailed invitation sent from django-invitations, I receive this error. IntegrityError at /accounts/signup/ duplicate key value violates unique constraint "accounts_userplus_username_key" DETAIL: Key (username)=() already exists. Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.5 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "accounts_userplus_username_key" DETAIL: Key (username)=() already exists. UserPlus is my custom model name -
Unable to send Xml request
Am having issue sending xml request in pthon because i don't know how to render python code in xml. I have no idea how to render or navigate xml text like in example below or how to render python code in xml text before sending the python request. def start_xml_payment(request): if request.method == 'POST': form = FormPaymentForm(request.POST) if form.is_valid(): payment = form.save() first_name = request.user.first_name last_name = request.user.last_name email = request.user.email serdate = datetime.datetime.now() ref = payment.ref amount = payment.amount fees = payment.fees datejson_str = json.dumps({'created_at': serdate}, default=str) url = 'https://secure.powerpay.com/API/v6/' xml = ''' <?xml version="1.0" encoding="utf-8"?> <API3G> <code>4332-9D7F-4E09-96D4-3D44E7A83EA3</Code> <Transaction> <PaymentAmount>{amount}</PaymentAmount > <customerEmail>{email}</customerEmail> </Transaction> <Services> <Service> <ServiceDate>{datejson_str}</ServiceDate> </Service> </Services> </API3G> ''' headers = {'Content-Type': 'application/xml'} response = requests.post(url, data=xml, headers=headers) response_data = response.json() TransToken = response_data["TransToken"] cashier_response = 'https://secure.powerpay.com/p.php?ID={TransToken}' return HttpResponseRedirect (cashier_response) else: form = FormPaymentForm(request.POST) return render(request, 'dpo/start_dpo_payment.html', {'form': form}) Response <?xml version="1.0" encoding="utf-8"?><API3G><Result>000</Result><ResultExplanation>Transaction created</ResultExplanation><TransToken>803E06BC-CB80-4671-9F92-90326411ACFC</TransToken><TransRef>R39855046</TransRef></API3G> I want to navigate through this xml response and fetch TransToken TransToken = response_data["TransToken"] i want something like this cashier_response = 'https://secure.powerpay.com/p.php?ID={TransToken}' Issue 1 i have issue fetching the Transtoken because am unable to navigate through the xml response to get the transtoken and merge the transtoken to my url. I need help in … -
ImportError ugettext_lazy as _
I am using Django 4 for my webApp and I started getting this error when I want to setup Authentication. I checked all the forum and I found that they suggest to import gettext_lazy as _. But it doesn't work. Any suggestions? -
Uploading a File to database in django from Google drive
As the title suggest, I am trying to figure out how to upload from google drive to my database in PostgreSQL and have gotten nowhere. Would really appreciate some direction. -
How to display timedelta object in grouped queryset as duration field with Django REST Framework?
I have AssigneeLog model class that stores user's clock-in and clock-out on each task. from django.db import models from django.utils import timezone class AssigneeLog(models.Model): topic = models.ForeignKey(to=Topic, on_delete=models.CASCADE, blank=True) assignee = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, help_text='Saved in case topic assignee is changed.') time_in = models.DateTimeField(default=timezone.now, blank=True, help_text='Default to current time.') time_out = models.DateTimeField(null=True, blank=True, help_text='Null at the start of time-in.') I want to list AssigneeLogs grouped by date and calculate how much time spent daily for every user-task combination. I'm able to do it, but the total_time annotated value is displayed in seconds even though I've set output_field argument to django.db.models.DurationField. When the queryset isn't grouped I can get it done with serializing the queryset using ModelSerializer class with rest_framework.serializers.DurationField. DRF view extra action method: from django.db import models from django.db.models.functions import TruncDate from rest_framework.response import Response from zoneinfo import ZoneInfo @action(methods=['post'], detail=False) def get_report(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) datetime_from = serializer.validated_data.get('datetime_from') # ex: "2022-08-01T00:00:00" datetime_to = serializer.validated_data.get('datetime_to') # ex: "2022-08-22T09:00:00" request_tz = serializer.validated_data.get('timezone') # ex: "Etc/GMT+7" logs = AssigneeLog.objects.filter( time_in__gte=datetime_from, time_out__lte=datetime_to ).annotate( date=TruncDate('time_in', tzinfo=ZoneInfo(request_tz)), # truncate to date with tz and add to select list. ).order_by('date').values('date').annotate( total_time=Sum(F('time_out')-F('time_in'), output_field=models.DurationField()) ).values('topic__id', 'topic__name', 'topic__description', 'assignee__name', 'date', 'total_time') return Response(data=logs) Output: [ { … -
How do I change the colum name of model in Django Admin?
My admin.py file from django.contrib import admin from . models import contactEnquiries class ContactAdmin(admin.ModelAdmin): list_display = ['cn_name', 'cn_email', 'cn_number'] @admin.display(description='Name') def cn_name(self, obj): return obj admin.site.register(contactEnquiries, ContactAdmin) I want to display the column titles as - Name, Email, Number instead of 'cn_name', 'cn_email', 'cn_number' . I tried the above code but I am not sure how to do it? Can anyone please help? -
How do I access objects (user info) across Django models? (Foreign Key, Beginner)
I have a Profile model and a Post model in my Django project: class Profile(models.Model): """ User profile data """ user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='profile') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) id_user = models.IntegerField() bio = models.TextField(max_length=280, blank=True) def __str__(self): return str(self.user) class Post(models.Model): """ Model for user-created posts """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post') post_text = models.TextField() created_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.user I want to be able to display a user's first_name and last_name on their posts (which are shown on index.html with other all user posts), along with their username. {% for post in posts %} <div class="row d-flex justify-content-between"> <h5 class="col-12 col-md-6">{{ first_name here }} {{ last_name here }}</h5> <h5 class="col-12 col-md-6">(@{{ post.user }})</h5> </div> I can display the username just fine (post.user above) because it's in the Post model. The first_name and last_name are in the Profile model, however, and I just can't figure out a way to access them. View: @login_required(login_url='signin') def index(request): """ View to render index """ user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() context = {'user_profile': user_profile, 'posts': posts, } return render(request, 'index.html', context) As well as getting all Post objects, my … -
When disconnect or refresh Django channels websocket "took too long to shut down and was killed"
I am using Django Channel for a real-time sending and saving data but when I refresh the page the error came up. log Application instance <Task pending name='Task-2' coro=<StaticFilesWrapper.__call__() running at path\channels\staticfiles.py:44> wait_for=<Future pending cb=[Task.task_wakeup()]>> for connection <WebSocketProtocol client=['127.0.0.1', 50991] path=b'/ws/graph/'> took too long to shut down and was killed. consumer.py async def connect(self): await self.accept() -
How can I get a list of pending invitations for a user using django-invitations?
I can see in the source code for django-invitations that there is a manager with an all_valid method but I'm having trouble connecting the dots back to request.user. I'm also using django-allauth. -
Django unique_together versus explicit duplicate restriction
I currently have this try-except block to restrict duplication of user and post fields in Follow model: def follow(request, post_pk): user = request.user post = Post.objects.get(id=post_pk) try: _follow = Follow.objects.get(user=user, post=post) except Follow.DoesNotExist: _follow = Follow(user=user, post=post) _follow.save() return redirect(request.META.get("HTTP_REFERER")) I recently just learned about unique_together in class Meta. Now, I can modify the model like this: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: unique_together = (('user', 'post'),) Having done so, is it safe to remove the explicit duplicate restriction in try-block of views.py? The code will then look like this: def follow(request, post_pk): user = request.user post = Post.objects.get(id=post_pk) _follow = Follow(user=user, post=post) _follow.save() return redirect(request.META.get("HTTP_REFERER")) -
I am not able to run `python manage.py runserver` in my vscode terminal but the same command is running in my system terminal
VScode terminal: System terminal: -
Django testing a form, self.request kwargs gives keyerror
I have a modelform that uses __init__ to get kwargs. When running tests, I get a keyerror: 'requests'. For my unit test, I setup an existing user and existing object to test for duplicates per user. Here is the form and test: class CourseForm(ModelForm): """ Form used for both creating a new course or updating an existing course.""" class Meta: model = Course fields = ('course_name', 'grade_level',) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.qc = Course.objects.filter(user=self.request.user) super().__init__(*args, **kwargs) def clean(self): super(CourseForm, self).clean() course_name = self.cleaned_data.get('course_name') grade_level = self.cleaned_data.get('grade_level') # check exising course_name per user # exclude(pk=self.instance.pk) because when we update we don't have to consider the current name if course_name and self.qc.exclude(pk=self.instance.pk).filter(course_name__iexact=course_name).exists(): raise ValidationError("A course with that name already exists.") return self.cleaned_data class CourseFormTests(TestCase): @classmethod def setUp(self): self.user = CustomUser.objects.create_user( username='tester', email='tester@email.com', password='tester123', is_teacher=True, is_active=True, ) self.user.save() self.my_course = Course(user=self.user, id='4d192045-07fa-477f-bac2-5a99fe2e7c04', course_name="name", grade_level="SEC") self.my_course.save() def test_CourseForm_valid(self): form = CourseForm(self.user, data={ 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7c04', 'course_name': "Science", 'grade_level': "SEC" },) self.assertTrue(form.is_valid()) def test_CourseForm_invalid_name_too_long(self): form = CourseForm(self.user, data={ 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7c05', 'course_name': "NameistoolongforthistobeOKNameistoolongforthistobeOK", 'grade_level': "SEC" },) self.assertFalse(form.is_valid()) def test_CourseForm_invalid_name_exists(self): form = CourseForm(self.user, data={ 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7c05', 'course_name': "name", 'grade_level': "SEC" },) self.assertFalse(form.is_valid()) The exact error is: line 107, in … -
Opening the acquired URL in the same tab rather than loading it on a new window
I am a web hobbyist using Selenium with Django for some online web scraping. I have created a web app that iterates through the different dates of birth to find valid credentials to log in, but after logging in, it opens up a new window to show the results. I want the acquired URL (acquired through the driver.get function) to open up on the same tab instead of a new window whenever I successfully log in. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By def search_student(registration, dob, set_driver): set_driver.get("http://clearance2.giki.edu.pk:8005/ranks/") username = set_driver.find_element(By.NAME, "username") password = set_driver.find_element(By.NAME, "password") username.send_keys(registration) password.send_keys(dob) set_driver.find_element(By.NAME, "bt1").click() return set_driver op = webdriver.ChromeOptions() op.add_argument('headless') driver = webdriver.Chrome(ChromeDriverManager().install(), options=op) reg_no = input("Enter reg_no: ") birth_year = int(reg_no[0:4]) - 19 date = (birth_year * 10000) + 101 found = False print("Searching...") count = 1 while (count < 6) and (not found): date = (birth_year * 10000) + 101 for i in range(0, 383): driver = search_student(reg_no, date, driver) if driver.current_url == "http://clearance2.giki.edu.pk:8005/ranks/ranks.php": print(f"successfully logged in with DOB {date}") found = True driver.quit() break date += 1 if date % 100 == 32: date -= 32 date += 100 birth_year += pow(-1, count + 1) * … -
Django always accesses default database when creating users
I have django project with multiple databases: DATABASES = { 'default': {}, 'db1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / DB1_NAME, }, 'db2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / DB2_NAME, } } DATABASE_ROUTERS = ['app.router1.Router1', 'app.router2.Router2'] The router for db1 is defined: class Router1: route_app_labels = {'app', 'sessions', 'auth', 'admin', 'contenttypes'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'db1' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'db1' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'db1' return None Everything seems to work well, except creating new users. When I try to create a new user, I get the following error: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. When I change db1 to default, user creation seems works well.