Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Is there a way to have just one function in views and then put a lot of categories in it with just one path in URL?
Suppose the following codes are for different categories and they have to have same html file: def dsd(request): p=product.objects.filter(category__name='dsd') return render(request,'Tools.html',{'p':p}) def dad(request): p=product.objects.filter(category__name='dad') return render(request,'Tools.html',{'p':p}) def dfd(request): p=product.objects.filter(category__name='dfd') return render(request,'Tools.html',{'p':p}) def dadfd(request): p=product.objects.filter(category__name='dadfd') return render(request,'Tools.html',{'p':p}) def dasdfd(request): p=product.objects.filter(category__name='dasdfd') return render(request,'Tools.html',{'p':p}) def ss(request): p=product.objects.filter(category__name='ss') return render(request,'Tools.html',{'p':p}) def dasdfad(request): p=product.objects.filter(category__name='dasdfad') return render(request,'Tools.html',{'p':p}) def dfdfdfed(request): p=product.objects.filter(category__name='dfdfdfed') return render(request,'Tools.html',{'p':p}) def daaad(request): p=product.objects.filter(category__name='daaad') return render(request,'Tools.html',{'p':p}) def dddddd(request): p=product.objects.filter(category__name='dddddd') return render(request,'Tools.html',{'p':p}) html file: <div class="grid"> {%for p in p%} <div class='card'> <img src="{{p.image}}"></img> <p id="id">{{p.description}}</p> <a href="{{p.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{p.price}}</span> buy</button> </a> </div> {%endfor%} </div> If I go to my URLs and create different paths for each function and create separate html files with the same code inside of them, then I will be confused. Is there a way to have just one function in views and then put a lot of categories in it with just one path in URL? -
AttributeError Django & Pyinstaller (Failed to retrieve attribute INSTALLED_APPS from module...)
I'm trying to build an .exe app from my Django project using PyInstaller but I'm getting an error "AttributeError: Failed to retrieve attribute INSTALLED_APPS from module pixel.settings" I have created a project .spec file pyi-makespec -D manage.py I run this command pyinstaller manage.spec Please tell me how to solve this problem. My settings.py from pathlib import Path import os, sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'brain.apps.BrainConfig', ] 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 = 'pixel.urls' 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', ], }, }, ] WSGI_APPLICATION = 'pixel.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ … -
How to get a Django form to save every time (not just the first time it's submitted)?
I am trying to make an e-commerce site (CS50 Project 2) that allows its users to save bids on different listings through a Django form. The bid should only save if it is equal to or greater than the listing price or greater than all other bids. The code was previously working, but now the form only saves the first time it is submitted. How do I get it to save every time if it meets the requirements? views.py def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) listing_price = listing.bid sellar = listing.user bid_form = BidsForm() #code for the bid form bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() max_bid =0 for bid in other_bids: if listing.bid > max_bid: max_bid = listing.bid if request.method == "POST": bid_form = BidsForm(request.POST) if bid_form.is_valid(): new_bid = bid_form.cleaned_data.get("bid") if (new_bid >= listing_price) and (new_bid > max_bid): bid = bid_form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids." }) else: return redirect('listing', id=id) return render(request, "auctions/listing.html",{ "auction_listing": listing, "bidForm": bid_form, "bids": bid_obj }) (There … -
About disabling autocomplete in UserCreationForm
I long searched the internet and this site looking for a solution but nothing work. The problem is that in any registration form I make in Django, each time a user click on a username or password field, a list of previously entered values is shown and this behaviour is not desirable. The raw fact is that, if I directly comment this line widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), in # UserCreationForm, auth/form password1 = forms.CharField( label=_("Password"), strip=False, #widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) everything work as I want including the username. But I don't want to touch the Django UserCreationForm in auth/forms. The ideal would be subclass it, and customize it. Here what I did class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(*args, **kwargs) # prevents the form to automatically autofocus self.fields['email'].widget.attrs.pop("autofocus") self.fields['username'].widget.attrs.pop("autocomplete") #self.fields['password1'].widget.attrs.pop("autocomplete") #self.fields['password1'].widget.attrs.update({'autocomplete':'off', 'maxlength':'32'}) ... I tried it with many combinations, including with new-password, off, None, or even empty strings, everything is ignored. I repeat, the only way to not autocomplete the username and password fields is to comment the widget line in the original class, but this would be a very bad idea and, especially, it would break every time I will upgrade Django. Any other reasonable solutions? -
Django models filter by one to one model field
Imagine I have those two models: class A(models.Model): name = models.CharField(max_length=150) class B(models.Model): a = models.OneToOneField( to=A, on_delete=models.CASCADE, null=False ) location = models.CharField(max_length=100) And I want a queryset of B model to be filtered by the a.name and location, like this: select * from B join A on B.a.pk = A.pk where A.name="name" and B.location="location"; I tried this but it gives an error: query=B.objects.filter(a.name=name) -
In the div, i have placed a one word text. It is mysteriously getting unwanted space and I cannot understand why it comes
I am trying to build a portfolio website using Django. I have created a template with the following HTML code: <div class="bg-black fnt-white experience-div block brdr"> <h1 class="brdr block div-title roboto fnt-orange roboto"> Education </h2> <div class="experience-container inline-block bg-gray"> <h2 class="text-center fnt-black head-portfolio"> Lorem, ipsum. </h2> <br> <br> <p class="margin-auto txt-portfolio roboto fnt-black"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Vero nemo dolore sit perferendis qui ad hic, expedita, magnam ipsam est eligendi nulla, ipsum quasi fuga?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Modi corrupti asperiores voluptatem sit fugiat saepe doloribus suscipit rerum eum. Nulla molestiae quasi sint libero voluptate qui repellat quis eos ratione itaque! Aut deserunt labore excepturi corporis hic nostrum voluptates vero beatae facilis non amet quaerat aliquam iste eveniet natus, voluptatem aperiam veritatis, expedita incidunt quis sunt eaque saepe est totam. </p> <br> <a href="#" class="buttons read-more fnt-white">Read More</a> </div> </div> However, at the Education, the text is getting an unexpectedly large amount of indentation. With google's inspect element, it shows no margin, etc exists. However, on minimizing the browser, I notice that it aligns to the left perfectly. My CSS code: .div-title{ font-size: 40px; } .experience-container{ min-height: 100px; height: fit-content; width: 300px; margin-left: …