Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework with Mozilla Django OCID
I've been working on this Drf app to sign certificates. I have been using simple JWT for token authentication. But now I need to implement SSO authentication, so I have been trying to use Mozilla - Django - OIDC, but I can't seem to figure out the docs. I'm confused on where the access and refresh tokens would come from, since it clearly says in the docs. Note that this only takes care of authenticating against an access token, and provides no options to create or renew tokens. If mozilla-django-oidc is not creating the tokens, then where do I obtain them from and where will they be stored when I try to access them in my React frontend. Thank you in advance for any help!! -
Django perform a join on multiple tables
I have the following tables, class A: field_1 = models.CharField() field_2 = models.IntegerField() class B: a = models.ForeignKey(A, related_name='table_b') some_other_field = models.CharField() class C: b = models.ForeignKey(B, related_name="table_c") other_field = models.CharField() Let's assume ids are provided for objects on table A, I need to get all the C objects that are related to table A through table B. I have the following query, which gives me what I need but I am wondering if there is a better way to do this, I was reading into prefetch_related and select_related but can't wrap my head around on how to use them so far c_list = C.objects.filter(b__in=B.objects.filter(a__pk__in=table_a_ids)) Also, I would like to group them by other_field Any help is much appreciated. -
Trying to convert a function based view to a generic detail view
Creating a comment system for a ticket django project. I've completed most of the functionality for the comment, except I'm not quite sure how to implement the POST method so that I can use the frontend to create comments. If I use the admin site, it works and shows up in the view, but I get an error when I try to submit using the frontend form. I'm not sure how to proceed, any help is much appreciated. Here's the original function based view def ticket_single(request, post): ticket = get_object_or_404(Ticket, slug=ticket, status='published') allcomments = ticket.comments.filter(status=True) user_comment = None if request.method == 'POST': comment_form = NewCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.ticket = ticket user_comment.save() return HttpResponseRedirect('/' + ticket.slug) else: comment_form = NewCommentForm() return render(request, 'ticket_detail.html', {'ticket': ticket, 'comments': user_comment, 'comments': comments, 'comment_form': comment_form, 'allcomments': allcomments, }) Here's what I have so far in the DetailView class TicketDetailView(DetailView): model = Ticket def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(ticket=self.object) context['comment_form'] = NewCommentForm() return context def post(self, request, *args, **kwargs): if request.method == 'POST': comment_form = NewCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.save() return render(request, 'ticket_detail.html', {'comments': user_comment, 'comment_form': comment_form}) -
How implement django.views.generic for logoutPage/loginPage if earlier used request?
This my view.py What bast practice for migration from request to django.views.generic? How implement django.views.generic for logoutPage/loginPage if earlier used request? from django.shortcuts import render,redirect from django.http import HttpResponse from .models import * from django.contrib.auth import login,logout,authenticate from .forms import * from django.views.generic import ListView def logoutPage(request): logout(request) return redirect('/') def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request,username=username,password=password) if user is not None: print("working") login(request,user) return redirect('/') context={} return render(request,'book/templates/login.html',context) -
How to parse generic text query into dictionary - Python
I'm trying to parse generic text query that can look as the following in Python: first_name:Jon last_name:"Doe" address:"1st X street, Y, California" to: { "first_name":"Jon", "last_name":"Doe", "address":"1st X street, Y, California" } Any ideas how to do it while being able to properly parse text between quotes and spaces? -
Djoser unused endpoints
I don't need all endpoints that Djoser have. How i can switch off them? In documentation: SetPasswordView, PasswordResetConfirmView, SetUsernameView, ActivationView, and ResendActivationView have all been removed and replaced by appropriate sub-views within UserViewSet. But i don't find how to work with UserViewSet. I need: GET-api/users/ POST-api/users/ GET-api/users/{id}/ GET-api/users/me/ POST-api/users/set_password/ How can i set this endpoints, and hide or better delete others? -
Django Rest Framework application with gunicorn deployment
I have a django rest framework application that's using class style views. The API written on it takes (let's say) 5s to response. My deployment is simple: gunicorn --workers=4 application_name.wsgi -b 0.0.0.0:8000 But what this does is it takes only 4 requests at a time. If I bombard 20 requests concurrently. It processes the first 4, then next 4, & so on... What do I have to do so that it returns response for all 20 requests in 5s(if all takes, 5s let's say). I'm stuck here for a week now. -
How to adapt my CKEDITOR size in css and django?
I try to adapt the CKEDITOR in the textarea assign to but it overide textarea ? How to change so it match the textarea as below ? I uncheck the element.style { /* width: 835px; */ } and there it fits in textarea , what should I do ? enter image description here -
PostgreSQL database not showing data on Django website
I've converted my SQLite DB to a PostgreSQL DB. I've made all the migrations and collectstatic, and in my python script on my windows PC, I can access the DB and execute commands. My problem is that I don't see all that data on my website...It's like the server and Python talk to each other but not to the website. Here are a couple of code snippets- PC Python Script def get_query(group_name , heb_sale_rent ,heb_street, heb_city , heb_rooms , heb_size , heb_floor , heb_porch , heb_storage , heb_mamad , heb_parking , heb_elevator , heb_phone , heb_price): conn = psycopg2.connect(database='test', host='192.168.72.130', port='5432', user='user_sql', password='user_sql') cur = conn.cursor() cur.execute("SELECT * FROM to_excel") query = cur.fetchall() if I run this command I can see results I have added to the DB- (so far so good) On My Ubuntu Server #in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', 'USER': 'user_sql', 'PASSWORD': 'user_sql', 'HOST': 'localhost', 'PORT': '5432', } } But on the website- nada- Where is all the data that Python printed out in the query? What am I doing wrong? help, please! P.S- I don't know if it has any relevance, but when I run sudo -u postgres psql and then … -
Build a data heavy project with drf
I'm going to work on a project(Django and DRF) which is going to have lots of data and from that I've to calculate meaningful data (percentage, variance, average, etc). It's also going to have lots of graphs and different sorts of charts. Is there any Github repo or any platform where I can get help or take a reference from? -
Django - ordering after distinct raises error - how to make it work?
I have a custom QuerySet method that filters users with at least one mortgage. To not get duplicates, I have to add .distinct('pk'). The problem is that API allows on-demand ordering. That means, I can't just order the queryset before calling distinct. How can I make it work? The custom queryset: class UserQuerySet(models.QuerySet): def is_applicant(self): return self.filter(mortgages__isnull=False).distinct('pk') This is the relation: applicant = models.ForeignKey('User', verbose_name='Žiadateľ', on_delete=models.PROTECT, related_name='mortgages') Can I make the is_applicant method work without using distinct? Right now, if I try to order it, it raises: ProgrammingError SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("users_user"."id")... -
Translating {{ model.name }} data dynamically in django template
Can anyone suggest shortest way to translate {{ model.name }} type of data in django template? -
How to add dynamic field to django.core.serializers.serialize
I'm trying to export a queryset into json format. However, my query has a dynamic field (ie not defined in the model), and when I try to add it nothing shows. My model: class MyModel(models.Model): id = models.TextField(primary_key=True, blank=True) quantity = models.IntegerField(null=True, blank=True) rate = models.IntegerField(null=True, blank=True) class Meta: managed = False My queryset: qs = MyModel.objects.filter(id=id).annotate(result=F('rate') * F('quantity')) My call: class ClassName: @classmethod def build__json(cls, queryset): geojson_str = serialize('json', queryset, fields=('result') ) my_geojson = json.loads(geojson_str) return my_geojson qs_json = ClassName.build_json(qs) Is there a way to use serialize to do this? Or do I need to write a custom class? PS: I'm not building a view, just trying to convert a queryset into a json. Thanks in advance -
How to access the Data of an model using particular id in django rest framework
I want to access the data of an model which is named as IssueReport by using it's ID in django rest framework so I used the post method for passing the ID manually to get the IssueReport data by that ID but it gives me the Error as, Method Not Allowed: /app/auth/getissuereport/ [10/Aug/2022 23:26:21] "GET /app/auth/getissuereport/ HTTP/1.1" 405 7036 Internal Server Error: /app/auth/getissuereport/ Traceback (most recent call last): File "D:\MMRDA\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\MMRDA\.venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\MMRDA\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\MMRDA\.venv\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "D:\MMRDA\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\MMRDA\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\MMRDA\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\MMRDA\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\MMRDA\mmrda\apis\views.py", line 195, in post report=IssueReport.objects.get(pk=id) File "D:\MMRDA\.venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\MMRDA\.venv\lib\site-packages\django\db\models\query.py", line 496, in get raise self.model.DoesNotExist( DataSet.models.IssueReport.DoesNotExist: IssueReport matching query does not exist. This is my views.py, class GetIssueReportById(generics.GenericAPIView): serializer_class=GetIssueReportSerializer def post(self,request,*args,**kwargs): serializer=self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): id=serializer.data.get('id') report=IssueReport.objects.get(pk=id) data=IssueReportSerializer(report,context=self.get_serializer_context()).data return Response({ 'message':"Data Fetched successfully", 'status':"success", 'data':data, },status=status.HTTP_200_OK) else: return Response({ … -
Passing Javascript value into CSS?
I'm trying to pass my javascript value (a percentage) into the css 100% width line which is currently at 30%. This currently creates a table that populates outward, starting at 0 and then going out to 30%, I want to be able to implement my Javascript value (c2_percent) instead of the 30% value. If anyone can help that would be great. Thanks <div class="bar-graph bar-graph-horizontal bar-graph-one"> <div class="bar-one"> <span class="rating-a1">A1</span> <div class="bar" id="rating-a1" data-percentage=""></div> </div> <div class="bar-two"> <span class="rating-a2">A2</span> <div class="bar" data-percentage="11%"></div> </div> <div class="bar-three"> <span class="rating-a3">A3</span> <div class="bar" data-percentage="7%"></div> </div> <div class="bar-four"> <span class="rating-b1">B1</span> <div class="bar" data-percentage="10%"></div> </div> <div class="bar-five"> <span class="rating-b2">B2</span> <div class="bar" data-percentage="20%"></div> </div> <div class="bar-six"> <span class="rating-b3">B3</span> <div class="bar" data-percentage="5%"></div> </div> <div class="bar-seven"> <span class="rating-c1">C1</span> <div class="bar" data-percentage="9%"></div> </div> <div class="bar-eight"> <span class="rating-c2">C2</span> <div class="bar" id="c2-rating" data-percentage=""></div> </div> <div class="bar-nine"> <span class="rating-c3">C3</span> <div class="bar" data-percentage="5%"></div> </div> <div class="bar-ten"> <span class="rating-d1">D1</span> <div class="bar" data-percentage="5%"></div> </div> </div> @-webkit-keyframes show-bar-eight { 0% { width: 0; } 100% { width: 30%; } } <script> for(let i = 0; i < 1; i++) { const c2_security_values = Array.from(document.querySelectorAll('.security-value-c2')); const c2_security_values_inner = c2_security_values.map((element) => element.innerText); const c2_summed_values = c2_security_values_inner.reduce((accumulator, currentValue) => parseInt(accumulator) + parseInt(currentValue)); const total_security_values = Array.from(document.querySelectorAll('.individual-market-value')); const total_security_values_inner = total_security_values.map((element) … -
CORS error during API call for React/DRF app on Heroku
I have my react front end and my django rest api as two separate apps on heroku. I'm having the issue of the following error: The request options I use for the fetch request on the frontend: const credentials = btoa(`${data.get('username')}:${data.get('password')}`); const requestOptionsSignIn = { method: "POST", credentials: 'include', headers: { 'Accept': 'application/json, text/plain', 'Content-Type': 'application/json', "Authorization": `Basic ${credentials}` }, body: JSON.stringify({}) } And my Django/django-cors-headers settings: CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['https://_____frontend.herokuapp.com'] CORS_ALLOW_HEADERS = ("x-requested-with", "content-type", "accept", "origin", "authorization", "x-csrftoken") I've tried playing around with the settings but I can't get it to work. -
Return fields in a custom format in serializer Django Rest Framework
I am very new to Django rest framework and I am looking to return a the model field serializer in a custom format. This is the serializer: class SubjectSkillLevelSerializer(serializers.ModelSerializer): class Meta: model = SubjectSkillLevel fields = ["subject", "level"] It currently returns this: [ { "subject": 1, "level": 1 }, { "subject": 2, "level": 1 } ] How can I make the serializer return a custom format like this { 1 : 1, 2 : 1 } What I tried: def to_representation(self, value): return "%s : %s" % ("subject", "level") But it obviously didn't work and just returned the strings. -
Set django form value from javascript variable
I created a registration form in a django template. I have a variable in javascript which is get a value(which character choiced by the user) and I want to pass that variable to the form value. How I can make it work? <form method="POST" action=""> {%csrf_token%} <div class="input-group mb-2"> {{form.username}} </div> <div class="input-group mb-2"> {{form.email}} </div> <div class="input-group mb-2"> {{form.password1}} </div> <div class="input-group mb-2"> {{form.password2}} </div> <div class="input-group mb-2"> {{form.character_type}} </div> <input type="submit" value="Register Account"> </form> -
Django get the value of a field in the __init__ of forms
I need to have the value of a field before doing an update. forms.py class Form_Rol(forms.ModelForm): class Model: model = My_Model fields = "__all__" def __init__(self, *args, **kwargs): '''I want to do this''' value_coming_from_update = self.fields['name'] print(value_coming_from_update) Output.... <django.forms.fields.CharField object at 0x0000026649558DC0> How do I print the actual value in init? I can't use self.cleaned_data.get('name') in init. It gives me an error (AttributeError: 'Form_Rol' object has no attribute 'cleaned_data') -
session list is not updated after the from is submitted in Django
from django.shortcuts import render from django import forms from django.urls import reverse from django.http import HttpResponseRedirect # Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label="New Task") def index(request): if "tasks" not in request.session: request.session["tasks"] = [] return render(request,"tasks/index.html",{ "tasks":request.session["tasks"] }) def add(request): if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): newtask = form.cleaned_data["task"] request.session["tasks"] += [newtask] return HttpResponseRedirect(reverse("index")) else: return render(request,"tasks/add.html",{ "form" : form }) return render(request,"tasks/add.html",{ "form" : NewTaskForm() }) I Add the newtask to our list of tasks If the form is invalid, re-render the page with existing information. -
Checking the type of an argument in Django Python views
I have more experience with C (intermediary expertise) and now working on something in Django Python. I have a url function which directs a REST call to a views function. Now, I am trying to make a single url for passing an argument for both an ID (int) and an email (str/EmailField) to land on the same views function and I can then unpack the type of the arg sent and do something different. I want the url to be argument type agnostic and then do the conditional check in the views function. But it looks like each time, the argument is sent as a str (even when the id is sent). I believe there may be 2 things here I do not fully understand: perhaps the argument will always be sent to the view function as a str all the time? Or there may be an issue with my type checking (as you can see I am trying to cast the type of the arg and check if true. Seems more like a C method of doing stuff? Thank you! urls.py looks like path('<arg>/', views.getUpdateDeleteAccount), ->> this is what I am trying to do #path('<int:pk>/', views.getUpdateDeleteAccount), ->>> works in … -
For Django file upload can I set the models.FileField directly without using any Form or web input
Every example of uploading I can find for Django uses a web input to get the file. But I am getting the files from an array of REST api end points and I receive the files as byte strings. I am using a Model class with boto3 backend storage to upload to S3. I can upload files using the django admin but fail to do it manually. The actual code is too long but here is some pseudo code. My question is what is the data type I need for x in this line: zipf.zipfile = x Here is the pseudo code: class UploadedZip(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='zipfiles') name = models.CharField(max_length=102) zipfile = models.FileField(upload_to="zipfile") def getfiles(request): files = apicall() # Returns include a list of links for f in files: # the return can be a byte string of data or I could save it to a tmp file if I need to x = callapi_inline(request, f.apiurl) if x and len(x) > 0: zipf = UploadedZip() zipf.zipfile = x zipf.name = f[0]['name'] zipf.user = request.user zipf.save() -
I want to migrate the changes of models.py but it says the object has no attribute 'urls', i have to write urls.py first?
I have registered the models in admin.py the whole things I've changed in this app are in admin.py and models.py I didn't created the urls.py this is my models.py: from django.db import models class Clients(models.Model): name = models.CharField(max_length=300) company = models.CharField(max_length=300) def __str__(self) -> str: return self.company class Manufacturers(models.Model): name = models.CharField(max_length=300) location = models.TextField("address") def __str__(self) -> str: return self.name class Products(models.Model): cost_per_item = models.PositiveBigIntegerField("Cost") name_of_product = models.CharField("name") manufacturer = models.ForeignKey(Manufacturers, on_delete=models.CASCADE) def __str__(self) -> str: return self.name class ClientOrders(models.Model): fulfill_date = models.PositiveIntegerField("Fulfill Month") order_number = models.PositiveIntegerField(primary_key=True) client = models.ForeignKey(Clients, on_delete=models.CASCADE) products = models.ManyToManyField(Products) def __str__(self) -> str: return self.client and this is the error: AttributeError: 'ClientOrders' object has no attribute 'urls' -
404 error when getting file in static, django
I tried several attempts through googling, but it didn't work. I don't think it was like this when I was working on another Jango project, but I don't know why. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.HomeView.as_view(), name = 'home'), #to home.html path("blog/", include('blog.urls')), ] # urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "static/" STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static") home.html <img src="{% static 'assets/img/navbar-logo.svg' %}" alt="..." /> directory Project-folder | |__config | |__settings.py | |__urls.py | |__app | |__template | |__app | | |__bla.html | |__home.html | | #bootstrap |__static |__assets |__img ... -
How to create Date from year and month (IntergerFields in Django Form)
I have a selection in Django Form based on year and month (as integer fields) and I would like to create and save also Date value (first day of particular month and year) to link it to another table. My function in forms.py: def date_creation(year, month): if year and month: y = str(year) m = str(month) if len(m) == 1: m = "0"+ m entry = f"{y}-{m}-01 00:00:01" date1 = datetime.strptime(entry, '%Y-%m-%d %H:%M:%S') date2 = date1.strftime('%Y-%m-%d') return date2 else: return 0 models.py class MonthlyCosts(models.Model): y = int(date.today().year) y1 = y - 1 y2 = y - 2 year_selection = ( (y, y), (y1, y1), (y2, y2), ) months_selection = ( (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ) year = models.IntegerField("Year", choices=year_selection) month = models.IntegerField("Month", choices=months_selection) date = models.DateField("Date", null=True, blank=True) When I tried function above in my form, so I got following error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data '<django.forms.fields.IntegerField object at 0x102c521c0>-<django.forms.fields.IntegerField object at 0x102c52280>-01 00:00:01' does not match format '%Y-%m-%d %H:%M:%S Thanks a lot for help, L.