Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display admin TabularInline in list_display
I have two models, which are linked reverse by foreign key from my admin point of view: class Product(models.Model): name = models.CharField("name", max_length = 128) class Store(models.Model): store_id = models.PositiveIntegerField(unique = True) product = models.ForeignKey(Product, on_delete = models.CASCADE, null = True, blank = True) And I have an admin view where I want to display the store_id of each product it is available in list_display. I ask because I found TabularInline - my apporach: class StoreInline(admin.TabularInline): model = Store readonly_fields = ['store_id', "product"] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["name",] inlines = [StoreInline,] But how would i be able to display the store_id value in list_displays using the Inlines method? I worked around by creating a custom method but, I feel like from reading (1, 2, 3) that I have solved it "by hand" and not using a path Django already has. This works: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["name", "get_stores"] def get_stores(self, obj): return [s.store_id for s in Store.objects.filter(product = obj)] -
i am tring to write a customr permissions class to add permissions for the user to rate the movie once per user
here i am trying to add custom permissions 1.user can rate the movie once 2.Users can add a movie and other people, except the creator, can rate it. i have written the custom permission class in the permission.py but still it not doing what i want but it is going wrong .can please some help one models.py from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Movie(models.Model): title = models.CharField(max_length=128) director = models.CharField(max_length=128) added_by = models.ForeignKey(User, related_name="movie", on_delete=models.CASCADE, null=True) added_at = models.DateTimeField(auto_now_add=True) # rating=models.IntegerField() class Meta: db_table = "Movie" class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_rating') class Meta: db_table = "Rating" views.py from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAuthenticated from knox.models import AuthToken from TestApp.models import Movie, Rating from TestApp.serializer import UserSerializer, RegisterSerializer, LoginSerializer, MovieSerializer, RatingSerializer from TestApp.permissions import * class UserAPIView(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user class RegisterAPIView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return … -
Best way to save Raw SQL queries in Django
What is the best way to make raw SQL queries in django? I have to search a table for the mode of another table. I could not find a way to solve this in django's ORM so I turned to raw SQL queries. Yet creating all these very long queries in python is very unreadable and does not feel like a proper way to do this. Is there a way to save these queries in a neat format perhaps in the database. -
django ckeditor won't show the errors
I am using django-ckeditor package in my django project. These are my problems: when my text has tabs and spaces, no object is created and it does not give any error! Here is my codes: Also Ckeditor does not show any error when I leave the about_me field blank! But it does not create a new object. view, template, model and form -
How to redirect a user to submited confrim page if he has submited a kyc from?
Well here I just want to redirect a user to submitted confirm page. There is one option in sidebar for kyc form , If he ones submitted the kyc forms then whenever he clicks on kyc form he should redirect to the submitted confrim page instead of kyc create form. How it can be done ? class KycFormCreateView(CreateView): model = KycModel template_name = "accounts/kyc/new_kyc.html" def get(self): userkyc = KycModel.objects.filter(owner=self.request.model) print('user kyc form count ',userkyc.count()) userkyc = KycModel.objects.filter(owner=self.request.model) print('user kyc form count ',userkyc.count()) if userkyc.count() >=1: return('accounts:submitted') else: form_class = KycModelForm return form_class I'm trying this way and this is not making sense at all.... and getting an error: TypeError at /accounts/kyc get() takes 1 positional argument but 2 were given -
Django UpdateView get name error: pk is not defined
I get a name error: pk is not defined although I can see that the pk is passed to the view from the url. urls.py: from django.conf.urls import url from cashflow.views import cashflowView, SelectAccountView, CashflowEditView from django.urls import path app_name = 'cashflow' urlpatterns = [ url(r'^select_account', SelectAccountView.as_view(), name="select_account"), url(r'^$', cashflowView.as_view(), name="cashflow_processing"), path('edit/<pk>/', CashflowEditView.as_view(), name="cashflow_editing"), ] views.py: class CashflowEditView(UpdateView): model = ttransactions template_name = 'cashflow/cashflow_processing.html' form_class = CashflowForm success_url = 'cashflow' def get_form_kwargs(self): kwargs = super(CashflowEditView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def get_queryset(self, **kwargs): transaction = ttransactions.objects.filter(pk=pk) transaction_lines = transaction_lines.objects.filter(transaction=transaction.id) return transaction, transaction_lines I get the error on the line transaction = ttransactions.objects.filter(pk=pk) When I run in debug I can see that pk is send to the view but when I use it on the object I get the error. I will appreciate help to resolve the problem for me. -
How to get the ssl certificate from request object in Django?
I have an API developed using Django Rest Framework. When a request is sent to the API, the client certificate is bound to the request object. But from the server-side, I need to access the client's SSL certificate from the request object. But it is not working. Please give me some suggestion to get the certificate: Server-Side API: class GetBalance(APIView): def get(self, request, format=None): print(request.session.cert) // Raising Exception Here Client-Side Request resp = requests.get('API ENDPOINT', verify=True, cert=['/path/to/my/ca.crt']) But Getting key error when I am printing in get method/ -
Django admin didn't allow me to create a group for one app
I am trying to create a group for a specific app like blog, so that group users can only create and edit blog posts. I also assign staff status to the users of that group. The group is created but it didn't allow me to login in it. After some research, I came to know that if I give access to all of the installed apps it allows me to log in. any suggestion on how to give permission for any specific app. -
How do I fill an empty div with js?
The aim is to access a particular endpoint after performing a search only when I hit a button but I am finding it difficult to do that with JS. I have an HTML which is rendered in an html endpoint, and I want that html file to fill an empty div I created in another HTML file. I am trying to achieve this with vanilla JS but all answers I see are in JQuery and I do not really know JS Implement search for friends. def results(request): if request.method == "GET": search_query = request.GET.get("username") searched_user = UserProfile.objects.filter( user__username__contains=search_query ) return render( request, "toggle.html", { "searched_user":searched_user }) else: return HttpResponse("Search returned nothing") rendering html to fill empty div def html(request): return render(request, template_name= "search_results.html" ) index.html <p>Welcome</p> <form id="search" method="GET" action="{% url 'results' %}" placeholder= "Search for user" autocomplete="off"> {{form}} <input type="submit" value="search" name="search"> </form> search_results.html {% extends "base.html" %} {% block spotify %} {%if searched_user %} {% for each_searched_user in searched_user %} <br/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}}<br/> {% endfor %} {% endfor %} {% endif %} {% endblock %} toggle.html {% extends "base.html" %} {% block spotify %} <div id="div"> </div> <button id=likedsongsbutton>View liked songs</button> <script> var request = … -
Django jsonresponse for making chart
I want to display a chart using chart js with data from django back end. Currently it works if data is there, if data is not there in a particaular day it is not showing proper data, this is my view def member_week_graph(request): labels = [] data = [] date = datetime.date.today() current_week = date.today().isocalendar()[1] member_in_week = User.objects.filter(date_joined__week=current_week).exclude(is_staff=True).values( day=TruncDay('date_joined') ).annotate( total_members=Count('date_joined') ).order_by('day') for entry in member_in_week: labels.append(entry['day']) data.append(entry['total_members']) return JsonResponse(data={ 'labels': labels, 'data': data, }) the output is {"labels": ["2021-01-05T00:00:00Z", "2021-01-06T00:00:00Z"], "data": [1, 5]} this is correct data, if data is not there for a day I want to display the date and an empty string, hope someone can help, thank you. -
Complex custom React component in Django Template
I've made a custom react component based on the react-chatbot-kit and it works fine with React. However, I now want to use the same component inside a Django template. Have tried looking at browserify, webpack but it is not helping since the web tutorials use very simple components like Hello World or the likes to show how to do it. In fact some of the tutorials are not even working the way they should even after following each and every instruction. I need help to use/display my custom React component in a Django template or rather any HTML for that matter. Thanks in advance. Following is the code in App.js to display the Chatbot component. import React from "react"; import './App.css'; import Chatbot from 'react-chatbot-kit'; import ActionProvider from './components/react-chatbot-kit/ActionProvider'; import MessageParser from './components/react-chatbot-kit/MessageParser'; import config from './components/react-chatbot-kit/config'; function App() { return ( <div className="App"> <header className="App-header"> <Chatbot config={config} actionProvider={ActionProvider} messageParser={MessageParser} /> </header> </div> ); } export default App; -
What's the benefit of using Django ManyToManyField instead of just get by related_name?
I was just wondering "Why" use Django ManyToManyField. I can still retrieve data form related_name. -
Django Rest Framework DjangoModelPermissions now working properly
Why the DRF permission class DjangoModelPermissions allow every users to perform all requests like POST, PUT, DELETE even those user i didn't manually assign them the add, change, delete permissions from my django admin. they are allowed to be only view the objects but why the are getting all unsafe request POST, DELETE... ? Views.py class HotelViewSet(viewsets.ModelViewSet): queryset = Hotel.objects.all() serializer_class = HotelSerializer authentication_classes = [SessionAuthentication] permission_classes = [DjangoModelPermissions] settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissions', ] } -
Count error with annotate() & values() while filtering categories, repetition
Django : Count error with annotate() & values() while filtering categories, duplication error as I'm using below count function to filter categories but its displaying accountant separately twice. queryset = Blogpost \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset > My function in template {% for cat in category_count %} <div class="item d-flex justify-content-between"> <a href="#">{{ cat.categories__title }}</a><span>{{ cat.categories__title__count }}</span> </div> {% endfor %} -
docker-compose how to reference files in other directories
Having this dockerfile: FROM python:3.8.3-alpine ENV MICRO_SERVICE=/home/app/microservice # RUN addgroup -S $APP_USER && adduser -S $APP_USER -G $APP_USER # set work directory RUN mkdir -p $MICRO_SERVICE RUN mkdir -p $MICRO_SERVICE/static # where the code lives WORKDIR $MICRO_SERVICE # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev gcc python3-dev musl-dev \ && apk del build-deps \ && apk --no-cache add musl-dev linux-headers g++ # install dependencies RUN pip install --upgrade pip # copy project COPY . $MICRO_SERVICE RUN pip install -r requirements.txt COPY ./entrypoint.sh $MICRO_SERVICE CMD ["/bin/bash", "/home/app/microservice/entrypoint.sh"] and the following docker-compose.yml file: version: "3.7" services: nginx: build: ./nginx ports: - 1300:80 volumes: - static_volume:/home/app/microservice/static depends_on: - web restart: "on-failure" web: build: . #build the image for the web service from the dockerfile in parent directory command: sh -c "python manage.py collectstatic --no-input && gunicorn djsr.wsgi:application --bind 0.0.0.0:${APP_PORT}" volumes: - .:/microservice:rw # map data and files from parent directory in host to microservice directory in docker containe - static_volume:/home/app/microservice/static env_file: - .env image: wevbapp expose: - ${APP_PORT} restart: "on-failure" volumes: static_volume: I need to reference the following files (in … -
Websocket with Django channels drops connection with heroku,
im stck in here , i made a blog with a chat room , with django channels and its workin locally perfectly, but when i deploy it to heroku using daphne no message(chat) is showing this is the result og heroku logs --tail this is redis configuration in settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [(os.environ.get('REDIS_HOST', 'localhost'),6379)], }, }, } Procfile web: daphne elearnow.asgi:application --port $PORT --bind 0.0.0.0 -v2 please let me know if i need to add anything else, as i mentioned its stopped showing messages only in production , but locally with the same code everythin is fine i made sure Redis is working, and add "s" for my jquery so its secure "wss://" Thank you very much for your help -
Abstract model with dynamic fields
I am wondering since ages how to achieve the following: I have an abstract class wrapping several attributes shared by multiple models. But not every model needs every attribute in exactly the same way. Here is an example: MyModelA and MyModelB both have two fields: value_1 and value_2. But while MyModelA needs them to be required/not nullable, they can be nullable for MyModelB. class MyAbstractModel(models.Model): value_1 = models.IntegerField() value_2 = models.IntegerField() class Meta: abstract = True What I tried: Not deriving MyAbstractModel from models.Model but from object like a regular mixin Setting a class attribute which is overwritten in the child classes to determine the nullable-state. It always takes the definition from MyAbstractModel. Using a class attribute but not set it in the MyAbstractModel. Then the makemigrations command fails because of the undefined variable. Cry Being DRY is such an important paradigm in django, I really wonder that there is nothing on this topic in the internet. Thanks in advance! -
Django IntegrityError: null value in column "interestreceiver_id" of relation "HomeFeed_interest" violates not-null constraint
Django : Why is my submit interest form not submitted because of an integrity error issue? Did I write my view or template wrongly? How should I solve this error as i've never encountered before. i searched on this website and saw some profile examples but mine is blog post and i dont really understand how their change could solve the error.. I received the following integrity error: IntegrityError at /HomeFeed/submitinterest/slug-5 null value in column "interestreceiver_id" of relation "HomeFeed_interest" violates not-null constraint DETAIL: Failing row contains (17, 2021-01-06 10:54:25.489884+00, t, ddfe, efeffe, 5, documents/Discussion_between_joowon_and_SLDem_-_2021-01-05.pdf, 13, null, null, 1). views.py @login_required def submit_interest_view(request, slug): user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') interest_requests = Interest.objects.filter(interestsender=user, interestreceiver=blog_post.author, is_active=True) if interest_requests.exists(): return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form) form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.get(email=user.email) # use 'author = user.account' if there is OneToOne relation between user and account obj.author = author obj.blog_post = blog_post obj.save() messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest') … -
relation "app_model" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_model"
I'm using Django and created a new model after deploying my app to Heroku, I get this error when I try to access my app's admin page. -
Djongo Models - How to get rid of : Object of type AssertionError is not JSON serializable
I'm having a weird problem in my django Restfull Application ! i'm using Djongo as db engine (MongoDB) the problem seems to be happening in /usr/local/lib/python3.8/dist-packages/rest_framework/utils/encoders.py which sometimes say create() function returned null object or returned AssertionError as Object which is not Serializable at the end ! Model : class Product(models.Model): """ Product Model """ _id = models.ObjectIdField() name = models.CharField(max_length=MAX_PROD_NAME_LEN) sku = models.CharField(max_length=MAX_PROD_SKU_LEN , unique=True) category = models.CharField(max_length=MAX_PROD_CAT_LEN) desc = models.TextField(default="") agent_desc = models.TextField(default="") urls = models.JSONField(blank=True , null=True) productType = models.CharField(max_length=MAX_PROD_TYPE_LEN) variants = models.JSONField(default={ # "op1":models.CharField(max_length=MAX_PROD_OPTION_LEN), # "op2":models.CharField(max_length=MAX_PROD_OPTION_LEN), # "op3":models.CharField(max_length=MAX_PROD_OPTION_LEN), # "quantity":models.IntegerField(default=1), # "price":models.DecimalField(max_digits=10, decimal_places=2), }) options = models.JSONField(default={}) accessories = models.JSONField(default={ # "name" : None, # "attachements":[], # "quant" : None, # "desc" : None }) created_at = models.DateTimeField(auto_now_add=True , null=False) updated_at = models.DateTimeField(auto_now=True, null=True) deleted_at = models.DateTimeField(default=None) is_deleted = models.BooleanField(default=False) objects = models.DjongoManager() # built-in Model's objects Alike ! def __str__(self): return self._id View : class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def list(self, request): queryset = Product.objects.all() serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): print(f"Retrieving infos of {pk}") queryset = Product.objects.all() oid = None try: oid = ObjectId(pk) except Exception: return Response("Product not found !") product = get_object_or_404(queryset, _id=oid) serializer = … -
Django date is not recognized in the view
The date is not recognized in the view . When I post, error came out like "please enter the date" There seems to be a problem with select name. Because of prefix. i need to use prefix because of multiple forms Is there a way to solve this? I need help . my models.py class Grade(models.Model): title = models.CharField(max_length=255, verbose_name='title') date = models.DateTimeField(default=datetime.now, verbose_name='date') ... my views.py class StudentDetail(DetailView): model = Student template_name = 'student/view.html' context_object_name = 'student' form_class = AddConsultation second_form_class = AddGrade def get_object(self, queryset=None): return get_object_or_404(Student, pk=self.kwargs['pk'], school_year=self.kwargs['school_year']) ... def post(self, request, *args, **kwargs): student = get_object_or_404(Student, pk=kwargs['pk']) consultation_form = self.form_class(request.POST, prefix='consultation') grade_form = self.second_form_class(request.POST, prefix='grade') if grade_form.is_valid(): grade = grade_form.save(commit=False) grade.created_to = student grade.created_by = request.user grade.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) my template ... <dl class=""> <dt>date</dt> <dd> <ul class="select-box thumb3"> <li> <select name="grade-date_year" class="member__select-btn"> {% for i in year %} <option value="{{i}}">{{i}}year</option> {% endfor %} </select> </li> <li> <select name="grade-date_month" class="member__select-btn"> {% for i in month %} <option value="{{i}}">{{i}}month</option> {% endfor %} </select> </li> <li> <select name="grade-date_day" class="member__select-btn"> {% for i in day %} <option value="{{i}}">{{i}}day</option> {% endfor %} </select> </li> </ul> </dd> </dl> ... -
How do I stream video using Node JS and Use it in my Django Project?
I am working on a Django project related to Video Streaming. All my basic functionalities(like Authentication, login, etc.) are being made using Django. Now I want to Stream Video on my Web App. I didn't find a solution to Stream my videos directly using Django. So, I decided to stream my video using Node.js and integrate this feature in my Django Project. Here is the Node-Express Code I used for Streaming my Videos in my frontend. app.get("/video", function (req, res) { const range = req.headers.range; if (!range) { res.status(400).send("Requires Range header"); } const videoPath = "mySample.mp4"; const videoSize = fs.statSync("mySample.mp4").size; const CHUNK_SIZE = 10 ** 6; // 1MB const start = Number(range.replace(/\D/g, "")); const end = Math.min(start + CHUNK_SIZE, videoSize - 1); const contentLength = end - start + 1; const headers = { "Content-Range": `bytes ${start}-${end}/${videoSize}`, "Accept-Ranges": "bytes", "Content-Length": contentLength, "Content-Type": "video/mp4", }; // HTTP Status 206 for Partial Content res.writeHead(206, headers); const videoStream = fs.createReadStream(videoPath, { start, end }); videoStream.pipe(res); }); If someone can tell me how can I integrate this with my Django Project. Thanks :) -
Page reload is not working with POST request on browser back and forward button
I am trying to reload a page on clicking the back or forward button or reload in the browser. Below are the usecases: 1.User enters details in signup form and submits -> the same page shows up with an OTP form. If this page is revisited using back, forward or reload button, it should be redirected to the first page with empty signup form. 2.User submits the cart form -> moves to checkout page and submits form -> moves to payment gateway. If the Checkout page is revisited using back, forward or reload button, it should be redirected to the cart page. Redirects are happening to Cart page if I copy paste the Checkout page to the browser, based on the type of request, GET or POST I want this similar to Instagram signup, where user fills the Signup form and goes to OTP form. If user reloads or revisits the OTP form, he is redirected to the original Signup form. Also the tab history stack only has one page for both Signup and OTP forms I tried using PerformanceNavigationTiming.type but it's not working. Below is the code. var perfEntries = performance.getEntriesByType("navigation"); if (perfEntries[0].type === "back_forward") { location.reload(true); } I … -
Django: 'python manage.py runserver' returns 'TypeError: object of type 'WindowsPath' has no len()'
I have created a new django proejct and the only modification I have made is to the settings, changing the database from sqlite to postgres: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'yachtdrop', 'USER': 'postgres', 'PASSWORD': 'passsword', 'HOST': '127.0.0.1', 'PORT': '5432', } } I am using pipenv to manage my virtual environment, my pipfile is as follows: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" requests = "*" flask = "*" psycopg2-binary = "*" [dev-packages] [requires] python_version = "3.9" When I write the command 'python manage.py runserver', the system returns 'TypeError: object of type 'WindowsPath' has no len()' and I don't understand why this is happening. I am running this on Windows. I have recently reset my Windows system and have a fresh installation of python, pipenv and postgres. It would be great if anyone could help me out here. Thanks! -
Get data user profile django rest
i want to get data user in profile . i do register login rest_framework_simplejwt I got the token.But it is not possible to get data this user. which URL to get data . token work. //simplejwt simplejwt Models class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=11) likecus=models.ManyToManyField(smartphone ,verbose_name="b") def __str__(self): return "User: {}, phone: {}".format(self.user, self.phone) url ??here correct ????? path('customers/<int:id>', views.CustomerRetrieveView.as_view()), path('api-token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api-token-refresh/', TokenRefreshView.as_view(), name='token_refresh'), Views class CustomerRetrieveView(generics.RetrieveAPIView): queryset = Customer.objects.all() permission_classes=(IsAuthenticated,) def get(self,request, **kwargs, pk): queryset = get_object_or_404(Customer, pk=self.kwargs.get('pk')) serializer=CustomerSerializer(queryset) return Response(serializer.data) Serializer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__'