Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I update my customuser table when user is created by django-allauth social login?
I've integrated django-allauth google and facebook login successfully but I'm having problem with my custom user model I want to update is_customer field in to True in my user model here is my user model class UserManager(BaseUserManager): def create_customer(self, email, phone=None, password=None, **extra_fields): '''Creates and saves a new user''' if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.phone = phone user.set_password(password) user.is_customer = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): '''Custom user model that supports using email instead of username''' phone = models.CharField(unique=True, max_length=15, null=True) email = models.EmailField(max_length=255, unique=True) fname = models.CharField(max_length=255, default='None') lname = models.CharField(max_length=255, default='None') is_customer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] this how my signup page looks in my signup page I've facebook, google, and normal signup form for user who don't have account on both. I think is there any way I can override django-allauth socialaccount model. One thing I forgot to mension that facebook and google login proccess handled by django-allauth forms so they don't call my User.objects.create_customer() method is there way to call this method so it will become easy for … -
django: how to make query be not lazy executed?
I have problem with query lazy execution in my custom Manager method. In it i want to separate query by model CharField choices and return dict[choice, QuerySet]. model.py part: ... PRODUCT_STATUS = [ ('pn', 'Запланировано'), ('ga', 'В процессе (Ознакомляюсь)'), ('rv', 'Повтор'), ('ac', 'Завершено'), ('ab', 'Брошено'), ('pp', 'Отложено'), ] class ExtendedManager(models.Manager): def separated_by_status(self, product_type): query = super().get_queryset().all() dict_ = {} for status in PRODUCT_STATUS: dict_.update({status[1]: query.filter(status=status[0]).all()}) return dict_ ... views.py part with manager use: ... class ProductListView(ContextMixin, View): template_name = 'myList/myList.html' def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: product = kwargs.get('product') if product not in {'film', 'game', 'series', 'book'}: raise Http404 context = self.get_context_data() context['title'] = f'Список {product}' context['dict_queryset'] = Product.objects.separated_by_status(product) return render(request, self.template_name, context) ... django debug toolbar result: here The problem is that the query is lazy executed in the manager, but in templates it is already fully executed for each PRODUCT_STATUS element separately. How cat it be optimized to execute 1 time? I'm very sorry if I use the term "lazy" incorrectly. -
Send data to database via fetch and subsequently display this data to html page via fetch again without submitting form or refreshing the page
I have a django app. I'm typing a comment in a form and I'm sending it to my database via fetch. my js code document.getElementById("comment-form").onsubmit = function write_comment(e) { e.preventDefault(); const sxolio = document.getElementsByName("say")[0].value; fetch('/comment', { method: 'POST', body: JSON.stringify({ say: sxolio }) }) .then(response => response.json()) .then(result => { //print result console.log(result); }); my views.py @requires_csrf_token @login_required(login_url = 'login')#redirect when user is not logged in def comment(request): if request.method != 'POST': return JsonResponse({"error": "POST request required."}, status=400) new_comment = json.loads(request.body) say = new_comment.get("say", "") user = request.user comment = Comment( user = user, say = say, photo = Userimg.objects.get(user = user).image ) comment.save() return JsonResponse({"message": "Comment posted."}, status=201) Next thing i wanna do is to display this comment and all the other data from my db, to my html page without refreshing.The moment i push the post button i want the comment to be dispayed. I dont want to update the page with some element.innerHTML = data. my js code function display_comments() { fetch('/all_comments') .then(response => response.json()) .then(all_comments => { do some stuff my views.py @login_required(login_url = 'login')#redirect when user is not logged in def all_comments(request): all_comments = Comment.objects.order_by("-date").all() print(all_comments[0].serialize()) return JsonResponse([comment.serialize() for comment in all_comments], safe=False) If i … -
Template File not found
So I am trying to open a template from... But the template file is not shown as below... from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "home/index.html") Weird thing is that my webpage still works, and when I delete that function it does not. Here is some additional Info... settinbgs.py # Application definition INSTALLED_APPS = [ 'project_long_page', 'about', 'home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] home/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] -
Django Processing Bar between two requests
I have a calculation-intensive application, it takes inputs and processes about 10-15 formulas on the inputs including NPV, IRR-like calculations. I am implementing the calculations using template tags in django. Below are the code snippets : [filters.py][1] @register.filter def **client_irr**(value,arg): fcf_list = [] for i in arg: fcf_list.append(fcf(value,i)) return round(npf.irr(fcf_list) * 100,2) [inputs.html][2] <div class="products-row"> <div class="product-cell price">{{ i.parameter }}</div> <div class="product-cell price">{{ i.units }}</div> <div class="product-cell price">{{ i.values|**client_irr:**total_time}}</div> </div> There are a lot of calculations like these!! I am implementing these calculations correctly? I am not sure, I find this way completely wrong! The request for (/inputs) calculating the values takes about 20-22 seconds and the UI gets stuck, this creates a very user experience(UX). So, I am looking for either a processing bar(which I am unable to get a good tutorial in Django) or a way to optimize these calculations. Thank you, folks!! It means a lot! If you have any solutions please help! -
Django - Geting fields by values_list in queryset
I have trouble getting values by values_list(From what I've read it is supposed to this) from my db in django: stocks_query = Indexes.objects.filter(Symbol=index).values("Date","Open", "High", "Close", "Low","Volume") print(stocks_query.values_list("Date", flat=True)) Every time I get QuerySet object <QuerySet [datetime.date(2021, 12, 28), datetime.date(2021, 12, 27), datetime.date(2021, 12, 26), datetime.date(2021, 12, 24)... -
Django Image Form upload & update is not working properly?
models.py class ProductVariantsImages(DateTimeModel): product_variant = models.ForeignKey(ProductVariants, on_delete=models.CASCADE, related_name='product_variants_images') display_image = models.ImageField(upload_to='product_images/', null=True) item_image1 = models.ImageField(upload_to='product_images/', null=True) item_image2 = models.ImageField(upload_to='product_images/', null=True) item_image3 = models.ImageField(upload_to='product_images/', null=True) def __str__(self): return str(self.product_variant) forms.py class ProductVariantsImagesForm(forms.ModelForm): class Meta: model = ProductVariantsImages fields = ('display_image','item_image1','item_image2','item_image3') views.py if request.method == "POST": print(request.POST) item = ProductVariants.objects.get(item_num=pk) product_id=item.product_id admin_user = CustomUser.objects.get(id=request.user.id) product_variant = ProductVariantsImages.objects.filter(product_variant=item) product_form = AdminProductForm(request.POST, instance=product_id) item_form = ProductVariantsForm(request.POST, instance=item) variant_images_form = ProductVariantsImagesForm(request.POST,request.FILES,instance=product_variant[0]) if product_form.is_valid(): product = product_form.save(commit=False) vendor = request.POST.get('vendoruser') vendoruser = CustomUser.objects.filter(id=vendor) product.vendoruser = vendoruser[0] product.save() if item_form.is_valid(): item = item_form.save(commit=False) item.save() if variant_images_form.is_valid(): --------> #Problem comes here variant_image = variant_images_form.save(commit=False) variant_image.save() return redirect('loomerang_admin:loomerang_admin_products') I am getting the form details correctly. When I am updating the details is all worked fine. I have four image inputs. When I update the single image file input in the template, the other image fields were also updated. how to do this correctly? -
Does Django Rest Framework have a built in solution for a Validation API?
By Validation API, I mean an API that simply takes in a field and a field type, and returns the validation result, without attempting to create, update, or delete anything. Rough Example I would want a request like this curl -X POST /api/validation -H 'Content-Type: application/json' -d '{"type":"email","value":"invalid.email@@com"}' To return a body like this: { 'Enter a valid email address.' } Use Case Let's say you have a decoupled frontend and backend, and the backend is an API using the Django Rest Framework. In the frontend you may have a sign up flow that has several pages. Page 1: user enters an email, and we check if it's valid Page 2: user enters a phone number, and we check if it's valid Finally, create a user with those fields In this flow, it would be useful to validate the email and phone number with the backend at separate times without attempting to create a User first. You wouldn't want to create a partial user with just an email, and then later patch that user to update the phone number field, because --- well because you just wouldn't want to. Why not take care of the validation in the frontend? Because … -
How Database should I use for django other than django admin?
After making a whole project, when deploying it in the heroku server, I came to know that heroku doesn't accept sqlite3 database. So what should I do? Will I change the database or will I change the hosting site? But I cannot find a good free hosting site. Please someone suggest what to do? -
Django OAuth2 Toolkit implementation authorization call returns login page html
I am new with the Django OAuth2 Toolkit (and relatively new with Django still) and am trying to implement it with an already existing API (DRF). Up until now, the authorization of the API has worked through a static token that is passed through along with the request. On the website itself, users are able to login and session authentication is enabled. I installed the toolkit as per the instructions and have created an authorization code application with the 'skip authorization' toggle ticked. I am now trying to access the authorization server with the following URL (as a GET): http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=client_1&redirect_uri=http://127.0.0.1:8000/trial&code_challenge=WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U&code_challenge_method=S256&scope=read&client_secret=secret_1 When I try to call this (via postman, API or browser) I get back the login page instead of the code as expected. I do not understand why this is happening and how to skip this. Any ideas or help would be much appreciated! -
django channels fetch data from db and send over websocket
error: File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /ws/test/ [127.0.0.1:63954] comsumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer from random import randint from api.models import Asset class WSConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() res = list(Asset.objects.filter(id=56).values('token_id')) await self.send(json.dumps(res)) here is the code i am using for websocket. here i am fetching data from database but getting above error please take a look what will be the error ? -
How to write API test case for generic views in DRF?
Here I'm writing some TestCase for some queryset to view in api and getting error not a valid function or pattern name. I didn't get any idea what missing here! Is there any solution for this? views.py class StudentView(generics.ListAPIView): queryset = StudentDetails.objects.raw('SELECT * FROM collegedetails.college_studentdetails LIMIT 3;') serializer_class = StudentDetailsSerializers test_views.py from rest_framework.test import APITestCase from rest_framework.reverse import reverse from rest_framework import status STUDENT_URL = reverse('student/') class StudentsDetailsTest(APITestCase): def test_details(self): response = self.client.get(STUDENT_URL, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) college/urls.py urlpatterns=[ path('student/',views.StudentView.as_view(), name='student'), ] django.urls.exceptions.NoReverseMatch: Reverse for 'student/' not found. 'student/' is not a valid view function or pattern name. Ran 1 test in 0.000s FAILED (errors=1) -
"ValidatioError: Value ... is not a valid choice" in Django even with a valid choice
I have a model with a object_type field where the choices should be numbers and the human readable a string like below: OBJECT_TYPES = ( (0, "analog-input"), (1, "analog-output"), (2, "analog-value") ) class MyModel(models.Model): object_type = models.CharField( max_length=20, choices=OBJECT_TYPES, blank=True, null=True ) However, when I try to create an object and assign an integer value to object_type I get a ValidationError that the object_type is not a valid choice and I can't understand how to configure it properly. I have tried with CharField, TextField and IntegerField. obj = MyModel.objects.create(object_type=2) obj.full_clean() ValidationError: {'object_type': ["Value '2' is not a valid choice."]} -
Django ORM taking 10x more time than raw sql for same query
I am trying to fetch around 1000 records from postgress using django ORM and that takes ~1.3sec, but the same with raw sql queries takes 1/10 of the time i.e. ~ 130ms ? Is there any way to speed things up? -
Django – Migrate a field from a child model to its parent model – Manual migration for inheritance leads to a `FieldError`
Short version I'm trying to run a custom migration (via RunPython) that involves an inherited model, say Restaurant. However a FieldError exception is raised at Restaurant.objects.all(), specifying that an inherited field cannot be resolved. Indeed the model returned by apps.get_model("myapp", "Restaurant") oddly does not inherit from the parent class. Longer version Context Consider a Django multi-table inheritance where a model, say Restaurant(address, serves_pizza), inherits from a parent model, say Place(name). The fields for both models are indicated between brackets. The goal is to transfer a certain Restaurant field, say address, to the parent class Place. One challenge is to preserve the data by transferring it through a customized migration operation. One idea that I feel is rather straightforward is first create an intermediate field address_place in Place, then, manually move the data from Restaurant.address to Restaurant.address_place (via migrations.RunPython) finally remove address field and rename address_place into address Focusing on 2., here is what the custom code called by RunPython looks like: def transfer_address_from_restaurant_to_place(apps, schema_editor): Restaurant = apps.get_model("myapp", "Restaurant") for restau in Restaurant.objects.all(): restau.address_place = restau.address restau.save() FieldError, the unexpected error However when running the corresponding migration, a FieldError exception is raised and looks like: FieldError: Cannot resolve keyword 'name' into … -
Django: How to update a class attribute of an invalid form field to display error messages in Bootstrap 5?
When I use server-side validation in Bootstrap 5, I need to add an .is-invalid class to the input form field with an error to display it in div with class="invalid-feedback". To update a class attribute of a form field in Django I can do this, as stated in the docs: class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'special'}) self.fields['comment'].widget.attrs.update(size='40') But I cannot figure out how to add .is-invalid to the form field when the form is returned invalid. I have found this in the docs, but it doesn't work. -
Add html code if the element is first in query - Django
In the Bootstrap slider, the first element has the value "active", how to check and add this value to the html code for the queryset, if element is first. Example (which is not working): {% for obj in query %} <div class="carousel-item {% if query|first %}active{% endif %}"> [...] </div> {% endfor %} *this gives activity for all items, not just the first. Expected result is only for first. -
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' with Django + react + load balancer
I have the following in the settings.py ALLOWED_HOSTS = ['http://64.227.106.224', 'http://143.198.246.160',] CORS_ALLOWED_ORIGINS = ['http://64.227.106.224', 'http://143.198.246.160',] CSRF_TRUSTED_ORIGINS = ['http://64.227.106.224', 'http://143.198.246.160',] CORS_ORIGIN_WHITELIST = ['http://64.227.106.224', 'http://143.198.246.160',] INSTALLED_APPS = ['corsheaders',] MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',] I deployed a load balancer and used react on digital ocean. The error I get is Access to XMLHttpRequest at 'http://64.227.106.224/api/analyze_im/' from origin 'http://143.198.246.160' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. Can someone please point out what is the issue? -
How to active subindex button in django using jinja2 or js?
I am trying to active(highlight) sub-index on a page in Django. Click here to see the sample image Here is my files home.html <div class="col-md-2 text-left" id="subIndex"> <br><br> <h5 class="text-primary">CATEGORIES</h5> <!-- <a href="/" class="abc btn btn-outline-success my-1 " style="width: 100%; text-align: left;">All Products </a> --> <a href="/" class="abc btn btn-outline-success my-1 " style="width: 100%; text-align: left;">All Products </a> <!-- Here href="/?category={{category.id}}" generates the category link --> {% for category in categories %} <a href="/?category={{category.id}}" class="btn btn-outline-success my-1 {% if category.id in request.get_full_path %} active {% endif %}" style="width: 100%; text-align: left;">{{category}} </a> {% endfor %} </div> urls.py from django.urls import path from home import views urlpatterns = [ path('', views.home, name='home'), *** ] view.py from admn import models as AMODEL def home(request): categories = AMODEL.product_category.objects.all() context = { 'categories' : categories, } return render(request, 'home/home.html', context) I have tried to Javascript. But this could not work. main.js // Add active class to the current button (highlight it) let hd = document.getElementById("subIndex"); let btnss = hd.getElementsByClassName("btn"); console.log(btnss) for (let i = 0; i < btnss.length; i++) { btnss[i].addEventListener("click", function () { let current = document.getElementsByClassName("active"); if (current.length>0){ current[0].className = current[0].className.replace(" active", ""); // console.log(current[0]) } // current[0].className = current[0].className.replace(" active", ""); … -
DRF ValueError: Cannot query " ": Must be "Tag" instance
I want to add a field to a serializer that counts all occurrences of a word (a tag). the 2 relevant models in Models.py are: class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def __str__(self): return self.name or '' class Tagging(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE) resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='taggings') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) # media_type = models.ForeignKey(Gamemode, on_delete=models.CASCADE) origin = models.URLField(max_length=256, blank=True, default='') objects = models.Manager() def __str__(self): return str(self.tag) or '' def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) The Serializer I am trying to write is: class TagCountSerializer(serializers.ModelSerializer): tag = TagSerializer(read_only=True) tag_count = serializers.SerializerMethodField('get_tag_count') class Meta: model = Tagging fields = ('id', 'tag', 'gameround', 'resource', 'tag_count') def get_tag_count(self, obj): # return obj.tag.all().count() tag_count = Tagging.objects.filter(tag=obj).count() return tag_count def to_representation(self, data): data = super().to_representation(data) return data I have tried a couple of potential solutions for the get_tag_count() method, including the ones visible here but I keep getting this error "Cannot query "tag name": Must be "Tag" instance." Does anyone know how I can get around this? -
saving celery data into postgresql
I'm trying to deploy a django project that scrapes data every few minutes and updates redis cache and postgresql data. i used celery tasks and django_celery_beat to do this and it worked fine in development however when i want to automate celery worker and beat in the background and save data to postgres i get this error in logs: [2022-01-07 18:15:17,012: WARNING/MainProcess] django.db.utils [2022-01-07 18:15:17,012: WARNING/MainProcess] . [2022-01-07 18:15:17,012: WARNING/MainProcess] OperationalError [2022-01-07 18:15:17,012: WARNING/MainProcess] : [2022-01-07 18:15:17,012: WARNING/MainProcess] connection to server at "127.0.0.1", port 5432 failed: fe_sendauth: no password supplied celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_website.settings') app = Celery('personal_website') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py: from celery import shared_task from .currency_scraper import get_prices from .models import Currency from django.core.cache import cache @shared_task def update_prices(): """ Updates currency model prices using get_prices function. """ prices = get_prices() if prices: for name, price in prices.items(): try: old_price = Currency.objects.get(name=name) old_price.price = price old_price.save() cache.set(name, price, None) except Currency.DoesNotExist: Currency.objects.create(name=name, price=price) cache.set(name, price, None) I understand the error but i don't know how to authenticate to postgresql with celery. i use supervisor to run celery and … -
registering signals in Django results in "Apps aren't loaded yet." error
I keep getting the error, when trying to import signals: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I can't understand this, b/c I've used the following pattern successfully when setting up a user profile in other apps: models.py: from django.conf import settings from django.db import models class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) signals.py: from django.contrib.auth import get_user_model from django.db.models.signals import post_save from my_project.my_app.models import UserProfile def post_save_user_hander(sender, *args, **kwargs): created = kwargs.get("created", False) instance = kwargs.get("instance", None) if created and instance: UserProfile.objects.create(user=instance) post_save.connect( post_save_user_hander, sender=get_user_model(), dispatch_uid="post_save_user_handler", ) app.py: from django.apps import AppConfig class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_project.my_app' try: import my_project.my_app.signals except ImportError: pass According to the documentation, ready() is called "as soon as the registry is fully populated". Therefore, shouldn't the import of UserProfile succeed? Also, the documentation states Although you can’t import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model(). Therefore, including them at the top of signals.py which is itself imported in ready() should work, right? -
Accessing django admin panel in Angular + Django application
I am building a website using Django. Now the Angular is used too. I have used Jinja2 before, so any object creation or update was made in the Django admin panel. What is the best way to deal with them now? Is it necessary to create a component for an admin user so he could edit objects from the Angular frontend or is there a way to use Django admin panel after app deployment? What is the best approach? My application does not provide an ability for users to register, so in this case only one root user (admin) will be created. -
In Django Generic Create View Is there any way to add condition like if the item is out of stock return some error otherwise create the item?
In Django Generic Create View Is there any way to add condition like if the item is out of stock return some error otherwise create the item? -
How to perform an action according to different select option value?
I want to show the prices in selected currency from INR,USD,EUR etc. But each currency has a different api key. Plz suggest how can I change api key value based on the selected option. <select class="form-select form-select-lg mb-3 output" aria-label=".form-select-lg example"> <option onclick="getCurrency()" selected>Open this select menu</option> <option value="1">inr</option> <option value="2">usd</option> <option value="3">eur</option> </select> <script type="text/javascript"> function getCurrency() { selectElement = document.querySelector('#select1'); output = selectElement.value; if (output==2){ apidata=api2data; } else if (output == 3){ apidata=api3data; } } P.S api2data and api3data corresponding to apikeys of USD and EUR respectively.