Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which database is best for python? [closed]
I am confusing to choose the database. Mysql or mongodb or sqllite -
In django, how to annotate(group by) date from a datetime field with MYSQL
Defined as class Data(models.Model): created_at = models.DateTimeField(default=timezone.now) number = models.IntegerField(default=1) And the requirement is to get sum group by date from created_at and I was using. qs = Data.objects.values('created_at__date').annotate(sum=Sum('number')) The above query works fine with sqlite3, but it failed with MySql. In MySql, it returns single result <QuerySet [{'created_at__date': None, 'sum': 100}]> Excepted: <QuerySet [ {'created_at__date': datetime.date(2021, 7, 12), 'sum': 50}, {'created_at__date': datetime.date(2021, 7, 13), 'sum': 50} ]> -
How to access properties of one-to-Many relationships in Django templates?
I am very new to Python & Django. I am building a personal diary with pretty simple properties such as Months and Entries. models.py class Month(models.Model): id = models.AutoField(primary_key=True) month_name = models.CharField(verbose_name="Month", max_length=20, unique=True) year_number = models.IntegerField(verbose_name="Year") featured_img = models.ImageField(verbose_name="Featured", upload_to='diary/featured_img', default=False) class Meta: verbose_name = "Month" ordering = ['-year_number', 'month_name'] def __str__(self): return '%s, %s' % (self.month_name, self.year_number) class Entry(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField() month = models.ForeignKey('Month', on_delete=models.RESTRICT, null=True) img = models.ImageField(verbose_name="Image", upload_to='diary/entry_img', default=False) date_created = models.DateTimeField(verbose_name="Date", default=timezone.now) def __str__(self): return self.title class Meta: verbose_name_plural = "Entries" ordering = ['-date_created'] I am trying to build a simple webpage which displays the Months in list form and when I click on the month I get the entries in detail view. I completed the first step but I cannot figure out how to access the one-to-many relationships between Month and Entry model in Django templates. What I want to do is to display a page with all the Month model objects and when a user clicks on a specific month say "December", Django returns all the entries which have the month object defined as December. This worked fine in the admin site where I inserted TabularInLine … -
Is it correct to use Celery in Kafka Consumer?
I am doing some long-running tasks in Kafka Consumer. I want to know that I am doing right or wrong? I am using Kafka Consumer to consumer messages from another server and messages are processing as I want. I am putting the received message in the Celery queue. And all is working well. Does Here need Celery? Or Kafka will handle it as a queuing system? _consumer = KafkaConsumer(KAFKA_TOPIC, bootstrap_servers=['{}:{}'.format(HOST, PORT)],auto_offset_reset="earliest", value_deserializer=lambda x: ReadHelper().json_deserializer(x), group_id="mygroupZ1") for msg in _consumer: payload = msg.value print("data fetched payload------------------") long_running_task.delay(payload) # Does here need Celery task to put in? -
Cannot send javascript post data to django view
I have a function in javascript in which I am trying to a very simple key value pair of data through a post request into the same view in which the webpage is rendered from. I have a form in the same template/webpage HTML that is able to send post data to the view just fine, however the javascript is unable to do so and I am left with null data in the view. Javascript: ` postAccount(); async function postAccount() { accountPromise = getAccount().then(accounts => { return accounts[0]; }) //This function call to retrieve the account will be put here until I can figure out a way to //pull the address with the user pressing login ONLY IF the the user has already connected theyre metamask. account = await accountPromise; var data = new FormData(); data.append("address", account.toString()); console.log("address=" + account.toString()); let post = new XMLHttpRequest(); post.open("POST", "{% url 'index' %}", true); post.setRequestHeader('Content-Type', 'application/json'); post.send(data); } Django view: @csrf_exempt def index(request): context = {} usernameInput = None; address = None; if (request.method == 'POST'): usernameInput = request.POST.get("username_input") address = request.POST.get("address") print(usernameInput, address) if (usernameInput != None and address != None): user = generalUser(address = str(address), username = usernameInput, lastLogin = timezone.now()) … -
User data not updating in admin panel and forms django
When I try to update user data (in admin panel or form) it does nothing and give 0 errors. In the admin panel, it says it updated, but data stays the same. Here's my model.py: https://pastecode.io/s/jx4jpt0x -
Multi file upload with other info in Django Rest Framework
I am going to create multi file upload api in django rest framework. Each file has file description field. So I need to upload bulk files and files description data at the same time. files = request.FILES.getlist('files[]') files_description = json.loads(request.data.get('files_description')) I can create File model instances by looping files_description. The issue is, file field is optional. So above files, files_description length can be different, since file field can be optional. How can I match file field and file description? -
How should I handle package dependency conflicts, especially in Django?
I've been trying to implement BERTopic inside my Django project. However, the dependencies of BERTopic conflicts with my existing numpy version: When I run !pipdeptree -p bertopic in jupyter notebook, I get this output: * tensorflow-gpu==2.3.0 - numpy [required: >=1.16.0,<1.19.0, installed: 1.21.6] I was trying to use BERTopic in views.py More than wanting to solve this specific issue with numpy, I would like to know how to solve any conflicts between package dependencies. -
I don´t get to see my mistake. Why do I get this error? raise RequestsJSONDecodeError
......................... ....................... ...................... When I execute, python py_client/details.py, I get: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) What´s going wrong here? detail.py import requests endpoint = "http://localhost:8000/api/products/1" get_response = requests.get(endpoint) print(get_response.text) this is urls.product from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.ProductDetailAPIview.as_view()), path('', views.ProductCreateAPIview.as_view()), ] I am getting error Expecting value: line 1 column 1 (char 0) It doesn´t work in the browser either. It says: Page not found (404) this is urls.cfehome from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("new_api.urls")), path('/api/products/', include("products.urls")) ] this is my view in the app products from rest_framework import generics from .models import Product from .serializers import Productserializers class ProductDetailAPIview(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = Productserializers class ProductCreateAPIview(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = Productserializers -
Blending the rendering of DataTableView and a standard view in Django
I'm pretty new to django and have been experimenting with some of the code I want to build a form that starts with a parent record, lists the children of that record, and then when I click on a child (or a button in the row of that child) shows the children under that in a datatableview object. phew It should look a little like this: So the dataset is the primary object into the view, and the tables are a datatables filtered by the dataset id, which all works fine... but how do I get the {{ datatable }} to render in context? The current view code is pretty basic - this is initially all just for display. def datasetview(request, datasetid): dataset = get_object_or_404(DataSet, pk=datasetid) context = { 'dataset': dataset, } return render(request, 'data/dataset_view.html', context) within the html template, I render the table list with: {% for datatable in dataset.datatables.all %} {% if not datatable.deleted %} <tr> <td class="p-1 align-middle">{{ datatable.tablename }}</td> <td class="p-1 align-middle"><button type="button" class="btn btn-outline-primary" onclick="fill_attribute_table({{ datatable.datatableid }})">Edit</button></td> </tr> {% endif %} {% endfor %} I've been able to render the dataviewtable as a generic page using the demo code provided at pypi.org/project/django-datatable-view (that's how I … -
404 error while implementing async function
detail.html {% if request.user.is_authenticated %} <form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}"> {% csrf_token %} <h4> {% if request.user in review.like_users.all %} <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button> {% else %} <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button> {% endif %} </h4> </form> {% endif %} <!-js--> <script> const likeForms = document.querySelectorAll('.like-forms') const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value likeForms.forEach((form) => { form.addEventListener('submit', function (event) { event.preventDefault() const reviewId = event.target.dataset.reviewId const bookId = event.target.dataset.bookId axios({ method: 'post', url: `/detail/${bookId}/like/${reviewId}/`, headers: {'X-CSRFToken': csrfToken}, }) .then(response => { const isLiked = response.data.isLiked const likeBtn = document.querySelector(`#btn-like-${reviewId}`) console.log(isLiked) if (isLiked === true) { likeBtn.classList.add('bi-emoji-heart-eyes') likeBtn.classList.remove('bi-emoji-angry') } else { likeBtn.classList.add('bi-emoji-angry') likeBtn.classList.remove('bi-emoji-heart-eyes') } }) .catch(error => { console.log(error) }) }) }) </script> urls.py path("detail/<int:book_pk>", views.detail, name="detail"), path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"), ..... views.py def detail(request, book_pk): reviews = Review.objects.order_by("-pk") book = Book.objects.get(pk=book_pk) context = { "reviews": reviews, "book": book, } return render(request, "review/detail.html", context) def like(request, book_pk, review_pk): review = Review.objects.get(pk=review_pk) book = Book.objects.get(pk=book_pk) if review.like_users.filter(pk=request.user.pk).exists(): review.like_users.remove(request.user) is_liked = False else: review.like_users.add(request.user) is_liked = True data = { "isLiked": is_liked, } return JsonResponse(data) I got a 404 not found error while writing code for a "like" async function. data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} … -
django annotate based on another annotate create a duplicate query
I want to calculate number of group members (no_members), sum of the points of the group members(point) and average point per person(avg_point) for each group with annotation: groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate( no_members=Count('student', distinct=True), point=Sum('student__point__point', filter=point_filter), avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField())) but when I check query (groups.query) in avg_point instead of use point/no_members query is SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id) (point and no_members calculate again). query is: SELECT `study_league_studygroup`.`id`, `study_league_studygroup`.`name`, `study_league_studygroup`.`parent_id`, COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`, SUM(`study_league_point`.`point`) AS `point`, ( SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`) ) AS `avg_point`, `layers_layer`.`id`, `layers_layer`.`name`, `layers_layer`.`type_id`, `layers_layer`.`parent_id`, `layers_layer`.`created`, `layers_layer`.`default`, `layers_layer`.`lft`, `layers_layer`.`rght`, `layers_layer`.`tree_id`, `layers_layer`.`level` FROM `study_league_studygroup` LEFT OUTER JOIN `users_student` ON ( `study_league_studygroup`.`id` = `users_student`.`study_group_id` ) LEFT OUTER JOIN `study_league_point` ON ( `users_student`.`user_id` = `study_league_point`.`student_id` ) INNER JOIN `layers_layer` ON ( `study_league_studygroup`.`parent_id` = `layers_layer`.`id` ) GROUP BY `study_league_studygroup`.`id` but I want use (point / no_members) AS avg_point instead of (SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id)) AS avg_point -
What are Pharaoh, Grandmother, and Monarchy deletion patterns?
I was looking at the docs for Django CTE Trees and saw the text: Multiple delete semantics: supports Pharaoh, Grandmother, and Monarchy deletion patterns. This meant nothing to me, so I did a bit of googling - and found nothing! Does anyone know what "Pharaoh, Grandmother, and Monarchy deletion patterns" are? -
CKEditor in production not showing in admin panel
I've launched my project into production, CKEditior and CKEditor_uploader both worked on my local server but now doesn't show on my production admin panel. Any ideas why it may not be showing would be greatly appreciated. Or any alternative ways to implement richtext and image uploading to blog posts in django admin. settings.py STATIC_URL = '/static/' MEDIA_URL = '/static/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static/images/') STATIC_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static') CKEDITOR_UPLOAD_PATH = "uploads/" urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('martinhensonphotography.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) models class Topic(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField() def __str__(self): return self.title class BlogPost(models.Model): blog_title = models.CharField(max_length=255) blog_article = RichTextField(null=True, blank=True) blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") def __str__(self): return self.blog_title admin from django.contrib import admin from . models import PostImage, EnterImage, BlogPost, Topic # Register your models here. admin.site.register(PostImage) admin.site.register(BlogPost) admin.site.register(EnterImage) admin.site.register(Topic) -
django DenseRank annotation based on another annotate
I want to annotate rank queryset based on avg of points. annotate(avg=Avg('point'), rank=Window(expression=DenseRank(), order_by=Value("avg").desc()) but rank is 1 for all data. When I check query straight in database result is true! but in django all rank is 1. When I use F("avg") instead of Value("avg"), result is true but query is not optimal . With F() in query once calculate average of points for avg and calculate avg again for rank avg: query 1: SELECT AVG(point) AS avg, DENSE_RANK() OVER ( ORDER BY AVG(point) DESC ) rank, but I want below query: query 2: SELECT AVG(point) AS avg, DENSE_RANK() OVER ( ORDER BY avg DESC ) rank, when I user Value('avg') query 2 generate but all rank is 1 and when I use F('avg'), result is true but query 1 generate which is not optimal and calculate 'avg' twice(twice AVG(point) in query). -
Showing data in modal
Using Django 3 i developed a page where some tasks are showed like links. If task is not finished, than the user own can edit it, but if task is finished the user can only see. The tasks color are diferents from each task depends in the status: Atrasada, em dia, futura. The purpose is click in a task and open a modal with data from that task, but i dont know how to transfer data from main page to modal. I have no idea what to do. There is a way to make this using just django??? -
Django Rest Framework no read multiple records
I have tried everything on the blogs. I even consume the service with postman and multiple records are not inserted. Can you help me understand what is happening? There are no errors thrown by the code. Only one record is inserted. My code in DJANGO class ProviderListSerializer(serializers.ListSerializer): def do_stuff(data): return data def create(self, validated_data): some_data = self.do_stuff() return Provider.objects.bulk_create(some_data, ignore_conflicts=True) class ProviderSerializer(serializers.ModelSerializer): class Meta: model = Provider fields = '__all__' list_serializer_class = ProviderListSerializer class ProviderViewSet(viewsets.ModelViewSet): queryset = Provider.objects.all() serializer_class = ProviderSerializer def create(self, request, *args, **kwargs): many = isinstance(request.data, list) serializer = self.get_serializer(data=request.data, many=many) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers) My code in POSTMAN: curl --location --request POST 'http://127.0.0.1:8000/api-auth/providers/' \ --header 'Authorization: Basic YRtaW46SklFTTkzMDYMQ==' \ --form 'name="Proveedor09"' \ --form 'representante="Proveedor09"' \ --form 'alias="Proveedor09"' \ --form 'ruc="isuioasuio92"' \ --form 'mobile="48489948"' \ --form 'address="shds"' \ --form 'telefono="45546546654"' \ --form 'email="Proveedor09@mail.com"' \ --form 'activo="true"' \ --form 'name="Proveedor091"' \ --form 'representante="Proveedor091"' \ --form 'alias="Proveedor091"' \ --form 'ruc="isuioasuio921"' \ --form 'mobile="48489948"' \ --form 'address="shds"' \ --form 'telefono="45546546654"' \ --form 'email="Proveedor109@mail.com"' \ --form 'activo="true"' I just expect to insert multiple records. As I said, I've tried everything I've seen on the web. Maybe I'm sending the form-data wrong, but I see that in many … -
Sync to Async Django ORM queryset foreign key property
Very simple question: Django. Model. Has foreign key: class Invite(models.Model): inviter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='inviter') ... In async context, I do: # get invite with sync_to_async decorator, then print(invite.inviter) Get async favorite error: You cannot call this from an async context - use a thread or sync_to_async How do I handle this? -
Django retrieving data from m2m table
I am using Django default User model. I've made a relation m2m to it with model Books. Django made automaticly table in library app - library_books_user. How can I get acces to it? I want to be able to delete relations. Normally when I use not built in models i can do it like: models.BooksUsers.objects.get(book=book, user=user) importing models before. -
Not working Create Mutation in Graphql [django]
I use Django and graphql. Not working Create Mutation in Graphql. I can't understand why. Update and Delete works. But I can't create anything. class MovieCreateMutation(graphene.Mutation): class Arguments: title = graphene.String(required=True) year = graphene.Int(required=True) movie = graphene.Field(MovieType) def mutate(self, info, title, year): movie = Movie.objects.create(title=title, year=year) return MovieCreateMutation(movie=movie) and I have: class Query(api.schema.Query, graphene.ObjectType): pass class Mutation(api.schema.Mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) I'll say it again - Update and Delete mutations work. Only Create does not work. And I can't understand why. What I'm doing: mutation { createMovie(title: "TestMovie", year: 1981) { movie { title year } } } What do I always get: { "data": { "createMovie": { "movie": null } } } -
how to customize UserCreationForm in django
Hi I am trying to clean up my usercreation form using widgets but its not working. The class is not being passed 'form-control' It does however work for model form. Not sure what I am doing wrong? I am new. forms.py class ProfileForm(UserCreationForm): class Meta: model=User fields = ('email', 'avatar', 'password1', 'password2') def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class CustomerForm(ModelForm): class Meta: model = Customer fields = ['name','email','phone_number' ] widgets={ 'name' :forms.TextInput(attrs={'class':'form-control'}), 'email' :forms.TextInput(attrs={'class':'form-control'}), 'phone_number' :forms.TextInput(attrs={'class':'form-control'}), } -
Django count records with aggregate
I have field like this I want all records count with all tags for example sale = Sale.objects.using('read_rep') \ .filter(tags__name__in=['Device','Mobile']) \ .aggregate( **{total: Count('pk', for status, _ in ['Device','Mobile']} ) Device - 2 Mobile-5 It is difficult to count records with all tags because tags are being store in only one field. Any help would be Appreciated. -
Group by field in serializer for DRF
I am trying to group all my articles by category for DRF. I have the following my serializers.py: class GroupPageSerializer(serializers.ModelSerializer): sound = serializers.FileField(required=False) image = Base64ImageField(max_length=None, use_url=True) category = serializers.PrimaryKeyRelatedField( many=True, queryset=Category.objects.all()) url = serializers.CharField(allow_null=True, required=False, default=None, allow_blank=True) english = serializers.CharField(source="base", required=False, allow_blank=True) per_language = PerLanguageCondensedSerializer(many=True, required=False, read_only=True) target = serializers.CharField(required=False, allow_null=True, allow_blank=True) base = serializers.CharField(required=False) class Meta: model = Page fields = ['per_language', 'base', 'target', 'english', 'date', "json", "id", "category", "title", "image", "sound", "url", "slug"] And this in my views.py: class GroupedArticleListView(generics.ListAPIView): queryset = Page.objects.select_related().all() serializer_class = GroupPageSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) pagination_class = LimitOffsetPagination ordering_fields = ['date'] filter_class = ArticleMultiValue I have been trying writing a list serializer class, I've been trying to write various "to_representation" functions, etc. All I want is so that all of my results are grouped by category, as such: "business": [ {article1...}, {article2...} ], "technology": [ {article3...}, {article8...}, ], etc How do I do this? -
How to change the docker and nginx config to support asgi WebSocket wss in Django?
I'm working on a small Django project related to a chat where I have to use WebSocket for real0time cominucation, I deployed my project using wsgi and it was working but when i reached the point of using websockt I found myself that I have to change the configuration to asgi or something, could you please help me out This is my project architecture: -myproject -docker(folder) -certbot(folder) -proxy(folder) -nginx (folder) -default-ssl.conf.tpl -uwsgi_params -Dockerfile (file2) -Dockerfile (file1) -Docker-compose-delpoy.yml This is my Dockerfile (file1) FROM python:3.10-alpine3.16 ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN apk add --upgrade --no-cache build-base linux-headers && \ pip install --upgrade pip && \ pip install -r /requirements.txt COPY app/ /app WORKDIR /app RUN adduser --disabled-password --no-create-home django USER django CMD ["uwsgi", "--socket", ":9000", "--workers", "4", "--master", "--enable-threads", "--module", "myproject.wsgi"] This is my production Docker-compose-delpoy.yml version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql environment: - POSTGRES_DB=xxx - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xx app: build: context: . restart: always volumes: - .:/app environment: - DJANGO_DEBUG=0 - POSTGRES_NAME=xxx - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xxx - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - DJANGO_ALLOWED_HOSTS=${DOMAIN} depends_on: - db redis: image: redis:alpine proxy: build: context: ./docker/proxy restart: always depends_on: - app ports: - 80:80 - 443:443 volumes: - certbot-web:/vol/www - … -
How to get same search result if i filter a value with hyphen or without hyphen or with white spaces in queryset field?
I need to get the same result when i search a word with or without a hyphen as well as white space in django queryset field.What should i do to satisfy this.