Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Math expression in html format
My study shows the only effective method to include the mathematical expression on my html pages is mathType. It converts the math expression to html code. That is not supported in some of the browsers (including chrome) however. Is there any alternative? -
Django: How to pass value from one CBV to another
I'm trying to customize django authentications forms/templates. URL /accounts/password_reset/ (CBV:PasswordResetView) is used to enter account email. After form submitting user redirected to /accounts/password_reset/done/ (CBV:PasswordResetDoneView) I need to use email value in PasswordResetDoneView. How can I do it? Sorry for newbie question. urls.py from django.urls import path, include from . import views urlpatterns = [ # ... path('accounts/password_reset/', views.CustomPasswordReset.as_view(), name='password_reset'), path('accounts/password_reset/done/', views.CustomPasswordResetDone.as_view(), name='password_reset_done'), # ... ] views.py from django.contrib.auth import views as auth_views from .forms import LoginForm, ResetForm, NewPasswordForm class CustomPasswordReset(auth_views.PasswordResetView): template_name = 'authorization/password_reset_form.html' html_email_template_name = 'authorization/password_reset_email_html.html' email_template_name = 'authorization/password_reset_email_plain.html' subject_template_name = 'authorization/password_reset_subject.txt' class CustomPasswordResetDone(auth_views.PasswordResetDoneView): template_name = 'authorization/password_reset_done.html' # TODO. I have no idea how to get email address that was entered in 'password_reset' step # email = 'example@gmail.com' mbox, mserver = email.split('@') extra_context = {'mserver': mserver} -
What is the best way to schedule a task, scheduler or bots?
I'm making a website, and I need everyday some specific tasks will run automatically at a specific time.What's the best way to do that? -
How do I annotate a django queryset with StringAgg or ArrayAgg concatenating one column from mulitple children rows?
Documents is the parent table. Paragraphs is the child table. Users filter Documents based on various search criteria. Then I wish to annotate Documents with certain Paragraphs filtered by a text query. The same text query is used to filter Documents and rank them (SearchRank). This ranking makes it necessary to start from Documents and annotate them with Paragraphs, instead of starting from Paragraphs and grouping them by Document. The postgresql way of concatenating one text field from multiple rows in Paragraphs would be the following: SELECT array_to_string( ARRAY( SELECT paragraph.text FROM paragraph WHERE document id = '...' ORDER BY paragraph.number), ''); I am trying to translate this into django coding. I have tried numerous django approaches, to no avail. I can annotate 1 Paragraph. Query_sum is a Q() object built from user input. results = Documents.filter(Query_sum) sub_paragraphs = Paragraphs.filter(Query_sum).filter(document=OuterRef('id')) results = results.annotate(paragraphs=Subquery(sub_paragraphs.values('text')[:1], output_field=TextField())) Problems start when I get rid of slicing [:1]. results = results.annotate(paragraphs=Subquery(sub_paragraphs.values('text'), output_field=TextField())) I then get the following error: "more than one row returned by a subquery used as an expression". To fix that, I tried to use ArrayAgg and StringAgg. I made quite a mess ;-) The Documents queryset (result) should be annotated either with … -
how to override returned serializer object that is returned with the response django rest framework serializer
I have a django rest framework project. I want to override the returned json object structure when a get request is made to display a specific way not similar to the database structure. My current return object is displayed like so: { "id": 9, "namespace": "steve", "path": "something/another", "value": "this is a value", "person": 1 }, { "id": 11, "namespace": "namespace1", "path": "path2", "value": "anyoher value", "person": 2 }, { "id": 12, "namespace": "namespace1", "path": "path3", "value": "this dsiaalks", "person": 2 }, { "id": 13, "namespace": "namespace2", "path": "path4", "value": "asdfasdfasdf", "person": 2 }, I want to switch the "person":2 to display "user":{ "userId":testUser } testUser is the username of the user with id 2 * THis is my current serailzer: from rest_framework import serializers from .models import Preference from django.contrib.auth.models import User class PreferenceSerializer(serializers.ModelSerializer): person = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),) class Meta: model = Preference fields = ('id', 'namespace', 'path', 'value', 'person') and this is the current model: from django.db import models from django.contrib.auth.models import User from owf_framework.people.models import Person class Preference(models.Model): id = models.BigAutoField(primary_key=True, null=False) version = models.BigIntegerField(default=1, null=False) path = models.CharField(max_length=200, null=False) namespace = models.CharField(max_length=200, null=False) value = models.TextField(null=False) user_id = models.BigIntegerField(null=False, default=1) person = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
Django rest framework - no such table
I'm trying to create an API endpoint on my Django project to retrieve data from my frontend. I'm using two DBs on my django project, the first one is a SQLite DB, the second one is a MongoDB database, the data i need to retrieve is on MongoDB. Here is my model: class tst(models.Model): _id = models.CharField(max_length=100) ticker = models.FloatField() def save(self): # ALL the signature super(Trade, self).save(using='dbtwo') Here is my view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.all() serializer_class = tstSerializer And the url: path('tst/', views.tstList.as_view()), Everything is alright here but when i try to open the API from my browser, i keep getting the following error: OperationalError at /tst/ no such table: main_tst I think this happens because it tries to look for the table tst on the first SQLite database, instead of looking for it on the MongoDB one. Is there any way to solve this? I thought that adding using='dbtwo' would do it, but it's not the right solution. Every advice is appreciated! -
Django - Render HTTP before database connection
I have a serverless database cluster that spins down when it's out of use. Cold starts take a minute or so, during which django just waits and waits to send the http request object back. Before I code something complicated, I'm looking for recommendations for an existing middleware/signal integration that would allow me to render an interim view while django attempts to get the database connection (for instance, if the database query takes longer than a second to complete, render to this view instead.) -
Django multi-form validation from different models
I have been struggling to normalize a few tables/models I have in Django that are to be used in one large form. Let's say I have 2 forms based off of 2 models, 1 of which is dependant of the other. Is there a way to add form validations in 1 model when a specific selection is made in a different model? I can provide code if it'll help, but want to see if this is even possible. So basically, in 1 form I need to reference fields which are in a different model (a different modelForm that's instantiated on the same page) Form2 based off table/model2 : def clean(self): cleaned_data = super().clean() if 'model1_field' in cleaned_data and not cleaned_data['model2_field']: self.add_error('model2_field', forms.ValidationError('This field is required.')) else: print('No validations are needed') -
Accessing the request object from within a class based view? Needed to determine if the request is coming from a mobile device
I have the following CBV: class Index(TemplateView): template_name = 'index_app/index.html' As well as a function that could take the a request object and return whether its coming from a mobile device or not: def mobileBrowser(request): mobile_browser = False ua = request.META['HTTP_USER_AGENT'].lower()[0:4] if (ua in mobile_uas): mobile_browser = True else: for hint in mobile_ua_hints: if request.META['HTTP_USER_AGENT'].find(hint) > 0: mobile_browser = True return mobile_browser I want to be able to use this to do something like the following in my CBV: class Index(TemplateView): if mobileBrowser(request): template_name = 'index_app/mobile/index.html' else: template_name = 'index_app/index.html' This isn't possible, as a CBV doesn't seem to have access to the request object. Is there any way that this object can be accessed in this situation? I know it would be possible to create a standard view instead, but later on I would like to continue using CBVs like CreateView and whatnot, which will just land me in the same situation again. -
Why does not redefining the add and change form?
Подскажите почему не работает переопределение формы add_form, form? forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True, label="Email") phone = forms.CharField(label="Phone number") class Meta: model = User fields = ("username", "email", "phone", "password1", "password2",) class CustomUserChangeForm(UserChangeForm): email = forms.EmailField(required=True, label="Email") phone = forms.CharField(label="Phone number") class Meta: model = User fields = ("username", "email", "phone", ) admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'phone', ] admin.site.register(CustomUser, CustomUserAdmin) -
Django Rest Framework Custom JWT authentication
I created a Django app in which I want to be able to authenticate users by checking not only the username and password, but also a specific field in a related model. The custom request body I want to POST to the endpoint is: payload = { 'username': user, 'password': password, 'app_id': uuid4} I am using djangorestframework-simplejwt module to get the access token. models.py class Application(models.Model): app_name = models.CharField(max_length=300) app_id = models.UUIDField(default=uuid.uuid4, editable=False) def __str__(self): return self.app_name class ProfileApp(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) app = models.ForeignKey(Application, on_delete=models.CASCADE) expires_on = models.DateTimeField(default=datetime.now() + timedelta(days=15)) def __str__(self): return self.app.app_name + " | " + self.user.username Is it possible to override the TokenObtainPairView from rest_framework_simplejwt to only authenticate an user if the expires_on date is still not expired? Or is there an architecture problem by doing it like this? -
How do I update a generic class-view?
I have a django app that stores information on different profiles of people. I want to be able to provide a downloadable spreadsheet and update a class-view(ListView) on the website using the same url. I don't fully understand class views yet and I'm struggling to figure out how to combine the two view functions below. I tried this: views.py class ProfileList(ListView): model = Profile #template_name = 'search.html' def get(self, request): return export_profiles(request) def export_profiles(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="profile_list.csv"' writer = csv.writer(response) writer.writerow(['Name','Title','Location','Phone','Email','Company Name','Company Size','Link']) data = Profile.objects.filter() for row in data: rowobj = [row.name,row.title,row.location,row.phone,row.email,row.GetCompany().companyName,row.GetCompany().companySize,row.url] writer.writerow(rowobj) #Clean up database return response urls.py urlpatterns = [ path('search/', views.search, name='search'), path('profiles/', ProfileList.as_view()), path('accounts/', include('django.contrib.auth.urls')), url('session_security/', include('session_security.urls')), ] This worked for downloading the file, but still didn't update the profile list with the django as_view() function. It just downloaded the csv file without erroring. This is what I currently have: views.py #Post a view of profiles on the website when a search is initiated class ProfileList(ListView): model = Profile template_name = 'search.html' @login_required def export_profiles(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; … -
How can i use MongoDB with Django Rest Framework?
I would like to use Django Rest Framework with a MongoDB database but i don't really know where to start. Is it possible to do it? I tried to look for some help online, but i found very little material. I heard there was a module called django-rest-framework but it's not longer supported, is there anything else i can use? -
How can I get exceptions from django-rest in my vue.js method?
I'm using django-rest-passwordreset for forgotten password recovery. In my Vue.js I have a method to set a new password. It works, but I need to get exceptions if a password is too short of too common etc... Here is my vue.js set_password: methods: { set_password() { axios.post('/app/reset-password/confirm/', {'password': this.password, 'token': this.token}) .then(response => { console.log(response) }) .catch(error => { console.log(error) }) } }, If I send POST request to http://localhost:8000/app/reset-password/confirm/ using RestMan to raise exceptions on django server, for example: a short password I'm getting: { "password": [ "This password is too short. It must contain at least 8 characters.", "This password is too common." ] } but in my vue.js set_password() I really cannot get these exceptions. In browser console I'm getting: POST http://localhost:8000/app/reset-password/confirm/ 400 (Bad Request) Error: Request failed with status code 400 at createError (build.js:15685) at settle (build.js:27186) at XMLHttpRequest.handleLoad (build.js:15559) If I send a good password(not short, etc...) I will 'response' in my browser console: {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …} But How can I get exceptions from my django server? -
Weird behavior while testing: It works without any problem but gives error while testing
I have a small function which rounds the Decimal numbers and my function is as follows: from decimal import Decimal, ROUND_UP def convert_decimal(decimal_number): return decimal_number.quantize(Decimal('0.01'), rounding=ROUND_UP) It works properly in my code when I run the django project without any problem. The function works without any error. But when I try to the code as below it fails with a weird error: class UtilityFunctionsTests(TestCase): def test_decimal_number(self): decimal_number = Decimal("23.54646354745375634756868") converted = convert_decimal(decimal_number) self.assertEqual(converted, Decimal("23.55")) The failing error is as follows: integration/tests/test_base_updater.py:78: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ decimal_number = Decimal('23.546463547453758025085335248149931430816650390625') def convert_decimal(decimal_number): > return decimal_number.quantize(Decimal('0.01'), rounding=ROUND_UP) E decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] entegrasyon/tests/test_base_updater.py:11: InvalidOperation -
Array convert to string in views django
i have a array in Django views and i want to convert into comma separated string, to save data into DB field like all in one. class FindInfo(object): def __info__(request): if request.method == 'POST': name = request.POST.get('name') address = request.POST.get('address') phone = request.POST.get('phone') info = {} info['name'] = name info['address'] = address info['phone'] = phone info = ["Younus", "DHA-A251", "+923228738738"] i did't get anything how to do that? and i need output like this. sting = "Ford,Volvo,BMW" -
How do I convert a Django QuerySet into a Map with List of Objects?
I need to filter and map the result to a map of string keys and list of object values. Something like in Java will result to Map<String, List<SomeDbMoel>>. -
How can i fixed PostgreSQL setup problem from Django
I created postgreSQL in django project. When i do migrate for database it's return this exception. django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' I tried postgresql_psycopg2 and pip install psycopg2-binary but not work DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'eatadil', 'USER': 'postgre', 'PASSWORD': 'realpassword', 'HOST': 'localhost', 'PORT': '5432', } } How can i fix this problem. Can you help me ? -
Row cells not showing up in django-tables2 by default, model issue?
I think there may be an issue with a work django project I inherited. I'm using django-tables2 to display info. Mostly it works in an intuitive way. However, some tables when I render them the actual columns that contain the data cells do not show up. All the table properties show up as columns, but not the data columns. I think the issue may be related to how the model is laid out. a given cell has a row and column property. Rows have a cell_set and a table property but no column_set. Tables have a row_set and column_set property. So is the issue here maybe that the Rows have no column_set property? So when it looks for data to render it isn't finding those columns. If I'm tying to get all the cells associated with a row it's a clunky process of iterating over each column looking for the cell in the cell set that belongs to that column (see below). (I can design customized columns in django_tables2 views in some cases but have an app were users can create tables themselves which need to be rendered dynamically.) As an example, here's the __str__method for Row: def __str__(self): cell_values … -
Django can open image, but not saving it to database
I created a form that will ask for a name and an image to be uploaded in django. In my views, I am using pytesseract to read the text on the image. I was able to successfully save the name and text parameters into the database, but the image itself does not save. `# models.py class Component(models.Model): Serial_number = models.CharField(max_length=20, primary_key='True', default = '') image = models.ImageField(blank=True) text = models.TextField(default = 'no text found') Good_Candidate = models.BooleanField(default=False) dimension1 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) #forms.py class partForm(forms.ModelForm): Serial_number = forms.CharField(max_length=128) class Meta: model = Component fields = ['Serial_number', 'image', 'text', 'dimension1'] widgets = {'dimension1': forms.HiddenInput(), 'text':forms.HiddenInput()} #views.py def image_view(request): form = partForm(request.POST, request.FILES) if form.is_valid(): # make copy of the data data = request.POST.copy() # access image data through FILES and calling the name attribute image_file = request.FILES.get('image') text_content = pytesseract.image_to_string(Image.open(image_file)) data['text'] = text_content # get largest dimension text_list = [] zeros = ['O', 'o'] badChars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', … -
Customize the return object from django rest framework serializer
I want to customize the django rest framework serializer return object to a specific requirement. right now it returns the fields in a single object that is not nested. { "id": 9, "namespace": "steve", "path": "something/another", "value": "this is a value" }, and this is what I want the outcome to look like: { "id": 6, "namespace": "tempnamespaced", "path": "randompath", "value": "anothertest", "user": { "userId": "testUser1" } } So i want to add a nested object named user and add the userID value within the user. the data that is returned in the userId is actually person.username person is a model username so the data is going to look like this when it is assigned and returned: "user": { "userId": {{person.username}} } I will attach mmy code below: serializer: from rest_framework import serializers from .models import Preference from django.contrib.auth.models import User class PreferenceSerializer(serializers.ModelSerializer): # person = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),) class Meta: model = Preference fields = ('id', 'namespace', 'path', 'value') here is the get viewset: @permission_classes((IsAuthenticated)) def get_queryset(self): namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: queryset = Preference.objects.all().filter(user_id=1) if namespace and path is None: queryset = Preference.objects.all().filter(user_id=1, namespace=namespace) if namespace and path: queryset … -
Is it possible to perform mathematical operations on information entered into a Django form?
I'm trying to make a pretty simple web app with a few pages. On one of the pages, let's say I take in 6 numbers from the user. I then want to perform mathematical operations on these inputs e.g., +,-,*,/. After these operations, I want to output a single number for the user to see. Is this possible using Django forms and if so how? If it isn't possible, please recommend an alternative method in Django. -
How to fix data that is not displayed on site Heroku?
I deployed site on Django in Heroku. I've Connected PostgreSQL (also have locally), created migrations (I've checked, all tables exist). But on the site I haven't any data. What should I do, that fix this? -
How to properly run virtualenv via .sh run script (django)
I am having an issue via an apache Nearly Free Speech server (I have been following the NFS guide via this link: https://blog.nearlyfreespeech.net/2014/11/17/how-to-django-on-nearlyfreespeech-net/. I have created a run-django.sh file to properly run the application which also opens a virtualenv (I have named the folder 'venv'). These are the contents of my run-django.sh file: #!/bin/sh . venv/bin/activate exec python3 manage.py runserver On the current step of the guide I am attempting to run the run-django.sh as follows: [questionanswer /home/protected]$ ls question_answer run-django.sh venv [questionanswer /home/protected]$ cd question_answer/ [questionanswer /home/protected/question_answer]$ ../run-django.sh .: cannot open bin/activate: No such file or directory How is this not detecting my directory of 'venv/bin/activate' ? -
Refreshing OAuth2 Access Tokens in Serverless Application
I'm creating a project in Django (v2.2) with a REST backend though Django Rest Framework (v3.9.4). This REST API is consumed by both SPAs and headless applications running on external servers. All views require user authentication with appropriate permissions. The front-end SPAs are able to use Session Authentication and pass this along to the REST API no problem. However, Session Authentication is not appropriate for headless servers and autonomous functions that we want to be able to consume the API as well. I've settled on using Django OAuth Toolkit (v1.2.0) to provide authentication using OAuth2. My issue is as follows. Developers who wish to consume the API from some headless environment can generate an access token using password-based or client credentials grant type (or any of the other types, really). This gives them an access token, an expiry time, and a refresh token. For applications which have a stateful server, they can store the access and refresh tokens in a file, environment variable, etc. When the token expires, they can use the refresh token to acquire a new access token, and overwrite the file or environment variable so that it is available going forward. However, some of our applications exist …