Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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: … -
I can't figure out the Reverse for 'cart_add' with arguments '('',)' not found error. 1 pattern(s) tried: ['cart/add/(?P<product_id>[0-9]+)/\\Z']
There is a form in the product detail view template that doesn't work and throws an error. Here is my code: cart/cart.py from decimal import Decimal from django.conf import settings from TeaYardApp.models import Products class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() product = Products.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in product: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.save() cart/Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from TeaYardApp.models import Products from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Products, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data … -
I am trying to deploy my website on Pythonanywhere.com but I having "ModuleNotFoundError". How do I debug?
Error running WSGI application ModuleNotFoundError: No module named 'starclone' File "/var/www/wholes_pythonanywhere_com_wsgi.py", line 16, in application = get_wsgi_application() -
Django ModelForm not displaying Model Verbose Name
I am trying to get my Django ModelForm to label my select dropdown boxes with the Model verbose names. According to the DjangoModel Form documentation "The form field’s label is set to the verbose_name of the model field, with the first character capitalized." # model.py class StLouisCitySale208(models.Model): landuse = models.CharField(max_length=254, blank=True, null=True, verbose_name="Land use") neighborho = models.CharField(max_length=254, blank=True, null=True, verbose_name="Neighborhood") # form.py class StLouisCitySale208Form(ModelForm): required_css_class = 'form-group' landuse = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('landuse', flat=True).distinct()) neighborho =forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('neighborho', flat=True).distinct()) policedist = forms.ModelMultipleChoiceField(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'] -
Django Template: Dynamic template variable inside another variable
I hope this makes sense... I am building a crypto asset list page (easy); however, in the {% for %} loop I would like to include a variable inside a variable. Showing the code will make more sense: Tempalte.html {% for crypto_asset in objects__list_cryptoAssets %} <tr role="row" class="body-row"> <td role="cell">{{ api_external_prices.bitcoin.usd }}</td> </tr> {% endfor %} So the {% for %} loop grabs all the crypto assets and then I can use Django template {{ asset_class.slug }} to grab all slugs... nothing exceptional here. This variable {{ api_external_prices.bitcoin.usd }} grabs external USD prices for Bitcoin, {{ api_external_prices.bitcoin.eur }} prices in EUR, and so forth... nothing exceptional here either. Here is where the question comes :: the idea would be to have something like {{ api_external_prices.{{ asset_class.slug }}.usd }}... so each crypto would have its own price FX fetched correctly. Is it possible to have a variable inside a variable? -
Django Subquery Sum with no results returns None instead of 0
I have a Django Subquery which returns a Sum. If the subquery finds at least one result, it works fine. But, if the subquery finds no records, it returns None which then causes any other calculations using this result (I use it later in my query in an F expression) to also result in None. I am trying to Sum all non-null 'consumed' values - sometimes, they are all null and therefore there are no rows upon which to sum. I would like this to result in a 0 instead of None ... annotate(tapx=Subquery(InvTrx.objects.filter(job=OuterRef('job')).\ filter(consumed__isnull=False).\ filter(inventory__inv_type='APX').\ values('job__job').\ annotate(tot_cons=Sum('consumed', default=0)).\ values('tot_cons') )).\ ... I've tried Coalesce with and without Value(0) annotate(tot_cons=Coalesce(Sum('consumed', default=0)), 0).\ annotate(tot_cons=Coalesce(Sum('consumed', default=0)), Value(0)).\ the value of tapx (which I reuse in F expressions in another part of the query) = None if no rows are returned. If at least one row is returned, this works fine. If no rows are returned, I would like the value of tapx to be 0 instead of None so that the value of fg_total in the following annotation results in a number and not None: annotate(fg_total=F('fg') + F('tapx')) Doing this outside a subquery, I have used "or 0" to force the value … -
Best Project Structure for Multisite (subdomain) in Django
We want to develop the software to be used in our university with Django. For web site we have one main domain and 150 subdomains. Please share your ideas and suggestions for the right project structure. For example, we will keep all our apps in a folder called apps. Do I need to do anything for the wsgi.py, settings.py and urls.py files of each subdomain? Best regards. -
Django Rest Framework Tests Failing When Using PostgreSQL
I'm new to Django and I recently changed the database from SQLite to PostgreSQL (first time using postgreSQL). I updated the settings with the below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost' } } For the user, I'm not using the default postgress user, instead I created a new user (for which there is a User account on the OS) and added a password for it. I then gave that user permission to createdb: ALTER USER username CREATEDB; I've also installed psycopg2. When using the api normally, the PostgreSQL database updates just fine and works as expected. Originally when using SQLite, all the tests used to pass too. But when I changed to PostgreSQL using the above, 2 out of 9 tests fail. These are the tests that fail. The tests that fail are all under the same class. 6 of the tests are under a different class and they all pass fine. class APIDetailTest(APITestCase): items_url = reverse('site') item_url = reverse('site-item', args = [1]) def setUp(self): # Creating an initial entry to be tested. data = { "Name": "data name", "Description": "desc", "Date": "2022-06-11", "Time": "11:00:00", "Tag": "", } self.client.post(self.items_url, data, format='json') … -
How to use Admin Model as foreign key in django?
I try to develop a relationship as One admin can add one or many subscription plans. I try this but not worked from django.db import models from django.contrib import admin class SubscriptionPlansModel(models.Model): title = models.CharField(max_length=50) price = models.IntegerField() duraion = models.IntegerField() admin = models.ForeignKey(admin,on_delete=models.CASCADE) -
Problem in loading the logo in different URLs in Django
I have the same html for Tools.html and home.html but I realized the logo can be loaded in this URL: path('',views.home), But in this URL I do not see the logo and also the favicon: path('Tools/', views.Tools ), http://127.0.0.1:8000/ http://127.0.0.1:8000/Tools/ views: def Tools(request): p=product.objects.filter(category__name='Tools') return render(request,'Tools.html',{'p':p}) def home(request): p=product.objects.filter(category__name='home') return render(request,'home.html',{'p':p}) urls: urlpatterns = [ path('Tools/', views.Tools ), path('',views.home), ] the following codes are for favicon and logo in html file: <link rel="icon" type="image/x-icon" href="static/logo.png"> <img class="img" width="270px" src="static/logo.svg"> Why is this happening? -
Django - React - Google Cloud Storage SigedURL upload is not working
I have used signedURL with jquery/ajax and Django for uploading to Google Cloud Storage previously successfully. However with the Django - React setup I have not been able to establish a successful. upload yet. export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => { let resultState = { state: '', data: {} }; let config = { method: 'HOST', url: signedurl, headers: { 'Content-Type': 'video/mp4', "Access-Control-Allow-Origin": "*", 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS' }, data: form_data }; await axios(config).then(function (response) { console.log(JSON.stringify(response.data)); resultState.state = 'success'; }).catch(function (error) { resultState.state = 'error'; resultState.data.message = error.message; window.toastr.error(error.message); console.log(error) }) return resultState; } export const CreateAssets = async (data, key) => { let resultState = { state: '', data: {} }; await axios.get(`https://origin/asset/create/?category=1&title=%22` + data[key].title + `%22&size=1`) .then(res => { resultState.state = 'success'; resultState.data = res.data; }).catch((err) => { resultState.state = 'error'; resultState.data['message'] = err.message; }) return resultState; } The code for react js get singed url and calling signedurl with the file dialog is available. What shall I do for a succesful signedurl file upload to Google Cloud Storage ? -
Mypy complaining about Name "Optional" is not defined without the use of Optional
I've recently started using mypy, and have run into some weird problems that i cannot for the life of me seem to figure out. I'm using mypy 0.950, django-stubs 1.11.0, django 4.0.5 and python 3.10.2. Running mypy through the command line returns this: project/suppliers/models.py:6: error: Name "Optional" is not defined project/suppliers/models.py:6: note: Did you forget to import it from "typing"? (Suggestion: "from typing import Optional") project/users/models.py:6: error: Name "Optional" is not defined project/users/models.py:6: note: Did you forget to import it from "typing"? (Suggestion: "from typing import Optional") project/products/models.py:6: error: Name "Optional" is not defined project/products/models.py:6: note: Did you forget to import it from "typing"? (Suggestion: "from typing import Optional")(Suggestion: "from typing import Optional") However, line 6 in project/suppliers/models.py is completely empty: from django.contrib.sites.managers import CurrentSiteManager from django.contrib.sites.models import Site from django.db import models from django.utils.text import slugify from django.utils.translation import gettext_lazy as _ from django_countries.fields import CountryField from project.core.models import BaseImageModel, BaseModel from project.suppliers.managers import SupplierQuerySet _SupplierManager = models.Manager.from_queryset(SupplierQuerySet) class Supplier(BaseModel, BaseImageModel): ... Line 6 in project/users/models.py is a django import from django.contrib.contenttypes.models import ContentType: import random from typing import Any from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.contrib.contenttypes.models import ContentType from django.contrib.sites.managers import CurrentSiteManager from django.contrib.sites.models …