Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between Django normal and Async views
async def index(request): return HttpResponse("Hello, async Django!") and def index(request): return HttpResponse("Hello, Django!") -
Django: typehinting backward / related_name / ForeignKey relationships
Let's say we have the following django models: class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo) And if I use this somewhere in some other class: bar = self.foo.bar Then mypy complains: Foo has no attribute "bar" How can I make mypy happy here? -
How can I update my {% for x in list %} table with setInterval() in Django?
[NOTE] I'm really new in web development. Please consider this I can make mistakes and I can ask stupid questions. Sorry about everything. Hello, I'm trying to make a student table with Django + Ajax. But there's a problem which I really can't understand how can I implement my ajax code for each row in the table. Now, I'm taking first index of every field in my ajax code. And ajax refresh this field in tables every second. But I want to update every cell and row in every second. Also I tried to add new cell with append(). It doesn't worked because of {% for students in object_list %} I didn't understand how to add a new append() row in {% for students in object_list %} In my html, this is the table body and ajax code. infoindex.html <table class="table table-light" id="studentstable"> <thead> <tr> <th scope ="col">Numara</th> <th scope ="col">Adı</th> <th scope ="col">Soyadı</th> <th scope ="col">Yaşı</th> <th scope ="col">Cinsiyet</th> </tr> <tbody id="tbodyid"> {% for students in object_list %} <tr> <td id="num">{{students.num}}</td> <td id="first_name">{{students.first_name}}</td> <td id="last_name">{{students.last_name}}</td> <td id="age">{{students.age}}</td> <td id="gender">{{students.gender}}</td> </tr> {% endfor %} </tbody> </table> <script> setInterval(function (){ $.ajax({ url : "http://127.0.0.1:8000/studentsapi", dataType: "json", success : function (data) { … -
Django send profile picture with django channels
I am doing a chat app and I want to show the profile picture of a user every time he sends something in the chat. Here is the code: Models.py class Chat(models.Model): room_name = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) username = models.CharField(max_length=200,blank=False,null=True,unique=True) profpic = models.ImageField(upload_to='profpics/',blank=True,null=True) Consumers.py # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import * from main.models import * class ChatConsumer(AsyncWebsocketConsumer): @sync_to_async def get_profile(self): return self.scope['user'].profile async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] room = text_data_json['room'] profile = await self.get_profile() profile_pic = profile.profpic profpic = json.dumps(str(profile_pic)) print(profpic) username = text_data_json['username'] await self.save_message(message, room,username) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username':username, 'profpic':profpic } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] profpic = event['profpic'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username':username, 'profpic':profpic })) chat.html .... chatS.onmessage = function(e){ const data … -
Is it possible to get the payload data of a JavaScript socket io and print it using Django?
I have this JavaScript project that uses socket io and console the data. const = generateMockData(deviceId); console.log(payload) io.of("/").emit("data", JSON.stringify(payload)); And this is the generated mock data function generateMockData(deviceId) { const contaminants = [ { id: 9, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, { id: 10, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, { id: 14, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, { id: 15, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, ]; in my console it looks like this contaminants: [ { id: 9, ave: 5.4897571, ave_reduction: 0.5 }, { id: 10, ave: 5.4942647, ave_reduction: 0.7 }, { id: 14, ave: 5.316183, ave_reduction: 0.5 }, { id: 15, ave: 5.0806739, ave_reduction: 0.9 } ], is it possible to pass this payload data (console data) to Django? I tried using httpresponse in Django but it's not getting the data I want. The javascript and the django are in different projects. from … -
how to deploy django app on AWS windows server instance
thanks in advance. I want to deploy django app on aws having windows instance, gone through many doc and video but all are showing with ubuntu and linux machine. please provide any suggestion or right approach for doing this, your suggestion is vital.. Thank You -
Forbidden (CSRF cookie not set.): /api/signinUser
The error occurs in this react code const headers = new Headers({ "X-CSRFToken": Cookies.get('csrftoken') }); const response = await fetch("api/signinUser", { method: "POST", headers: headers, body: formData }); Trying to access this Django Api @ensure_csrf_cookie def signin(request): if request.method == 'POST': auth = False username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print("Authenticating User", user) if user is not None: auth = True login(request, user) # Does this return anything? ret = { "auth": auth } print("RET", ret) return JsonResponse(ret) I have django.middleware.csrf.CsrfViewMiddleware in my MIDDLEWARE variable I'm running my Django server in an AWS EC2 instance that I access with http://<my public ip>:8000/ -
Vue, How to control HTML attr by Vue Js
I made a web page through Django and Bootstrap. And now I'm using vue to change the code. However, I'm having a hard time controlling the attribute value, so please let me know if there is a good way. I'd appreciate it if you could give me an answer. in Django <button type="submit" data-bs-target="#carouselCaptions" data-bs-slide-to="{{forloop.counter0}}" aria-label="Slide {{forloop.counter}}" {% if forloop.first %} class="active" aria-current="true" {% endif%}> </button> vue?? <button v-else type="submit" data-bs-target="#carouselCaptions" :data-bs-slide-to="Slide [[idx]]":aria-label="[[idx+1]]" :class=""> </button> How do I code to operate in the same format as Django? And :data="[x]" works fine, but :data="Slide [[x]]" is a problem that causes errors. How do I fix it? -
Django formsets not saving all forms to the database
I have a formset to render multiple forms at once. By default only two forms are rendered. Using JavaScript, I'm adding another two forms to the formset, so the total number of forms is now four. When I sent POST request, my view saves only first two objects to the database. The data from forms, added using JavaScript, is not saved. What am I doing wrong? My code: This is my forms.py file, where i define my formset. class AddAnswerForm(ModelForm): class Meta: model = Answer exclude = ['question'] widgets = { 'answer_text': forms.TextInput(attrs={'class': 'input'}), } AnswerFormSet = modelformset_factory(Answer, form=AddAnswerForm, extra=2, max_num=4) This is JS code, which I'm using to add new forms to the page (it's not mine code, but it works). <script> let answerForm = document.querySelectorAll(".answer-form") let container = document.querySelector("#question-form") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = answerForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = answerForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`, 'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form=${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } </script> And here is my view. class QuestionAddView(View): form_class = NewQuestionForm form_class_for_answers = AnswerFormSet template_name = 'questions/question_add.html' def get(self, request, *args, **kwargs): form = self.form_class() answers_form = self.form_class_for_answers(queryset=Answer.objects.none()) return render(request, self.template_name, {'form': form, … -
What is running behind when creating Django project with one line command
a fresh question about Django. It maybe silly...I wonder what is running behind the scene when I create a Django project with one line command. Well, I have done with couples of Django projects, the framework is really powerful. So this question is just jumping into my mind. who created the directory structure. Is it a script in some installed Django folder? where can I find it? Thanks. -
How to merge two models inherited from Django into one serializer
In Django, is there a way to combine two models that inherit the same class into one serializer? from django.db.models import Model class A(Model): a = IntegerField(...) class B(A): # There may or may not be such a thing as class C. class C(A): # There may or may not be such a thing as class B. I have code like above. Could it be possible to create a serializer based on the class A model? I tried to create a view table in SQL, but gave up due to performance issues. Any good ideas please. It's so painful...😥 -
Time Zones and Filters in Django Rest Framework
We have a game where we keep track of daily, weekly and monthly leaderboards. Most of the users are in the US, so we're trying to have the daily/weekly/monthly charts update around a US timezone. So the setup we have is pretty straight forward. # models.py class PackGameSavedPack(auto_prefetch.Model): date = models.DateTimeField(null=True, blank=True) user_name = models.CharField(max_length=120, null=True) pack_score = models.IntegerField(null=True) # save_pack.py def pack_game_save_pack(user_id, user_name, pack_score=None): pack = PackGameSavedPack.objects.create( user_id=user_id, date=timezone.now(), user_name=user_name, pack_score=pack_score, ) #views.py class PackGameFilter(django_filters.FilterSet): user_id = CharInFilter(field_name='user_id', lookup_expr='in') date_range = DateRangeFilter(field_name='date') For the most part, this works great - except its saving all of the dates in the UTC (O offset) format. We set the USE_TZ and TIME_ZONE parameters in the settings.py file, however, this didn't seem t change anything. USE_TZ = True TIME_ZONE = "America/Los_Angeles"` I know I can adjust the dates/times at the serializer level, however, that doesn't help with the DateRangeFilter as it is using the UTC (0 offset) timezone. How can I get the DateRangeFilter using the TIME_ZONE or whats a better way to approach this? -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_user_email_key"
I have an issue where when I try to sign up on my app with the inputs: name, email, password, company. I get the error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_user_email_key" DETAIL: Key (email)=(csscsecscs@gmail.com) already exists. My postgres database running in a container on docker desktop and I have created a migration with no issue once I added the company to the models so I am not sure what the cause of the issue is. Models: class User(AbstractUser): name = models.CharField(_("full name"), blank=True, max_length=255) email = models.EmailField(_('email address'), unique=True) company = models.CharField(_("company"), blank=True, max_length=30) Migrations: migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('name', models.CharField(blank=True, max_length=255, verbose_name='full name')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), ('company', models.CharField(blank=True, max_length=30, verbose_name='company')), forms: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from rsm_app.users.models import User class MyUserCreationForm(UserCreationForm): field_order = ['name', 'email', 'company'] class Meta(UserCreationForm): model = User fields = ('name', 'email', 'company') signup.html: {% extends "site_blank_base.html" %} {% load staticfiles i18n compress %} {% load i18n %} {% load crispy_forms_tags %} {% block title %}{% trans "Signup" %}{% endblock %} {% block nav %} {% include "nav/auth.html" %} {% endblock nav %} <div class="form-wrapper"> <h2 class="mb-20">{% trans "Sign Up" … -
Error "python setup.py egg_info" while installing scikit-learn using pipenv
I have been getting following error while installing sklearn using pipenv. I have tried various suggestions including upgrading setuptools and pip. I have also tried installing my everything on different ubuntu machines. I believe this issue might be due to conflict between package versions. Would appreciate any help. Here is the error: Pipfile.lock (60e0f6) out of date, updating to (780331)… Locking [dev-packages] dependencies… Locking [packages] dependencies… elf.repository.get_dependencies(ireq) File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 174, in get_dependencies legacy_results = self.get_legacy_dependencies(ireq) File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 222, in get_legacy_dependencies result = reqset._prepare_file(self.finder, ireq, ignore_requires_python=True) File "/usr/lib/python3/dist-packages/pipenv/patched/notpip/req/req_set.py", line 644, in _prepare_file abstract_dist.prep_for_dist() File "/usr/lib/python3/dist-packages/pipenv/patched/notpip/req/req_set.py", line 134, in prep_for_dist self.req_to_install.run_egg_info() File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/req/req_install.py", line 435, in run_egg_info call_subprocess( File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/utils/__init__.py", line 705, in call_subprocess raise InstallationError( pip9.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/tmp9c38a1_hbuild/scikit-learn/ Here is my Pipfile [packages] django = "==3.2.13" asgiref = "==3.4.1" autopep8 = "==1.6.0" dj-database-url = "==0.5.0" gunicorn = "==20.1.0" pycodestyle = "==2.8.0" pytz = "==2021.3" sqlparse = "==0.4.2" toml = "==0.10.2" whitenoise = "==5.3.0" django-environ = "==0.8.1" mysqlclient = "*" djangorestframework = "*" drf-nested-routers = "*" celery = "*" redis = "*" sqlalchemy = "*" pymupdf = "*" django-redis = "*" pyarrow = "*" djoser = "*" pillow = "*" matplotlib … -
Django Traverse Foreign Keys
I have 3 models and I am trying to create a dashboard with a list of Trials that spans all Client Sessions for a specific client chosen via a filter. Here are the models: class Trial(models.Model): behavior_name = models.ForeignKey(Behavior, on_delete=models.CASCADE) client_session = models.ForeignKey(Client_Session, on_delete=models.CASCADE) frequency_input = models.PositiveIntegerField(default=0, blank=True) duration_input = models.DurationField(blank=True, default=timedelta(minutes=0)) class Meta: verbose_name_plural = 'trials' def __str__(self): return str(self.id) class Client_Session(models.Model): name = models.CharField(max_length=200, null=False) session_date = models.DateField(blank=False,null=False) client = models.ForeignKey(Client, on_delete=models.CASCADE) behaviors = models.ManyToManyField(Behavior, null=False) therapist = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Meta: verbose_name_plural = 'clientsessions' def __str__(self): return self.name class Client(models.Model): #user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES,blank=True) gaurdian_first_name = models.CharField(max_length=200, blank=True) gaurdian_last_name = models.CharField(max_length=200, blank=True) diagnosis = models.CharField(max_length=200, choices=DIAGNOSIS_CHOICES, blank=True) therapist = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.last_name Here is the view that im trying to create def dashboard(request): # filter list of client sessions by selected client client_sessions = Client_Session.objects.filter(therapist=request.user) client = DashboardClientFilter(request.GET, queryset=client_sessions) client_sessions = client.qs #Create list of Trials across Client Sessions for the filtered client trial_list = Trial.objects.filter(client_session__client=client) -
method to test get_queryset using Pytest
I've created a get_queryset function in order to fetch multiple product Id's filter_fields = ( "id", "name", "mass", ) ordering_fields = ( "id", "name", "mass", ) def get_queryset(self): queryset = Product.objects.all() id_value = self.request.query_params.get('id') if id_value is not None: queryset = queryset.filter(id__in = id_value) return queryset I would like to test this in test.py using pytest to check if the code is actually working with multiple id's. I am not very fond of django testing so how could I test this code out by creating a def test function in test.py The current approach to test function is def test(self, client, authenticated_headers): request = RequestFactory().get('/views/ProductsView') view = ProductsView view.request = request input_data = [ { "id": "1" * 100, "name": "Test Product1111111", "mass": 100, }, { "id": "1" * 100, "name": "Test Product1111111", "mass": 100, }, ] qs = view.get_queryset() res = client.post( reverse("______"), data=input_data, **authenticated_headers, ) self.assertQuerysetEqual(qs, Product.objects.all()) assert res.status_code == 200 -
Two querysets in one view in Django
so I'm trying to make two lists in one view but with different filters. They also change whether the campaign is paused or is running. This is what I came up with but it throws this error: TypeError: init() got an unexpected keyword argument 'queryset_paused' This is my views.py def home_view(request): #campaigns in progress queryset = Campaign.objects.filter(is_active=True, completion_percent__lt=100) if request.method == "POST": form_type = request.POST.get('id') if form_type == 'campaign_status': formset = CampaignStatusFormSet( request.POST, request.FILES, queryset=queryset, ) formset.save() else: formset = CampaignStatusFormSet(queryset=queryset) campaigns_and_forms = list(zip(queryset, formset)) #paused campaigns queryset_paused = Campaign.objects.filter(is_active=False, completion_percent__lt=100) if request.method == "POST": form_type = request.POST.get('id_paused') if form_type == 'campaign_status_paused': formset_paused = CampaignStatusFormSet( request.POST, request.FILES, queryset_paused=queryset_paused, ) formset_paused.save() else: formset_paused = CampaignStatusFormSet(queryset_paused=queryset_paused) campaigns_and_forms_paused = list(zip(queryset_paused, formset_paused)) context = { 'formset': formset, 'campaigns_and_forms': campaigns_and_forms, 'formset_paused': formset_paused, 'campaigns_and_forms_paused': campaigns_and_forms_paused, } return render(request, 'campaigns_in_progress.html', context) Here is my template for the two lists <table class="table table-striped table-hover table-bright table-bordered align-middle"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Nazwa</th> <th scope="col">Temat</th> <th scope="col">Nadawca</th> <th scope="col">Procent Realizacji</th> <th scope="col">Start Kampani</th> <th scope="col">Stan</th> </tr> </thead> <tbody> <form method="post" id="campaign_status"> {% csrf_token %} <input type='hidden' value='campaign_status' name='id'> {{ formset.management_form }} {% for campaign, form in campaigns_and_forms %} <tr> <td>{{ campaign.campaign_id }}</td> <td>{{ campaign.name }}</td> <td>{{ campaign.topic }}</td> … -
Django PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
I upload files to Google Drive by uploading files to the system first and then to Google Drive, after that I immediately delete them from website directory in one process. But here I get an error. I'm not deleting files on google drive but deleting files in the website directory. views.py tfile = request.FILES['file'] temp = db.FileTemp(files=tfile) temp.save() media_metadata = { 'name': str(tfile), 'parents': [folder.objects.filter(user__username=user)[0].id_folder] } media = MediaFileUpload(os.path.join(temp.files.path), mimetype='image/jpeg', resumable=True) upfile = drive.files().create(body=media_metadata, media_body=media, fields='id').execute() user_permission = { 'type': 'anyone', 'role': 'reader', } perm = drive.permissions().create(fileId=upfile.get('id'), body=user_permission).execute() link = drive.files().get(fileId=upfile.get('id'), fields='webViewLink').execute() result['status'] = True result['link'] = link['webViewLink'] temp.delete() models.py class FileTemp(models.Model): files = models.FileField(upload_to="file") @receiver(post_delete, sender=FileTemp) def foto_file_delete_handler(sender, **kwargs): filed = kwargs['instance'] storage, path = filed.files.storage, filed.files.path storage.delete(path) -
Extending multiple CustomViewsets - as readonly with Django
in our project, our lead developer assigned a task to refactor some viewsets in our project. Create a readonly Asset view that will return all defaults and romy assets So the original code looks like this class DefaultAssetViewSet(viewsets.ModelViewSet): queryset = DefaultAsset.objects.all() serializer_class = DefaultAssetSerializer permission_classes = [IsAdminUser] filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] filterset_fields = ['name'] search_fields = ['name', 'default_value'] @action(detail=False, methods=['get']) def defaults(self, request): defaults = {} for d in self.queryset.all(): defaults[d.name] = d.default_value return Response({'defaults': defaults}) def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **kwargs) except models.ProtectedError: return Response( {'detail': ErrorDetail('Unable to perform this action.')}, status=status.HTTP_403_FORBIDDEN) class RomyAssetViewSet(viewsets.ModelViewSet): queryset = RomyAsset.objects.all() serializer_class = RomyAssetSerializer permission_classes = [IsAdminUser] filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] filterset_fields = [ 'romy', 'default_asset' ] search_fields = [ 'romy', 'default_asset' ] So my first idea to come to my mind is to extend these two Views into AssetViewSet class class AssetViewSet(RomyAssetViewSet, DefaultAssetViewSet,viewsets.ReadOnlyModelViewSet): """ some code here""" Is it possible to extend custom viewsets like these? And also how to implement get or list for both RomyAssetViewet and DefaultAssetViewset inside AssetViewsetClass? -
How to pass type arguments when using a django generic class based view?
I want to use django.views.generic.edit.FormView and since it's a generic, I'm giving it a type argument (MyForm): class MyView(FormView[MyForm]): ... But it causes this error: TypeError: 'type' object is not subscriptable What's the proper way to pass type arguments to FormView? -
Heroku Posgres' DATABASE_URL cannot be loaded in Django's setting.py and application error occurs
When building an API server using Django+REST framework and uploading it to Heroku, hard-coding Heroku Postgres' DATABASE_URL in the DATABASES of setting.py as follows will work on Heroku without problems. (xxx is originally the information of DATABASE_URL, but we dare to hide it this time) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxx', 'HOST': 'xxx', 'PORT': '5432', 'USER': 'xxx', 'PASSWORD': 'xxx, } } However, you can add a .env file to your Django project, stating the following (where xxx is the information originally entered for the DATABASE_URL, but we've dared to hide it this time) DATABASE_URL=postgres://xxxx In setting.py import dj_database_url from dotenv import ( find_dotenv, load_dotenv, ) load_dotenv(find_dotenv()) DATABASES = { 'default': dj_database_url.config(conn_max_age=600), } If I put something like this, it works in the local environment, but when I upload it to heroku, I get an application error. Do you know the cause? -
Don't know how to query a complex SQL in django
I have these two models below class Category(models.Model): id = models.AutoField(primary_key=True) cate_id = models.CharField(max_length=16, editable=False, default=utils.generate_random_str) name = models.CharField(max_length=64, default="") class Record(models.Model): id = models.AutoField(primary_key=True) record_id = models.CharField(max_length=16, editable=False, default=utils.generate_random_str) count = models.IntegerField(blank=True) user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) And I want to make SQL Query distinct cate_id and Sum their values and Group them like this: SELECT B.name , SUM(A.count) AS count_sum FROM app_record AS A, app_category AS B WHERE A.`user_id` = 1 AND B.cate_id IN ( SELECT DISTINCT(B.cate_id) FROM app_record AS C, app_category AS D WHERE C.category_id = D.id ) AND A.category_id = B.id GROUP BY B.cate_id; I expect the results should be like this: +---------+-----------+ | name | count_sum | +---------+-----------+ | Test1 | 494 | | Test2 | 18 | | Test3 | 269 | +---------+-----------+ 3 rows in set (0.001 sec) I want to make that query in Django but I couldn't work out on my own. I have tried this but it didn't seem to work out: Record.objects.filter( user=user ).distinct().annotate( record__category_id=F('category__id') ).aggregate( count_sum=Sum('count') ) I don't know how to do that, hope someone can solve this.Thanks a lot. -
How to write an ajax like button for django like object that uses foreign key?
So I have been trying to write a jquery ajax button that would stop page reload effect when a post object is liked, As I'm having a challenge doing so because my like model object is using a foreign key on my webapp, As I can do this with a many to many field but my challenge is when I change my like button to a ManyToMany field i wouldn't be able to recover already liked post on my app and I find it would be much convenient if I could write jQuery ajax to handle the foreign key like object instead. This is what i have been able to come up with , but it doesn't trigger the like button ! #Model for like class Like(models.Model): user_like = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_likes', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='user_likes', on_delete=models.CASCADE) like_date = models.DateTimeField(auto_now=True) View.py def like_button(request, pk, c_slug=None): user = request.user if request.method =="POST": if request.POST.get("operation") == "like_submit" and is_ajax(request=request): content_id=request.POST.get("content_id",None) content=get_object_or_404(Like,pk=content_id) if liked.likes.filter(id=request.user.id): #already liked the content content.likes.remove(request.user) #remove user from likes liked=False else: content.likes.add(request.user) liked=True resp = { 'liked':liked,'like_id':content_id, } response = json.dumps(resp) return HttpResponse(response,content_type = "application/json") product = Product.objects.get(pk=pk, slug=c_slug) liked= False like = Like.objects.filter(user_like=user, product=product) if like: like.delete() else: … -
Django How to format JSON response from drf API?
I would like to know how to modify the way I represent the JSON Response of my requests to the API created with DRF, tabs, spaces, etc..., in order to respond exactly to my frontend app. I have the following code: My models.py extract: class Email(models.Model): user_email = models.CharField(primary_key=True, max_length=200) user_phone_number = models.IntegerField() user_device_id = models.CharField(max_length=200)#request.META.get('HTTP_DEVICE', '') lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) user_address = models.CharField(max_length=200) creation_date = models.DateTimeField(default=None) email_status = models.BooleanField(default=False) email_score = models.IntegerField() valid_email = models.BooleanField(default=False) fraud = models.BooleanField(default=False) My views.py extract: class UserListView(APIView): serializer_class = EmailSerializer queryset = Email.objects.all() pagination_class = StandardResultsSetPagination def get_serializer_class(self): if self.action == 'list': return EmailListSerializer return EmailSerializer def post(self, request, *args, **kwargs): parametros = request.POST email='email=' + request._full_data['user_email'] response = UserConnector(email).get_user_data() obgs = response[1]['results'] if len(obgs) == 0: user_email = self.request.POST.get('user_email') email_stat = '' email_scor = '' email_valid = '' frau = '' else: obg = response[1]['results'][0] user_email = self.request.POST.get('user_email') email_stat = obg.get('email_status') email_scor = obg.get('email_score') email_valid = obg.get('valid_email') frau = obg.get('fraud') NewEmail = Email( user_email = user_email, user_phone_number = self.request.POST.get('user_phone_number'), user_device_id = request.META.get('HTTP_DEVICE', ''), lat = self.request.POST.get('lat'), lng = self.request.POST.get('lng'), user_address = self.request.POST.get('user_address'), creation_date = timezone.now, email_status = email_stat, email_score = email_scor, valid_email = email_valid, … -
Problem with .only() method, passing to Pagination / Serialization --- all fields are getting returned instead of the ones specified in only()
I am trying load some data into datatables. I am trying to specify columns in the model.objects query by using .only() --- at first glance at the resulting QuerySet, it does in fact look like the mySQL query is only asking for those columns. However, When I try to pass the QuerySet into Paginator, and/or a Serializer, the result has ALL columns in it. I cannot use .values_list() because that does not return the nested objects that I need to have serialized as part of my specific column ask. I am not sure what is happening to my .only() db_result_object = model.objects.prefetch_related().filter(qs).order_by(asc+sort_by).only(*columns_to_return) paginated_results = Paginator(db_result_object,results_per_page) serialized_results = serializer(paginated_results.object_list,many=True) paginated_results.object_list = serialized_results.data return paginated_results