Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
channels_presence.models.Presence runtimeError
its my first time implementing a Websockets with Django and I'm struggling to do this. I keep getting this error everytime I try to runserver: RuntimeError: Model class channels_presence.models.Presence doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'votemanager', 'roommanager', 'rest_framework', 'multiselectfield', 'django_filters', 'channels', ] CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } Can someone help me? -
How use uuid as primary key and slug for url in Django App?
I defined uuid to as primary key for my model and url. Now we want to use slug in the url, but we have a production database and the objects are using their uuid as id. Instead of modify the database type for the primary key (postgres), is posible to keep the primary key as uuid and use slug for the url? model.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(null=True) urls.py urlpatterns = [ path("", Article.as_view(), name="article_list"), path("<slug:slug>", ArticleDetail.as_view(), name="article_detail"), ] template <a href="{% url 'articles:article_detail' article.slug %}">{{article.title}}</a> This configurations is giving me a ValidationError with ['“my-slug” is not valid UUID.'] Thanks -
Need to confirm this ER diagram of simple transfermakt like databse to use in django
I'm creating a simple transfermarkt like database to use in django but I think I have the wrong ER relations, would love some help if possible. This is what I have (not complete): ER Diagram Also, I'm using this tool: http://onda.dei.uc.pt/v3/ -
What is the most similar framework to Django in java [closed]
What I liked most about Django was the built in admin page, built in database manager, simplicity of creating dynamic websites, and built in authentication, although the admin page and database manager aren't a must. -
Django/Python - Datapicker and data from server
I've been trying for a while to figure out how to make a data picker that uses moment.js (website: http://www.daterangepicker.com), and connect it to my database which is displayed by a table, and the data is displayed from the server as a loop, and for no reason I can't get it to work. Maybe it just can't be done, I don't have the strength anymore, so I'm asking here if someone could help me how it can be done. I need to make a "datapicker" which will have a range selected by the client, and will automatically filter the database, and display the table only with rows that meet the query. test-table.js import moment from "moment"; $(document).ready(function() { $(function() { var start = moment("2022-01-01 12:34:16"); var end = moment("2022-03-03 10:08:07"); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); }); $('#reportrange').on('apply.daterangepicker', function(ev, picker) { var start = picker.startDate; var end … -
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?