Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FilterSet on ManyToManyField
I don't even know if this is possible for the way I've set it up but I'll try. I have a Students_Course model that holds information for each class as of a student such as the class itself, the student, grade, status, etc.. class Students_Course(models.Model): student = models.ForeignKey(Student, null=True, on_delete=models.SET_NULL) course = models.ForeignKey(Course, null=True, on_delete=models.SET_NULL) # other fields... The Course itself is also a model like this: class Course(models.Model): prerequisites = models.ManyToManyField('Course', blank=True, default="") # other fields.. In my filters.py, I want to have a checkbox that when ticked, will show me only courses that either have no prerequisites or the student have completed the prerequisites. I can get a students completed courses like this: completed_courses = student.students_course_set.filter(status="Completed") I think the best way to do this is to exclude classes that have prerequisites that are not in the students completed_courses. Note though that prerequisites is a queryset of Course, while completed_courses is a queryset of Students_Course, which has a field that is Course. I got started but this is obviously not working, I'm not sure how to do this. class CourseFilter(django_filters.FilterSet): prerequisites = django_filters.BooleanFilter(label='Prerequisites Completed', field_name='prerequisites', method='filter_only_prerequisites_met', widget=forms.CheckboxInput) def filter_only_prerequisites_met(self, queryset, name, value): if value: lookup = '__'.join([name, 'iexact']) queryset … -
Django: Fetching data for charts from the same view function OR from a separate REST view function
I'm making an app that's going to display a few charts on the index page, along with some other things. Is it better if I pass the data needed for charts along with rendering the view, or should I create a separate REST api view that is going to serve me data needed, and make a GET request to it from axios/fetch? What is the practice here, what is more efficient or a better choice? -
Im having issues getting Django/Python to recognise dj_database_url
I'm having problems getting Django/Python to recognise dj_database_url. I've installed in my virtualevn using pip install dj-database-url and even tried dj_database_url The terminal says that pip install dj-database-url installed fine, I even see it in my requirements.txt after doing pip freeze > requirements.txt But when running python manage.py runserver I get the following Traceback error that ends with "ModuleNotFoundError: No module named 'dj_database_url'": Traceback (most recent call last): File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Delroy Brown\Desktop\Delvinci Code\FryedSauces\virtual\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Public\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Delroy Brown\Desktop\Delvinci … -
Dual authentication in Djnago
I would like to have different types of Users in Django (say Driver and Passenger). So I want both email (with password for Driver) and phone number (with password + OTP for Passenger) authentication. So I have created custom authentication back end and that is fine. But in my User model, I have to add both email and phone. Is there any way that could create different kind of two users, one user model (Driver) store email & password and other one (Passenger) stores phone, OTP and password ? -
Fetch API PUT method not updating database
I have posts on my webpage that are being displayed via a Fetch API 'POST' method and I managed to create a like/dislike button for each post that toggles back and forth when clicked. The like count displayed next to the post updates when the post is liked or disliked but on refreshing the page all values reset so nothing is being updated in the database. Also when I go to the Fetch API route for that post, the likes count has not changed. This is a Django project. The like/dislike button are working on a Fetch API 'PUT' method that I created in views.py but I obviously haven't created it correctly. models.py class Post(models.Model): creator = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post_creator") content = models.TextField(max_length=250, blank=True) created = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(blank=True, default=0) def serialize(self): return { "id": self.id, "creator": self.creator.username, "content": self.content, "created": self.created.strftime("%d %b %Y, %H:%M"), "likes": self.likes } views.py def post(request, post_id): try: post = Post.objects.get(creator=request.user, pk=post_id) except Post.DoesNotExist: return JsonResponse({"error": "No post found."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) elif request.method == "PUT": data = json.loads(request.body) post.likes = int(data.get("likes")) + 1 post.save() return HttpResponse(status=204) else: return JsonResponse({ "error": "GET or PUT request required." }, status=400) index.js function … -
How to access values in a nested array of objects via django rest framework?
I can not figure this out for the life of me and I'm new to Django, so a lot of things don't make sense but I am losing my mind lol. Expected outcome: SO, what I am hoping is to send 4 nested objects to my front end (react), in the form of an object or an array of objects so that I can access them by their specific labels. Such as name = valname['name'] and details = valname['deets'] The issue: I have a program that passes data back to my api view. Its in this form: {'valname': {'name': [...], 'name': [...]}, 'valname': {'name': [...], 'name': [...]}, 'valname': {'name': [...], 'name': [...]}} I have tried just about everything to access valname['name'] but when the data is passed through the serializer it is returned as a string so its literally {'valname': "{'name': "['...']"}" Here is my serializer: class CalcSerializer(serializers.ModelSerializer): cleanser, serum, moisturizer, sunscreen = (serializers.ListField(required=False) for _ in range(4)) class Meta: model = Skincare fields = ['cleanser', 'serum', 'moisturizer', 'sunscreen'] depth = 1 class ResultSerializer(serializers.ModelSerializer): class Meta: model = Skincare fields = ['cleanser', 'serum', 'moisturizer', 'sunscreen'] depth = 1 My views GET AND POST @api_view(['GET']) def list_result(request): data = Skincare.objects.all() serializer … -
Adding a multiple Image gallery to a page with text?
I'm learning Wagtail and I'm trying to make a basic Ecommerce style site. The layout will be: Home Page -> Products -> Product 1 -> ... -> Product N -> About -> Contact In the Product page I want to have a Title, Description, Picture gallery or just display a few pictures and eventually tags (But this post is about the Images). I have checked this Documentation which explain how to add Abstract Images in the View but it leaves me confused on what to import and add to the model, what type? when I just want to add 1,2...n Images on a Product page. The documentation only explains how to add an Image into a form and it leaves me wondering should I use a Django type or Wagtail type? How would I add the ability to upload/remove images from the admin console Product page? -
does filtering queryset in django query database every time?
Imagine I have the following code: qs = Users.objects.all() list = [] for i in range(10): list.append(qs.filter(age=i)) here the filter is called 10 times, does it connect to database 10 times or the first time filter is being used the qs is assigned (due to being lazy) and the filters are applied locally (total of one database connection)? -
How can I catch django.http.request.DisallowedHost in a view?
This works: def index(request): try: # Do some stuff except: return render(request, 'something.html') But how can I catch just the error: django.http.request.DisallowedHost ? Have tried this and it doesn't work: from django.core.exceptions import DisallowedHost def index(request): try: # Do some stuff except DisallowedHost: return render(request, 'something.html') -
Django - ValueError: Socket has not been accepted, so cannot send over it
I'm getting started to Django Channels and i created a very basic Consumer, but whenever i try to connect to that consumer, i keep getting the following error: Exception inside application: Socket has not been accepted, so cannot send over it Here is the consumer: class TestConsumer(WebsocketConsumer): def websocket_connect(self, event): self.send({ 'type': 'websocket.accept' }) print('CONNECTED') def websocket_receive(self, event): data = event['text'] print(data) def websocket_disconnect(self, event): print('DISCONNECTED!') What am i doing wrong here? Any kind of advice is appreciated. -
Is there a way to get the trigger time from a celery task?
Let's assume a situation that there is a celery beat task that is scheduled to run every 15 minutes. Now a "celery beat process" schedules it as per the system clock and the "celery workers" consume from the queue in which "celery beat" produces those tasks. Now there can be a delay in the time that the worker picks up the task to be executed and the time that the task was intended to run. How do I get this trigger time? For example let's say beat schedules a task every 15 minutes 8:00 AM, 8:15 AM, 8:30 AM and so on. The worker picks up the 8:30 task at about 8:51 PM and thus if I try to get the time in the task code I will get 8:51 AM instead 8:30 AM. Is there any parameter that can allow me to get this 8:30 AM trigger time from within the task? -
local variable 'params'might be initialized before assignment
enter code here from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'index.html', ) def blog(request): return HttpResponse('''This is my Blog page Back''') def services(request): return HttpResponse('''This is my services page Back''') def aboutus(request): return HttpResponse('''This is my aboutus page Back''') def contactus(request): # get the text djtext = request.GET.get('text', 'default') # Check boxes values removepunc = request.GET.get('removepunc', 'off') fullcaps = request.GET.get('fullcaps', 'off') newlineremover = request.GET.get('newlineremover', 'off') extraspaceremover = request.GET.get('extraspaceremover', 'off') charcount = request.GET.get('charcount', 'off') # Check which checkbox values is on if removepunc == "on": punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' analyzed = "" for char in djtext: if char not in punctuations: analyzed = analyzed + char params = {'purpose': 'Removed Punctuations', 'analyzed_text': analyzed} djtext = analyzed #return render(request, 'analyze.html', params) if (fullcaps =='on'): analyzed = '' for char in djtext: analyzed += char.upper() params = {'purpose': 'Change to uppercase', 'analyzed_text': analyzed} djtext = analyzed # analyze the text #return render(request, 'analyze.html', params) if (newlineremover == 'on'): analyzed = '' for char in djtext: if char != '\n' and char != '\r': analyzed += char else: print('no') print('pre', analyzed) params = {'purpose': 'Removed Newlines', 'analyzed_text': analyzed} djtext = analyzed # Analyze text #return … -
i have a problem in integration between djangp-oscar and paypal
i am trying to integrate paypal with oscar-django when i installed Django-Oscar-Paypal it gives me that error ModuleNotFoundError: No module named 'oscar.apps.communication' -
Error when adding multiple paths in django
When I add mulitple path in my code, it gives error. Code views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello Nikhil") def about(request): return HttpResponse("About Nikhil") urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index') path('about',views.about,name='about') #error:Above line is giving error ] when I run the code for 1 path,it does not give any error, but when multiple path is added it givens error -
djnoer gives TypeError: permission_denied() got an unexpected keyword argument 'code' on get request on /users/me/
Doing just a get request on auth/users/me/ results in this error which says the above. Couldn't find anything that helps. Can you help me figure out where this error is coming from and how can I fix it. The link to the tutorial I was following is below. Just had setup a new project and installed djoner with jwt. Below is a detailed error message Djoner link https://djoser.readthedocs.io/en/latest/sample_usage.html Internal Server Error: /auth/users/me/ Traceback (most recent call last): File "/home/prashant/project/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/prashant/project/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/prashant/project/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 415, in initial self.check_permissions(request) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 333, in check_permissions self.permission_denied( TypeError: permission_denied() got an unexpected keyword argument 'code' [28/Oct/2020 17:40:20] "GET /auth/users/me/ HTTP/1.1" 500 16964 settings.py # SECURITY WARNING: don't run with debug turned on in production! … -
I have an excel file in my django models how can i import it in my views.py so that i can perform some pandas operations
from django.db import models class File(models.Model): file = models.FileField(blank=False, null=False) def __str__(self): return self.file. this is my modesl through which I upload excel file into my admin models now how can I make query to use this excel file in my views.py class TaskView(viewsets.ModelViewSet): file_obj = File.objects.all().order_by('-id')[0] data_1 = pd.read_excel(file_obj) data_1 = data_1.dropna() I want to create a function in my views.py which get excel file from models database and I can perform pandas operation on this -
How to feed information from one webpage into a view django
So, it has been two days now of searching StackOverflow for an answer, but I can't seem to find one that fits my question. Mainly, I think this question stems from a lack of understanding of how URLs pass information to views. What I want is when a user clicks on the pdf link, the application should grab the client's name, zip code, and city and feed that information into a pdf. (pdf is kind of auxiliary, I am mainly just trying to figure out how to extract information from one page and feed it into a view). Note: I wish I could imbed a picture here, but can't without a reputation of 10. You will get a great idea of what I am trying to accomplish by the picture. click here to see my demo client page Below is my best attempt on how I can see this working, but I obviously don't know how to actually do it. #client_detail.html {% extends "base_generic.html" %} {% block content %} <h1>Client: {{ compuweatherclient.client }}</h1> <p><strong>City:</strong> {{ compuweatherclient.city }}</p> <p><strong>State:</strong> {{ compuweatherclient.state }}</p> <p><strong>Zipcode:</strong> {{ compuweatherclient.zipcode }}</p> <a href="{% url 'catalog:renderpdf' %}">PDF</a> <!--<a href="{% url 'catalog:renderpdf' var1=compuweatherclient.client %}" ><button class="btn btn-primary">pdf</button></a>--> {% … -
sendgrid-django 4.2.0 do not work with django 1.11
My env: Django: 1.11.29 Python: 2.7.18 sendgrid-django: 4.2.0 I changed settings: EMAIL_BACKEND = "sgbackend.SendGridBackend" SENDGRID_API_KEY = 'api key' And used a code sample from the example: mail = EmailMultiAlternatives( subject="Your Subject", body="This is a simple text email body.", from_email="company <noreply@company.co>", to=["myemail@gmail.com"], ) mail.template_id = '6b02f312-ad80-4d7e-815a-24be029fd05b' mail.substitutions = { '%email%': 'some email', '%location_city%': 'some city', } mail.send() There are no errors, by email is not coming. I also tried to send it without template_id, and mail is coming: mail = EmailMultiAlternatives( subject="Your Subject", body="This is a simple text email body.", from_email="company <noreply@company.co>", to=["myemail@gmail.com"], ) # mail.template_id = '6b02f312-ad80-4d7e-815a-24be029fd05b' mail.substitutions = { '%email%': 'some email', '%location_city%': 'some city', } mail.send() -
How do I get a constant column in a Django ORM?
I am studying ORM. However, there are some things I don't understand even after reading the documentation. How do I get a constant column in a Django ORM? select *, 'a' as a from book; This is the query set I tried Book.objects.annotate(a=Value('a')) -
Djang default value field is not working while inserting through pymongo
I Created a Django Model name Student in which attendance field is by default True. But when I insert the value in Student, attendance field is not created. My Django Model is: class Students(models.Model): firstName=models.CharField(max_length=100, blank=True, null=True) lastName=models.CharField(max_length=100, blank=True, null=True) attendance=models.BooleanField(default=True, db_index=True) I am using mongodb as my database, when i am inserting in Students collection. data={"firstName":"python","lastName"="django"} collection.insert_one(data) But when i am fetching the data i am not getting attendance field. I was expecting that attendance field will be automatically created with default value as True -
Django channels - missing 2 required positional arguments: 'receive' and 'send'
I just got started to Django Channels and i created a very basic consumer which does nothing for now. The problem is that i keep getting the following error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\daphne\http_protocol.py", line 163, in process self.application_queue = yield maybeDeferred( TypeError: __call__() missing 2 required positional arguments: 'receive' and 'send' Here is the consumer: import json from channels.generic.websocket import WebsocketConsumer class TestConsumer(WebsocketConsumer): def websocket_connect(self, event): self.send({ 'type': 'websocket.accept' }) print('CONNECTED') def websocket_receive(self, event): #print(event['text']) dataset = event['text'] print(dataset) #print('Received') def websocket_disconnect(self, event): print('DISCONNECTED!') And here is my route: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/main/', consumers.TestConsumer), ] What am i doing wrong? -
How can I create custom user model for different user types using django rest framework
I am new to django rest framework and I want to create different types of users "I think it should be 4", (students, teachers, staff and admin) And I want the staff user to register the teacher and student users. I want to use custom user model and use email to register and login, can it be done, please help, I have been looking for days for anything that can help me to understand how to do it -
Django - redirect to the page i was before
I'd like to know if there is a way to redirect the user to the page he was on before way the click a "Go back" button. Because for now i used redirect or reverse_lazy to send them to a specific view when they click the button, but i'd like them to go to the page they were on before. -
403 Forbidden while making ajax request to endpoint in Django
I have this endpoint to which I am making a post request from console using AJAX, its not a web page from which I am making this request. $.ajax({ type: 'POST', url: "http://127.0.0.1:8000/browse/", data: {csrfmiddlewaretoken: window.CSRF_TOKEN}, success: function() { console.log("Success!"); } }) But its giving me VM29 jquery.min.js:2 POST http://127.0.0.1:8000/browse/ 403 (Forbidden) The Django views code is doing nothing but returning dummy data def Browse(request): data = [{'name': 'Peter', 'email': 'peter@example.org'}, {'name': 'Julia', 'email': 'julia@example.org'}] return JsonResponse(data, safe=False) urls.py urlpatterns = [ path('browse/', views.Browse, name = 'browse'), -
Module in django
this error comes to me when i try to makemigrations in cmd: ModuleNotFoundError: No module named 'homsapp.app' virtualenv_name: repro project_name: homspro app_name:homsapp models.py: from django.db import models class location(models.Module): location_name=models.CharField(max_length=200) location_type=models.CharField(max_length=200) class propertyview(models.Model): location = models.ForeignKey(location,on_delete=models.CASCADE) property_name = models.CharField(max_length=200) property_area=models.CharField(max_length=200) installed _apps in setting.py: INSTALLED_APPS = [ 'homsapp.app.HomsappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]