Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Boto3 Compatibility Issue, How can I install an older version of Boto3?
I'm trying to deploy my Django project to AWS Elastic Beanstalk. The tutorial I am following is suggesting I use Boto3 to link up my S3 Database. The problem is when I am installing Boto3 i am getting this message in red. awsebcli 3.20.3 requires botocore<1.24.0,>1.23.41, but you have botocore 1.27.7 which is incompatible. So I'm trying to install the older version of Botocore, 1.24.0 or 1.23.41, but after looking at PyPi I can't seem to find it since it just says use pip3 install boto3. Any suggestions? -
How to resolve "NoReverseMatch" Error in Django?
So I'm trying to create a table of hosts, and as one of the fields of that table include a clickable link to an update page. Which will pass the host_id to the update page. I was hoping someone could tell me what I'm doing wrong with regards to passing the correct parameter to upate/<host_id>. As I'm not quite sure as to how to fix the issue and make it so I can direct people via a clickable button in the table rendered to the appropriate update page. When I attempt to render the page with that added in I'm getting the following error: NoReverseMatch at /website/home/ Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['website/update/<host_id>'] Request Method: GET Request URL: http://127.0.0.1:8000/website/home/ Django Version: 4.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['website/update/<host_id>'] It is also spiecificlly pointing to the following line of code as the issue: <td><a href="{% url 'update' beacon.host_id %}"</a>Issue Command</td> This line is found in the following HTML segment. Relevant HTML Section {% for beacon in hosts %} <tr> <td>{{ beacon.host_id }}</td> <td>{{ beacon.hostname }}</td> <td>{{ beacon.internalIp }}</td> <td>{{ beacon.externalIp }}</td> <td>{{ beacon.current_user }}</td> … -
Unable to save webp file to model field
I'm not sure if this is entirely django related, but if someone could help me, that would be so much appreciated! I'm having trouble generating a webp file from the following code from io import BytesIO from PIL import Image import requests I've got the following model class UserImage(models.Model): user_provided_image = VersatileImageField(upload_to=folder10, null=True, blank=True) nextgen_image = models.FileField(upload_to=folder10,null=True, blank=True) #for WebP images I'm creating a webp file. This code works, but it saved it to the file to the root directory of my project and I'm not sure how to save it to the FileField (i.e. nextgen_image ) on my model def create_webp_image(sender, instance, *args, **kwargs): image_url = instance.image.thumbnail['1920x1080'].url try: response = requests.get(image_url, stream=True) path = image_url except: #local env path = "http://localhost:8000" + image_url response = requests.get(path, stream=True) img = Image.open(BytesIO(response.content)) #build file path position = path.rfind("/") + 1 newpath = path[0:position] #build file name image_name = path[position:] name_of_file = image_name.split('.')[0] + ".webp" #this creates the webp file img.save(name_of_file,"webp") #save image to model #instance.nextgen_image = ? post_save.connect(create_webp_image, sender=UserImage) Thanks! -
"Tainted canvases may not be exported" even after allowing all URLs with Django CORS Headers module
Using Django, I'm attempting to pull a texture from textures.minecraft.net, crop, zoom, and display a section of said texture. CORS of course has a problem with this. In response to this, I've installed the pip module "django-cors-headers" and set up my settings according to the instructions here. Here's what my settings.py looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # here it is 'users.apps.UsersConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # here it is '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', ] CORS_ALLOW_ALL_ORIGINS = True # Yes, it's unsafe. I just want a working prototype for now CORS_ALLOW_CREDENTIALS = True I have a JS that attempts to create a new image with the source of the above texture. Here's the JS snippet: let skin = "http://textures.minecraft.net/texture/74d1e08b0bb7e9f590af27758125bbed1778ac6cef729aedfcb9613e9911ae75"; let testImg = new Image(); testImg.height = 64; testImg.width = 64; testImg.setAttribute('crossorigin', 'anonymous'); testImg.src = skin; This script is loaded in VIA django like so: <!-- Load the JS script into the base html on this page --> {% block bodyscripts %} <script src="{% static 'js/test.js' %}" defer></script> {% endblock bodyscripts %} My Pipfile contains: django-cors-headers = "*" Yet I still receive the error "Access to image at 'http://textures.minecraft.net/texture/74d1e08b0bb7e9f590af27758125bbed1778ac6cef729aedfcb9613e9911ae75' from origin … -
Django: save multiple images on upload
I want to save multiple versions of a picture and based my solution on this thread: Django / PIL - save thumbnail version right when image is uploaded The model Class overrides the save() function, which calls the make_thumbnail() function, to scale the image. The issue is, that this code, does not save the uploaded file, but it takes the default image. Where is the issue? models.py pic_formats = [(640, 480), (1280, 960), (1920, 1440) ] def path_and_rename(path, sufix=None): def wrapper(instance, filename): file_extension = filename.split('.')[-1] # get filename if instance.pk: filename = f'{instance.pk}_{sufix}.{file_extension}' else: # set filename as random string filename = f'{uuid4().hex}.{file_extension}' # return the whole path to the file return os.path.join(path, f'user_{str(instance.pk)}', filename) return wrapper class UserProfile(models.Model): email = models.OneToOneField(User, on_delete=models.CASCADE) # Profile Pictures profile_pic_orig = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='orig'), default='img/profile_picture/default.jpg', verbose_name=_('profile picture')) profile_pic_640 = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='640'), default='img/profile_picture/default_640.jpg', verbose_name=_('profile picture 640px'), null=True) profile_pic_1280 = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='1280'), default='img/profile_picture/default_1280.jpg', verbose_name=_('profile picture 1280px'), null=True) profile_pic_1920 = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='1920'), default='img/profile_picture/default_1920.jpg', verbose_name=_('profile picture 1920px'), null=True) def make_thumbnail(self, formats: list): from PIL import Image from io import BytesIO from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile import copy image = Image.open(BytesIO(self.profile_pic_orig.read())) thumb_name, thumb_extension = os.path.splitext(self.profile_pic_orig.name) thumb_extension = thumb_extension.lower() if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' … -
django-autocomplete-light generic foreign key invalid view function
I am trying to use django autocomplete light to set up Autocompletion for GenericForeignKey However I am getting this error when I try to view the form: I have a simple a setup. My best guess is that because the urls are in an app's urls.py (and not in the project's urls.py), it's looking for them at root, instead of in the app? But I'm not sure how to get DAL to look for these views in the app, if that's even the problem. models.py class Prereq(IsAPrereqMixin, models.Model): name = models.CharField(max_length=256, null=True, blank=True) prereq_content_type = models.ForeignKey(ContentType, related_name='prereq_item', verbose_name="Type of Prerequisite", on_delete=models.CASCADE) prereq_object_id = models.PositiveIntegerField(verbose_name="Prerequisite") prereq_object = GenericForeignKey("prereq_content_type", "prereq_object_id") # lots more fields ignored for now forms.py from dal import autocomplete from prerequisites.models import Prereq class PrereqForm(autocomplete.FutureModelForm): prereq_object = autocomplete.Select2GenericForeignKeyModelField( model_choice=[(Prereq, "Prereq"), ] ) class Meta: model = Prereq fields = ['name'] urls.py from django.urls import path from prerequisites import views from prerequisites.forms import PrereqForm app_name = 'prerequisites' urlpatterns = [ path('edit/<int:pk>/', views.PrereqUpdateView.as_view(), name='prereq_edit'), ] # https://django-autocomplete-light.readthedocs.io/en/master/gfk.html#register-the-view-for-the-form urlpatterns.extend(PrereqForm.as_urls()) -
Django ModelForm submit button not working
I am trying to make a Django ModelForm that retrieves data from my database using the GET method. When I click the submit button nothing happens. What am I doing wrong? HTML doc <form role="form" action="" method="GET" id="form-map" class="form-map form-search"> <h2>Search Properties</h2> {% csrf_token %} {{ form.as_p }} <input type="submit" action= "" class="btn btn-default" value="Submit"> <input type="reset" class="btn btn-default" value="Reset"> </form><!-- /#form-map --> forms.py from django import forms from .models import StLouisCitySale208 from django.forms import ModelForm, ModelMultipleChoiceField class StLouisCitySale208Form(ModelForm): required_css_class = 'form-group' landuse = forms.ModelMultipleChoiceField(label='Land use', widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('landuse', flat=True).distinct()) neighborho =forms.ModelMultipleChoiceField(label='Neighborhood',widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('neighborho', flat=True).distinct()) policedist = forms.ModelMultipleChoiceField(label='Police district',widget=forms.SelectMultiple,queryset=StLouisCitySale208.objects.values_list('policedist', flat=True).distinct()) class Meta: model = StLouisCitySale208 fields = ['landuse', 'neighborho', 'policedist', 'precinct20','vacantland', 'ward20', 'zip', 'zoning','asmtimprov', 'asmtland', 'asmttotal', 'frontage', 'landarea','numbldgs', 'numunits'] -
Converting to WebP - 'VersatileImageFieldFile' object has no attribute 'mode'
I've got the following model class UserImage(models.Model): user_provided_image = VersatileImageField(upload_to=folder10, null=True, blank=True) nextgen_image = models.FileField(upload_to=folder10,null=True, blank=True) #for WebP images I'm attempting to save the user uploaded image to WebP. def create_webp_image(sender, instance, *args, **kwargs): image = instance.user_provided_image.thumbnail['1920x1080'].url #Create webp image webp.save_image(image, 'image.webp', quality=80) #save image to model instance.nextgen_image = webp post_save.connect(create_webp_image, sender=UserImage) I'm getting the following error: 'str' object has no attribute 'mode' The traceback indicates that it fails on the 3rd line of this block from the webp codebase: @staticmethod def from_pil(img): if img.mode == 'P': if 'transparency' in img.info: img = img.convert('RGBA') else: img = img.convert('RGB') return WebPPicture.from_numpy(np.asarray(img), pilmode=img.mode) Thanks! -
Django + PostgreSQL best way to improve performance of slow summary aggregation?
Context I have a Django REST API using PostgreSQL database with millions of Items. These Items are processed by several systems and the processing details are sent back and stored a Records table. The simplified models are: class Item(models.Model): details = models.JSONField() class Record(models.Model): items = models.ManyToManyField(Item) created = models.DateTimeField(auto_created=True) system = models.CharField(max_length=100) status = models.CharField(max_length=100) details = models.JSONField() Goal I would like to do arbitrary filters on the Items's table and get a summary of various systems. This summary obtains the latest status for each selected Item for each system, and displays a count of each status. For example if I filter for 1055 items an example return is: { System_1: [running: 5, completed: 1000, error: 50], System_2: [halted: 55, completed: 1000], System_3: [submitted: 1055] } I currently have this working doing queries like below, which returns the count of processing statuses for System_1 and repeat for the other systems and package into a JSON return. Item.objects.filter(....).annotate( system_1_status=Subquery( Record.objects.filter( system='System_1', items__id=OuterRef('pk') ).order_by('-created').values('status')[:1] ) ).values('system_1_status').annotate(count=Count('system_1_status')) We have millions of Items and Records and this works reasonably well if we select less than a thousand Items. Above this it takes minutes. Trying to do it for hundreds of thousands of items … -
Is the UML/Design Pattern for my portfolio correct or how could it be improved (should?)?
First of all, I'm trying to create my web portfolio with Django and React to start as a Full Stack developer. I thought it would be a good idea to show already on my portfolio some of the things I can do (my portfolio would be ALREADY a fullstack project). So this is what I want to do: A web portfolio that is managed by me, with kind of a blog/comment functionality. I can add a project whenever I have sth new to display Those projects can be reviewd by users (who may or may not register to my site) Those projects can be liked only by registered users (I figured that might be simpler) Reviews can be answered by anyone It doesn't need to be complicated, so if you think that might work, just say so BUT, if you notice ANY problem I might run into with this design, please let me know. I don't know much about UML, but I noticed it makes your life so much simpler to actually create the backend once you designed your tables. The Tables shown on the graphic below will be represented by the Models on Django. This is the UML that … -
Django: how to set ForeignKey related_name in Abstract Model class?
I want to create on Abstract Model class for future inheriting like this: class AbstractModel(models.Model): created_at = models.DateTimeField( auto_now_add=True, blank=True, null=True, ) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='XXX_created_by', blank=True, null=True, ) class Meta: abstract = True Field 'created_at' is working fine, but how to generate related_name in 'created_by' for my child classes to prevent clashing? -
Testing Django project with pytest
All local tests passed successfully with pytest in my virtual environment. However, when I setted up a workflow (pipeline) in github actions, all tests fails. Could you please help me ? Here is my pipeline: name: Django CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.8, 3.9] steps: # Checkout the Github repo - uses: actions/checkout@v3 # Install Python - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} # Install project dependencies - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt # Move into the django project folder (Sigma) and run pytest - name: Run Tests with pytest working-directory: . run: | pip install pytest pytest -v -
Django Object Detection Webcam Video feed, TypeError: fromarray() missing 1 required positional argument: 'obj'
I have been asking questions on StackOverflow but have not been getting any positive responses. Got banned multiple times from posting further questions. Please provide help this time. I want to perform custom object detection using custom trained YOLOv5 model on a real-time video feed taken from the webcam. I am using Django for this purpose (later on I will connect this with React.js frontend). I have been successful with accessing the webcam feed using Django but when I try to run my custom yolov5 model on the video feed. I am getting this error and there is no video showing up in index.html. [12/Jun/2022 02:43:03] "GET / HTTP/1.1" 200 329 Traceback (most recent call last): File "c:\users\mh_s1\appdata\local\programs\python\python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\mh_s1\appdata\local\programs\python\python37\lib\wsgiref\handlers.py", line 183, in finish_response for data in self.result: File "D:\University\FYP\FYP-CovidDefence\stream\webcam\views.py", line 42, in stream data=im.fromarray() TypeError: fromarray() missing 1 required positional argument: 'obj' Here is my views.py file code: from django.http import StreamingHttpResponse import cv2 from PIL import Image as im import yolov5 from yolov5.utils.general import (check_img_size, non_max_suppression, scale_coords, check_imshow, xyxy2xywh, increment_path) from yolov5.utils.torch_utils import select_device, time_sync from yolov5.utils.plots import Annotator, colors import io import torch # Create your views here. def index(request): return render(request,'index.html') … -
AttributeError: module 'django.db.models' has no attribute 'ManyToMany'
I am trying to make one of my model objects a ManyToMany Field, so I can access the objects through both models. I am receiving the following error. listing = models.ManyToMany(Listings, blank=True, related_name="listing") AttributeError: module 'django.db.models' has no attribute 'ManyToMany' models.py class WatchList(models.Model): listing = models.ManyToMany(Listings, blank=True, related_name="listing") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") -
The change in the django view is not reflected to the page until restarting uwsgi
I installed Django + Uwsgi + Nginx. Project is running. But when i change something in the view, the change is not reflected to page until i restart uwsgi. Should i restart uwsgi everytime i make a change in the view? But when i add time to view to show in the page. The displayed time is changing everytime i refresh the page. My view is : from django.shortcuts import render from django.http import HttpResponse # added from django.utils import timezone def home(request): return HttpResponse('This is the home page. 101' + str(timezone.now())) My urls.py : from django.contrib import admin from django.urls import path from godentiapp import views # added urlpatterns = [ path('', views.home, name='home'), # added path('admin/', admin.site.urls), ] -
django.core.exceptions.ImproperlyConfigured each time running pytest
Whenever I open my django project and try to test it I get django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Or it can be other explanation with the same Error (not always with INSTALLED_APPS...). I can fix it with command: export DJANGO_SETTINGS_MODULE=<project_name>.settings But I would have to do it every time I open the project. Is there a way for this to be fixed once and forever? -
Django IntegrityError; NOT NULL constraint failed when trying to post on django blog web app
I am trying to upload text to my blog web app but I keep getting an intergity error saying 'NOT NULL constraint failed'. Can anyone help me resolve this issue? My models.py file looks like this: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class File(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=True) date_uploaded = models.DateTimeField(default=timezone.now) uploader = models.ForeignKey(User, on_delete=models.CASCADE) id = models.BigAutoField(primary_key=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('file-detail', kwargs={'pk': self.pk}) auto_now_add=True -
Django App running on Google Cloud Run fails SignatureDoesNotMatch with SignedUrl Storage upload
I am creating signed_urls using a Django app running on Cloud Run. def get_signed_url_for_upload(path): blob = settings.STORAGE.bucket.blob(path) expiration_time = timezone.now() + timedelta(minutes=120) signed_url = blob.generate_signed_url(expiration_time) return signed_url I am trying to use the SignedURL created with a Curl command : curl -X PUT --upload-file /Users/utku/Desktop/cat.mp4 "https://storage.googleapis.com/development-videoo-storage/d340a0e21c6b4681a1c26a46a6c30fee?Expires=1654985178&GoogleAccessId=videoo-348016%40appspot.gserviceaccount.com&Signature=delh%2BHVpqzaYl%2BGb%2FndhJbY5d7RtI4RH4q12BTd1NJoK9iU6%2BlE%2FrWAaBvdxgarafKIRH0PFpFfsFvYa4%2BauehUwaOWaY46e93fl3Cdok6Q%2BklVjQLrdAMS%2BT38YTDPdSTp1BGJir2UfsCFmjTJR7eul29y%2BjxrSZtAgUHc6%2Fym7%2FAjLuOheeKZauJAk1LmLejxPt8%2FsKm3jgHxtdAmq45OFZKVvCuYXmNghSBDTBPHOND%2BSmOyC1OXMOCFBjwgNGKziypf2OJpdQWe4iV4z9r2Afa9HYE5uHMB67ahBRip03LVCZApSnAZM7OaJrQaCPWk9pDQLaUu2rZYG49%2B9HA%3D%3D" Here is below the output that I get from curl command : <?xml version='1.0' encoding='UTF-8'?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>PUT 1654985178 /development-videoo-storage/d340a0e21c6b4681a1c26a46a6c30fee</StringToSign></Error>% In the Google Cloud documentation : https://cloud.google.com/run/docs/configuring/service-accounts It says that Cloud Run uses compute engine service account by default : Here are my Compute Engine Service Account settings : Any suggestions on what I might do to fix this "SignatureDoesNotMatch" failure ? -
Variables only receive if in debug mode (Django).. WHY?
I have the following assignments to do in my code: else: form = SourceForm(request.POST) form.instance.Id = x form.instance.Sheet_name = Sheet_name form.instance.User = User_ #form.instance.Project = proj.set() form.instance.Person = p form.instance.Role_type = Function_ form.instance.Institution = inst form.instance.Survey = surv if form.is_valid(): form.save() However, if I'm in debug mode running line by line, all variables receives values correctly. But if I'm running normally it seems it doesn't perform the assignments, just the first two: form = SourceForm(request.POST) form.instance.Id = x I've never seen this before. Why do variables only receive values in debug mode? I'm using PyCharm and Django Framework -
Celery tasks not running in docker-compose
I have a docker-compose where there are three components: app, celery, and redis. These are implemented in DjangoRest. I have seen this question several times on stackoverflow and have tried all the solutions listed. However, the celery task is not running. The behavior that celery has is the same as the app, that is, it is starting the django project, but it is not running the task. docker-compose.yml version: "3.8" services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: autoinfo_api command: python manage.py runserver 0.0.0.0:8000 depends_on: - redis redis: image: redis:alpine container_name: redis ports: - 6379:6379 volumes: - ./redis/data:/data restart: always environment: - REDIS_PASSWORD= healthcheck: test: redis-cli ping interval: 1s timeout: 3s retries: 30 celery: image: celery:3.1 container_name: celery restart: unless-stopped build: context: . dockerfile: Dockerfile command: celery -A myapp worker -l INFO -c 8 volumes: - .:/django depends_on: - redis - app links: - redis DockerFile FROM python:3.9 RUN useradd --create-home --shell /bin/bash django USER django ENV DockerHOME=/home/django RUN mkdir -p $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PIP_DISABLE_PIP_VERSION_CHECK 1 USER root RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' RUN … -
cannot unpack non-iterable ForeignKeyDeferredAttribute object
Hello I want to generate a pdf file with the information from the data base : here is my model : class Patient(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) age = models.PositiveIntegerField(null=True, blank=True) medcine = models.OneToOneField(Medcine, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(default="profile1.png" ,null=True, blank=True) def __str__(self): return self.name ``` This is my views : def get(self, request, *args, **kwargs): data = Patient.objects.get(Patient.user_id) open('templates/temp.html', "w").write(render_to_string('pdf1.html', {'data': data})) # Converting the HTML template into a PDF file pdf = html_to_pdf('temp.html') # rendering the template return HttpResponse(pdf, content_type='application/pdf') ``` urlpatterns = [ path('pdf/<str:id>', GeneratePdf.as_view(), name="GeneratePdf"), ] this is my html code <div class="button" > <a href="/pdf/{{ user.id}}">Votre Pass</a> </div> -
How to ensure only one entry is True in a Django model?
I'm stuck on thinking about implementing a "only one entry might be True for one combination". A Project has n members (Guards) through an intermediate table. every Guard may be member of n Projects only one combination of Guard <-> Project is allowed (unique_together) a MemberShip might be the 'Main' one (is_main) BUT: Only one of the memberships may be Main. Do I oversee something or do I have to implement a custom validation on my own? To complete this, see the given Model: class Project(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) shortname = models.CharField(_('shortname'), max_length=50) description = models.TextField(_('description'), blank=True) members = models.ManyToManyField(Guard, through='ProjectMembership') class Meta: unique_together = ['client', 'shortname'] class ProjectMembership(models.Model): guard = models.ForeignKey(Guard, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) is_main = models.BooleanField(_('is main project'), default=False) class Meta: unique_together = ['guard', 'project'] -
Boost Django Queryset with NumPy and Numba
Please I need your help! I have a large Query set (20 million rows) at views.py and for each row I want to compare the author's value with an input value added by "author_value_input". The comparison is made in the def levenshteinDistance method. My problem is that it takes too long to complete. I tried numpy without success. Could you tell me the changes I need to make to make it more effective? Can I use Numpa jit and if so how? I have an AMD gpu. from WebSite.models import Bibliography def listing_api(request): author_value_input = request.GET.get("author_value_input", "") selectedSim = request.GET.get("selectedSim", "") slider_value = request.GET.get("slider_value", 10) selectedSim=str(selectedSim); slider_value_int=float(slider_value); results = Bibliography.objects.all() author_demo=[] if (selectedSim=="ls"): paginator = Paginator(results, 1000000) for page_number in paginator.page_range: page = paginator.page(page_number) for obj in page.object_list: if (levenshteinDistance(obj.get("author"), author_value_input) < slider_value_int): author_demo.append(obj.get("author")) keywords = Bibliography.objects.filter(author__in = author_demo) def levenshteinDistance(s1, s2): if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2+1] for i1, c1 in enumerate(s1): if c1 == c2: distances_.append(distances[i1]) else: distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1]))) distances = distances_ return distances[-1] -
Django email backed error brings socket error on smtp but send to console successful
I tried to send email via django Email message for account mail verification. When I send email via to console it send the activation link successfully but when it comes to sending via smtp I get TypeError: getaddrinfo() argument 1 must be string or none Email code:https://www.javatpoint.com/django-user-registration-with-email-confirmation -
Using self.object in CreateView to create objects in other tables
When a user makes a new listing using a CreateView, I am trying to use this new object to create a Bid in the Bids table. class ListingCreateView(CreateView): model = Listing fields = ['title', 'description', 'starting_bid', 'url'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def post(self, request, *args: Any, **kwargs: Any): self.object = self.get_object() starting_bid = self.request.POST['starting_bid'] Bids.objects.create(bid_value=starting_bid, bidder=self.request.user, item=self.object) return super().post(request, *args, **kwargs) But it returns the error Generic detail view ListingCreateView must be called with either an object pk or a slug in the URLconf. The docs say that "When using CreateView you have access to self.object, which is the object being created. If the object hasn’t been created yet, the value will be None." When using a CreateView, when would self.object contain the object being created? How would I work with the object that has just been created in a CreateView?