Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Consume an API in Django REST, server side, and serve it ,client side, in Angular
I have an Angular app that consume API client side. Since it's bad practice to do so (I don't want to expose my API credentials), I decided to split into backend/ frontend before myapp get to big. I succeed to implement my Angular into a Django REST framework app and everything is working fine. But now I need to change my API logic and have DRF consume the external API I had: Angular <---API---> ext data Now I have: Django/ Angular <---API---> ext data What I need: Angular <---API---> Django <---API---> ext data But I am very confused about how to accomplish it. I have experience with setting up API endpoints in DRF, but only for data from models within DRF. I know as well how to consume API in Django. But how can I chain two API calls? Do I have to create a model to store the queries and then the response? Do I need to write serializers even if the returned data is json all the way? How my frontend will now that the data from the external API is available? What I need is someone to explain me what is the pattern for this task. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use activity.set() instead. React client/Django server|
I'm a beginner with a few months under my belt but am practically new to django. class Locations(ViewSet): def create(self, request): user = VacaUser.objects.get(user=request.auth.user) location = Location() # activity = Activity.objects.filter() location.user = user location.title = request.data["title"] location.time = request.data["time"] location.description = request.data["description"] location.photo = request.data["photo"] try: location.save() # location.set(activity) location.activity = Activity.objects.get(pk=request.data["activity"]) serializer = LocationSerializer(Location, context={'request': request}) return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) class Location(models.Model): time = models.DateField(models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)) user = models.ForeignKey("VacaUser", on_delete=models.DO_NOTHING, related_name="vacauser") title = models.CharField(max_length=50) description = models.TextField(max_length=200) activity = models.ManyToManyField("Activity", related_name='activities', blank=True) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) class Activities(ViewSet): def create(self, request): activity = Activity() activity.name = request.data["name"] try: activity.save() serializer = ActivitySerializer(activity, context={'request': request}) return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) class Activity(models.Model): name = models.CharField(max_length=50,) ` POSTMAN EXAMPLE : This is one of my fixtures. { "id": 1, "time": "2018-04-12", "user": { "id": 1, "bio": "Me", "user": 1 }, "title": "Hawaii", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mattis lectus sit amet velit viverra viverra. Cras efficitur volutpat sem.", "photo": "http://localhost:8000/https%3A/res.cloudinary.com/db1peeart/image/upload/v1601909566/Michael/hawaii2_jwrmwb.jpg", "activity": [ { "id": 1, "name": "Swimming" }, { "id": 2, "name": "Beach" }, { "id": 3, "name": "Hike" }, … -
Django Javascript: Why Won't My Function Change The Styling
I have a like button that is part of a form that uses a javascript function. The function seems to work as intended (adding or subtracting a like from the like count) so it must be changing the class of the button but it won't update the styling unless i refresh the page. I want the styling to turn the button background white when it is liked and transparent when not liked. Script: $(document).ready(function() { $('.like_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') console.log(post_id) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) console.log(trimCount + 1) var element = document.getElementById("like_button"); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'post_id': post_id, }, success: function(response){ if (element.classList.contains("liked_post")){ res = trimCount - 1 element.classList.remove("liked_post") } else if (!$(this).hasClass("liked_post")) { res = trimCount + 1 element.classList.add("liked_post") } $(`.like_count${post_id}`).text(res +' Likes') }, error: function(response){ console.log('error', response) } }) }) }); form: <form action="{% url 'like_post' item.id %}" class="like_form" id="{{ item.id }}"> {% csrf_token %} {% if user in item.likes.all %} <button type="submit" class="like_btn liked_post" name="post_id" value="{{ item.id }}"><div class="liked_btn" id="like_button">Like</div></button> {% else %} <button type="submit" class="like_btn" name="post_id" value="{{ item.id }}"><div class="liked_btn" id="like_button">Like</div></button> {% endif %} </form> -
Django:Permission || List View filter Objects based on current user
I am looking for a way to list only certain objects on which user has reader access. I have looked at Django Documentation and implemented has_object_permission but that does't work for List View. This is my my_permissions.py file from rest_framework import permissions ACCESS_LIST = ["1", "2", "3"] #This is for example this list will be based on user access class IsUserAdmin(permissions.BasePermission): def has_object_permission(self, request, view, obj): user = request.session['samlUserdata'] return obj.Number in ACCESS_LIST This is my view file from .models import DemoGroup from .serializers import dmSerializer from rest_framework.viewsets import ModelViewSet from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework import generics from django.http import JsonResponse from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.permissions import BasePermission from .my_permissions import IsUserAdmin ACCESS_LIST = ["1", "2", "3"] #This is for example this list will be based on user access class DemoViewSet(ModelViewSet): permission_classes = (IsUserAdmin,) serializer_class = dmSerializer queryset = DemoGroup.objects.all() # Overriding List View def list(self, request): user = self.request.session['samlUserdata'] queryset = DemoGroup.objects.filter(Number__in=ACCESS_LIST) serializer = dmSerializer(queryset, many=True) return Response(serializer.data) Currently I am able to filter List View with queryset but I want to explore if there is other efficient method which Django Rest Frameworks provides like permissions which can be … -
Django - get an IP from which model inst was changed
In my models.py I have: class User(AbstractUser): def save(self, force_insert=False, force_update=False, *args, **kwargs): created = self.pk is None super(User, self).save(*args, **kwargs) print("Hello") pprint(kwargs) user = kwargs.get('instance', None) ip = request.META['REMOTE_ADDR'] I want to log an IP from which User model inst was changed. But I can't since request is not in models. How can I get access to it? Thanks. -
Invalid syntax with path in Django 3.1.5
I'm getting a syntax error even though I've checked the code many times. I'm new with Django so I'm not sure if I'm missing something else. So this is my code in my urls.py: # Django from django.contrib import admin from django.urls import path, include from django.conf import settings # media from django.conf.urls.static import static urlpatterns = [ # Admin url path path('admin/', admin.site.urls, name='admin'), # Posts url paths path('', include(('posts.urls', 'posts'), namespace='posts')), # User url paths path('users/', include(('users.urls', 'users'), namespace='users')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm following a tutorial and I've literally copy-pasted what was working for the tutor and it throws the same error as shown in the image. Error Any ideas what this might be? -
Django: Is it possible to add constraint on model level only (Not on DB level)
Is there a way to add a unique constraint on model level only (not on DB level) in Django? -
Django filter datetime based on month and day only in a range
I am trying to filter model objects in between a certain range. If I consider the year then I am able to do it fine like below: today = datetime.date.today() start_date = today + datetime.timedelta(days = 1) end_date = today + datetime.timedelta(days = 7) for required_day in required_days: filter_dict.update({ required_day + "__range" : [start_date, end_date] }) list_of_Q = [Q(**{key: val}) for key, val in filter_dict.items()] if list_of_Q: model_objects = Model.objects.filter(reduce(operator.or_, list_of_Q)) But what I would like to do is to filter only by the values of day and month of the datetime. I tried as below: for required_day in required_days: filter_dict.update({ required_day + "__month__gte" : start_date.month, required_day + "__day__gte" : start_date.day, required_day + "__month__lte" : end_date.month, required_day + "__day__lte" : end_date.day, }) But I am not getting the correct values here. How can I rectify it? -
Django Default Image is showing
why i can't see default image here below are my model and profile.html file: Model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pics',default='default.jpg') def __str__(self): return f'{self.user.username} Profile' Profile.html: {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{user.email}}</p> </div> </div> <!-- FORM HERE --> </div> {% endblock content %} Thank you in advance... -
Django Add Field Error to Non-Model Form Field
Can anyone help me understand how to properly send a field error back to a non-model form field in django that is not using the standard django form validation process? Rendering the form again with error and user data still entered for correction and resubmission? Example html for a simple username field that is validated on the model level: <!--form--> <form id="profile" class="small" method="POST" action="{% url 'profile' %}"> {% csrf_token %} <!--Username--> <label for="username">Username <span style="font-style: italic;">(create a unique display name that will appear to other users on the site)</span></label> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="username">@</span> </div> <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="username" name="username" value="{% if profile and profile.username is not None %}{{ profile.username }}{% endif %}"> </div> <button type="submit" class="btn btn-primary" name="profile_form" value="profile_form">Save</button> </form> View class ProfileView(View): def get(self, request, *args, **kwargs): # get request... def post(self, request, *args, **kwargs): if request.method == "POST": # check if profile_form submitted if 'profile_form' in request.POST: # get user form data profile_data = request.POST.dict() # get current user profile user_profile = Profile.objects.get(my_user=request.user) # check username entry against current if user_profile.username == profile_data['username']: messages.success(request, "This is the current user.") else: try: # try to save the new username user_profile.username = profile_data['username'] … -
Django add object on database after clicking button
I'm new to Django and I'm trying to create an events web app, I already have created the events, and when I'm on that particular event (with URL /event/pk/) of that particular event I have a join button, which has to add the logged user id and the event id to a model attend. My attend model is the following: class Attend(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) event_id = models.ForeignKey(Event, on_delete=models.CASCADE) In the Join button I added a POST form like this: <form action="{% url 'event-join' object.id %}" method="POST"> <button type="submit" id="event-info-join" class="icon" title="Join Event"> <i class="material-icons" title="Join Event">add</i>Join Event </button> </form> And in my urls ('event/int:pk/' because I want to refresh the page after joining): path('event/<int:pk>/', EventJoinView, name="event-join"), And the view I created is the following, my intention here is getting the request and the pk of the event, with that request get the user id using request.user.pk (which I think it is not working), create a new attend object and save it in the attend model: def EventJoinView(request, pk): if request.method == 'POST': event = Event.objects.get(pk=pk) user = request.user new_attend = Attend(user_id=user.pk, event_id=event.pk) new_attend.save() With this I am getting "CSRF verification failed", I know this would be solved by … -
Admin: Show related inline ManyToMany objects as MultipleChoiceField
I've overridden the UserAdmin class and wanted to add a user profile and some related objects as inline. I get now a table with related objects. But that's not really ideal for my application, it's a bit cumbersome to change the related objects, and there's no need to add new objects this way. I'd like to have simple MultipleChoiceField containing the related objects. Is there an easy way to achieve this? Here's my userprofile/admin.py: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from django_admin_listfilter_dropdown.filters import RelatedOnlyDropdownFilter from driverslog.models import Branch from driverslog.models import Car from .models import Userprofile User = get_user_model() class ProfileInline(admin.TabularInline): model = Userprofile can_delete = False max_num = 0 extra = 0 fk_name = 'user' class CarInline(admin.TabularInline): model = Car.users.through can_delete = True verbose_name = _('Car') verbose_name_plural = _('Cars') extra = 0 class BranchInline(admin.TabularInline): model = Branch.users.through can_delete = True verbose_name = _('Branch') verbose_name_plural = _('Branches') extra = 0 class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, BranchInline, CarInline) list_display = ('username', 'first_name', 'last_name', 'is_staff', 'is_superuser', 'represents') list_filter = ('is_active', 'is_staff', 'is_superuser', ('groups', RelatedOnlyDropdownFilter), ('branches', RelatedOnlyDropdownFilter), ('profile__represent', RelatedOnlyDropdownFilter), ('car', RelatedOnlyDropdownFilter)) def represents(self, obj): return obj.profile.represent.count() represents.short_description = _('Represents') admin.site.unregister(User) admin.site.register(User, … -
Python Django duplicate loop
i fetch two table from my db like this: query_tags = Tags.objects.all() query_usertags = UserNews.objects.all() context = {'query_tags': query_tags, 'query_utags': query_usertags} and in my html , i try that: {% for tags in query_tags %} {% for utags in query_utags %} {% if utags.user_tag == tags.name and utags.userid == user.id %} <input disabled type="checkbox" id="development" value={{ tags.name }} name="user_interest"> <label class="light" for="development">{{ tags.name }}</label><br> {% else %} <input type="checkbox" id="development" value={{ tags.name }} name="user_interest"> <label class="light" for="development">{{ tags.name }}</label><br> {% endif %} {% endfor %} {% endfor %} but my problem is output gonna duplicated cuz of second loop can you help me ? -
Django Ajax Javascript: Why Does My Function Use Class Name Instead Of id
I am trying to make a like post button that won't refresh the page so im trying to use ajax to do this. I am trying to log the id to see if it works but it just logs like_form (which is the class for the form). Scripts: <script> $(document).ready(function() { $('.like_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') console.log(post_id) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) console.log(trimCount + 1) }) }); </script> form <form id="like_form" action="{% url 'like_post' item.id %}" class="like_form" id="{{ item.id }}"> console: like_form -
How do i get email of a user after signing them in with django all auth
I am using django all auth to authenticate users but after authentication there is no email being saved to the database how can i get the email of the user? Thanks in advance -
Django Unicorn Failed About SQLite Version
I deployed django app to CentOS 7 Server. I want to use Nginx and Gunicorn. By the way i tried to make steps, gunicorn best.wsgi:application --preload -b 0.0.0.0:8000 when i run this code whit virtual environment gunicorn outputs like; [2021-01-11 14:56:16 +0000] [93067] [INFO] Starting gunicorn 20.0.4 [2021-01-11 14:56:16 +0000] [93067] [INFO] Listening at: http://0.0.0.0:8000 (93067) [2021-01-11 14:56:16 +0000] [93067] [INFO] Using worker: sync [2021-01-11 14:56:16 +0000] [93070] [INFO] Booting worker with pid: 93070 and working... But when i try to write gunicorn.service like : [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/root/best/best ExecStart=/root/best/virtenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/root/best/best [Install] WantedBy=multi-user.target I am getting error like : django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). I get this error before and i solved it but its about my virtual environment, i downloaded sqlite version and it worked ('import sqlite3; sqlite3.sqlite_version' output is 3.30.0). But i dont know how i fix it in Gunicorn side. (Maybe its about gunicorn doesn't see my virtual environment but i can't found how i change this) Any suggestion to solve it? Thx to all. -
What is the conventional way to write external SQL files in Django
I'm making a Django app that connects to a PostreSQL database other than the database used by the Django app itself. currently, I'm writing SQL code inside constant strings in python files, most queries contain multiple variables which are retrieved from the python script at runtime like: import psycopg2 connection = psycopg2.connect("connection information")) cursor = connection.cursor() customer_id = 5 cursor.execute('SELECT * FROM sometable WHERE id = {0}'.format(customer_id)) Howere, the SQL code will be more sophisticated than this and I have many different queries that need to be saved and reused and putting just inside python files is a very bad and unorganized way so I would prefer to save them in external files but also I wanna make sure I'm still following Django's conventions. So where should I be saving my custom .sql fils? is there any special utility for this in Django? -
How to obfuscate vue js code used in django template as inline script?
I am developing an app using django as backend, and django templates for front end (Pages reload when navigating between urls). For some advanced features, I had to use ajax communication between the template and the backend to avoid reloading for each action. So I ended up using vue js to react to server responses and also to build a pretty sophisticated UI. Usually I use django compressor & uglifyjs to minify and mangle the variable names of my scripts build with jquery or vanilla js on each user request (middleware) using {% compress %}. This time with vue, when I mangle the data and function names, their references from the html in the v-if and v-bind: ...etc remains the same as before causing the UI to break because the v- instructions in the html doesn't use the new variable names after the mangling. I want to know if there is a way to parse the html and rename the refrences with django compressor. In case compressor doesn't provide such feature, is there some npm package or other tool/script that I can manually feed a file.html containing both HTML and my vue js code and it does the renaming and … -
best practice to add/remove single objects from a many to many field via generic api view
So I have a view like this class MemberRolePutDeleteView(MultipleFieldMixin, PutDeleteAPIView): """ An API view to create member-roles as well as delete the same. Although the role is returned by the get_object method, we only remove the same from the referenced member, and don't delete/modify it. """ queryset = api_models.Role.objects.all() permission_classes = [IsAuthenticated, ManageRoles] lookup_fields = ['cluster_id', 'pk'] def destroy(self, request, *args, **kwargs): role = self.get_object() member = api_models.Member.objects.get(user__id=self.kwargs['user_id'], cluster=role.cluster) member.roles.remove(role) return Response(status=204) def update(self, request, *args, **kwargs): role = self.get_object() member = api_models.Member.objects.get(user__id=self.kwargs['user_id'], cluster=role.cluster) member.roles.add(role) return Response(status=204) I get the object I want via the get_object method. Now, in the api view, I want to remove the same from member.roles or add to it, instead of actually deleting the object. I am doing this right now by overriding the methods. However, I think that there is a better way to achieve this. Can someone please help me to do the same? thanks a lot! -
Add or Remove Row in Input Table Along With Some Available Jinja
I have an HTML table with some jinja(inside the value attribute). my template: <form class="" method="POST"> {% csrf_token %} <table class="table table-hover my-5"> <thead class=""> <tr> <th>No</th> <th>Name</th> <th>rank</th> <th>gmail</th> <th>Delete?</th> </tr> </thead> <tbody class="my_dynamic_table"> {% for i in report_tableA %} <tr> <td>i</td> <td><input type="text" name="name" value="{{ i.name }}"></td> <td><input type="text" name="rank" value="{{ i.rank }}"></td> <td><input type="email" name="gmail" value="{{ i.gmail }}"></td> <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td> </tr> {% endfor %} </tbody> </table> <div class="row mx-5"> <button class="btn btn-warning">Add row</button> <button type="Submit" class="btn btn-primary ml-auto">Submit</button> </div> </form> Now my problem is how can I implement the functionality of the Add row button and the Delete icon(inside last td)? Here Add row function will add a new row inside the table also with a blank value attribute. I have practiced it before by the following stackoverflow link. but now the problem is jinja is also added here. I will be very grateful if you help me to fix this out. -
Same column pointing to 2 different foreign keys in Django
I have 3 models in Django: Student Teacher Publication A single publication can have multiple authors, who can be both students and teachers. Since a student and teacher can have multiple publications and a publication can have multiple teachers and students as authors, I am using a M2M relationship using a through table called PublicationAuthor. However, I am not sure how to get my authors column in my through table. My effort so far : from django.db import models class Student(models.Model): name = models.CharField(max_length=50) publication = models.ManyToManyField(Publication, through=PublicationAuthor, related_name='students') class Teacher(models.Model): name = models.CharField(max_length=50) publication = models.ManyToManyField(Publication, through=PublicationAuthor, related_name='students') class Publication(models.Model): title = models.CharField(max_length=50) class PublicationAuthor(models.Model): publication = models.ForeignKey(Publication, on_delete=models.CASCADE) authors = -
Different submit button for the form on one page (django)
Hello sorry for the inconvenience. I want advice from you. I have question and answer inputs. In the question input, the question is written and in the answer input, the user must enter the answer. How can I do this in html so that there is a separate submit button for each form You can not see the code because I have not completed it yet I just wonder how the html logic is done for example (image) There are 2 forms rendered in the photo but there can be many Thanks for the help -
How to control selection of items in Django's QuerySet in html template?
I need 2 buttons that would control which item from QuerySet should be displayed as a part of video player to change playlist videos back and forth (all other features are done and good). In views.py I have function that sends QuerySet through "video.objects.all()" and I can select any item in HTML template by calling like "videos.all.1.video.url". But IDs arre hardcoded and for loop doesn't seems to be fitting here. So I'm stuck how and where to control items by IDs. Should be html (java?) or in Django's views.py? Some pointing the right direction would help. -
django-filter using a URL parameter and a related foreign key name
I have the following two models class Foo(models.Model): name = models.CharField(max_length=200) class Bar(models.Model): a = models.ForeignKey( "Foo", related_name="bars", on_delete=models.SET_NULL, null=True, ) Now I data in the following link http://127.0.0.1:8000/en/api/v2/dm/ and has the form: [ { "id": 4, "name": "whatever1", "bars": [ 203 ] }, { "id": 5, "name": "whatever2", "bars": [ 228, 113, ] }, ] I also have a template which would add the following parameter to the previous link http://127.0.0.1:8000/en/api/v2/dm/?bar=113 where bar indicates the id of a bar, notice that each bar's id appears only once, what I need is to filter the data in the previous link so if bar=113 it would only display [ { "id": 5, "name": "whatever2", "bars": [ 228, 113, ] }, ] I managed to do so doing the following class AView(ListAPIView): serializer_class = ASerializer def get_queryset(self): queryset = A.objects.all() bar = self.request.query_params.get('bar', None) queryset = queryset.filter(bars=bar) return queryset where ASerializer is class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ("id", "name", "bars") my question is, can I achieve the same using django-filter and filterset_class or filterset_fields?? -
drf-spectacular issue with filterset_fields
I am trying to implement drf-spectacular to an existing Django REST API. However I am getting the following error, when attempting to run ./manage.py spectacular --file schema.yml Error: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: client, tenant_id, subtenant_id, data_stream_id The filters do work, but don't seem to play nicely with the drf-spectacular lib. Can anyone please advise on how this might be solved? Specs as follows: Python 3.7.2 Django 3.0.2 django-filter 2.2.0 django-rest-framework 0.1.0 djangorestframework 3.12.1 drf-spectacular 0.12.0 Viewset example: class DataStreamViewSet(viewsets.ModelViewSet): """Standard ViewSet for the DataStream Model.""" queryset = DataStream.objects.all() serializer_class = DataStreamSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('client', 'tenant_id', 'subtenant_id', 'data_stream_id',) Serializer example: class DataStreamSerializer(serializers.ModelSerializer): """Class to validate an uploaded DataStream.""" class Meta: """Nested Meta Class.""" model = DataStream fields = '__all__'