Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using jQuery to Access Django Database
Okay, so I have been trying to figure this out for about a week and I can't find a straight answer on the internet: I am making Django website and I need to access my database (which is SQLite3) in jQuery to edit the contents of my site. Let's say I have a one-dimensional database like this: in my Django "Views.py" I have this: from exampleapp.models import database def page(request): data = database.objects.all() return(render(request, "homepage.html", {"data": data})) In my HTML file, I have this (which is an iteration of the database): {% for x in data %} <p id = {{x}} > {{x}} </p> {% endfor %} Which outputs this on the HTML Page: Anyways, the id of each DOM element is equal to it's content ("apple", "cheese", etc...). I would like to reference these id's in jQuery so I can edit them. For instance, if wanted to reference the element with the id = "cheese", how can I do that in jQuery? I understand that there is an Ajax function in jQuery which allows it to parse JSON. I can convert my database into JSON format with this in my "Views.py" file (but I still don't know how to … -
How to make dropdown currenycode-countryname in django model
I need to make dropdownlist like this, AED-UAE Dirham AFN-Afghani... For all countries. When I use CountryField() from django-countries I have got all country names only in the dropdown list. how can I get currencycode-country name as a dropdownlist in django model?? -
How to pass date and id through url in django
I am trying to pass date and id through url, but getting an error, I have passed just id before and I usually do it like this. path('user_payment_menu/<int:pk>/',user_payment_menu, name='user_payment_menu'), but now I want date to pass after int:pk/ but when I add date after a slash I am getting an error. -
Django Rest Auth using google authentication
url.py urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('rest_auth.urls')), path('', GoogleLogin.as_view()), path('auth/google/callback/', google_callback, name='google_callback'), path('auth/google/url/', google_views.oauth2_login) ] views.py import urllib.parse from allauth.socialaccount.providers.google import views as google_views from allauth.socialaccount.providers.oauth2.client import OAuth2Client from django.contrib import admin from django.shortcuts import redirect from django.urls import include, path, reverse from rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = google_views.GoogleOAuth2Adapter client_class = OAuth2Client @property def callback_url(self): # use the same callback url as defined in your GitHub app, this url must # be absolute: return self.request.build_absolute_uri(reverse('google_callback')) enter code here def google_callback(request): params = urllib.parse.urlencode(request.GET) return redirect(f'http://localhost:8000/accounts/google/login/callback/') Client ID for Web application URIs :http://127.0.0.1:8000 Authorised redirect URIs : http://127.0.0.1:8000/auth/google/callback/ error: Authorization Error Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console. Learn more The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google. If you’re the app developer, make sure that these request details comply with Google policies. redirect_uri: http://localhost:8000/auth/google/callback/ Pl help me. Thank you in advance. django-rest-auth using google authentication any reference documentation pl share me. -
how to filter only the rows containing first occurrence of an item in Django query
I have below data from my Django model id Date value 0 1975 a 21 1975 b 1 1976 b 22 1976 c 3 1977 a 2 1977 b 4 1978 c 25 1978 d 5 1979 e 26 1979 f 6 1980 a 27 1980 f I have this: id Date value 0 1975 a 21 1975 b 1 1976 b 22 1976 c 3 1977 a 2 1977 b 4 1978 c 25 1978 d 5 1979 e 26 1979 f 6 1980 a 27 1980 f I am having trouble finding a way to keep only the lines containing the first occurrence of a'value'. I want to drop duplicate 'values', keeping the row with the lowest 'Date'.The end result should be: id Date value 0 1975 a 21 1975 b 22 1976 c 25 1978 d 5 1979 e 26 1979 f -
How to save multiple dynamically created forms in django
I am trying to create a page where various data corresponding to mutliple models can be input by the user, and to have an option to dynamically add additional forms. I have been attempting to use htmx for this and am able to dynamically add forms, however when I save it is only the last entered form that is saved. I haven't used formsets as this wont integrate well with htmx https://justdjango.com/blog/dynamic-forms-in-django-htmx#django-formsets-vs-htmx. Code below any suggestion as to how to get all the dynamically created forms to be save would be most appreciated! models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) forms.py from django import forms from .models import Book, Author from crispy_forms.helper import FormHelper class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-CaseForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_tag = False class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_tag = False self.helper.form_show_labels = False views.py class create_book(TemplateView): template_name = 'create_book.html' def get(self, *args, **kwargs): author_form = AuthorForm book_form = … -
How do I design my django app which fetches the data from a legacy database which has huge number of tables?
I am developing a Django app which fetches the data from a huge database and then perform some statistical operation and prints the result. There are different ways available but I want to know what is the best way of doing it? Dataset have a lot of tables, so is it advisable to create models for all those tables? and use Django ORM to replicate below query? OR else I should not use Models at all and use RAW SQL query to fetch the data from database and perform operation and then show the result. If yes then please suggest the best way of doing it. "USE r_d; SELECT nus.noyau_utilisateur_id as "candidate_id", pcon.id as "assessment_id", pcon.created_at as "assessment_creation_date", YEAR(pcon.created_at) as "assessment_year", tti.libelle as "test_name", tfi.libelle as "factor_name", pcal.score_reel as "real_score", pcal.score_brut as "raw_score", pcal.score_calcule as "calculated_score" FROM `passation_calcul` pcal JOIN `passation_contrat` pcon ON pcon.id = pcal.passation_contrat_id JOIN `noyau_utilisateur_societe` nus ON nus.id = pcon.noyau_utilisateur_societe_id JOIN `test_test` tt ON tt.id = pcon.test_test_id JOIN `test_test_i18n` tti ON tt.id = tti.test_test_id JOIN `test_facteur` tf ON tf.id = pcal.id_ref JOIN `test_facteur_i18n` tfi ON tf.id = tfi.test_facteur_id WHERE pcon.test_test_id = 144 AND pcon.etat = "COMPLETED" AND tti.noyau_ref_langue_produit_id = 1 AND pcal.table_ref = 'test_facteur' AND tfi.noyau_ref_langue_produit_id = … -
Does Django's collectstatic command double the space used in production?
I understand that collectstatic command copies static-files found in different Django apps of the Django project to a defined single path so that webserver can easly serve files. Here is what question me: For example, I have many big static-files in several apps and I push my Django project to production. I run collectstatic. The static-files will be copied to project static folder. It means that the static-files are now in two different locations so use twice the storage isn't it? I probably miss a point somewhere in the production deployment process because it doesn't feel right to me in term of storage space. -
DRF test Swagger Fake View in get_queryset
I am able to test get_queryset() in ReadOnlyModelViewSet like this. class CatalogViewTests(APITestCase): def setUp(self) -> None: self.cur_user = UserFactory() self.cur_dataset = DataSetFactory(created_by=self.cur_user) @patch.object(CatalogView, "permission_classes", []) def test_get_queryset(self): url = reverse('data_tab:catalog-list') response = self.client.get(url, format='json', **{DATASET_ID: self.cur_dataset.id}) self.assertEqual(response.status_code, status.HTTP_200_OK) views.py class CatalogView(ReadOnlyModelViewSet): """ Returns the Data tab catalog page with pagination """ serializer_class = CatalogSerializer permission_classes = [UserHasDatasetChangeAccess] pagination_class = StandardResultsSetPagination queryset = TableMeta.objects.all() renderer_classes = [JSONRenderer] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] def get_queryset(self): if getattr(self, "swagger_fake_view", False): # queryset just for schema generation metadata return TableMeta.objects.none() return TableMeta.objects.filter( dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, "")) ).prefetch_related( "table_columns", "table_metrics", "table_relationship_source" ) Test case is running properly and I am getting the output as expected. But in test_report this line is not tested. As we can see red line is still showing untested because it is expecting swagger_faker_view variable to be true. does anyone know how to write test case for this scenario ? -
Digital Ocean deployment using a heroku buildpack
After numerous attempts to deploy via Heroku without success due to an issue with GDAL I have switched to digital ocean. For some reason, thought, digital ocean appears to be accessing the heroku/python python buildpack, despite there being no heroku dependencies in my requirements.txt (see below). Here is the build log from D.O: [...] [vygr] [2022-01-19 08:38:05] 3 of 4 buildpacks participating [vygr] [2022-01-19 08:38:05] digitalocean/python-appdetect 0.0.2 [vygr] [2022-01-19 08:38:05] heroku/python 0.205.4 [vygr] [2022-01-19 08:38:05] digitalocean/procfile 0.0.3 [...] I'm wondering how I remove this because I think it is causing a conflict in the deployment (concerning GDAL): [vygr] [2022-01-19 08:38:54] During handling of the above exception, another exception occurred: [vygr] [2022-01-19 08:38:54] [vygr] [2022-01-19 08:38:54] Traceback (most recent call last): [vygr] [2022-01-19 08:38:54] File "/tmp/pip-install-9oduhk43/gdal_84e5a56c81ab48e493ea76e58e0ca754/setup.py", line 195, in get_gdal_config [vygr] [2022-01-19 08:38:54] return fetch_config(option) [vygr] [2022-01-19 08:38:54] File "/tmp/pip-install-9oduhk43/gdal_84e5a56c81ab48e493ea76e58e0ca754/setup.py", line 108, in fetch_config [vygr] [2022-01-19 08:38:54] raise gdal_config_error(e) [vygr] [2022-01-19 08:38:54] gdal_config_error: [Errno 2] No such file or directory: 'gdal-config' [vygr] [2022-01-19 08:38:54] [vygr] [2022-01-19 08:38:54] Could not find gdal-config. Make sure you have installed the GDAL native library and development headers. [vygr] [2022-01-19 08:38:54] ---------------------------------------- [vygr] [2022-01-19 08:38:54] WARNING: Discarding https://files.pythonhosted.org/packages/c5/f6/4fed0cacc8a6fb5d7659a05d300e01a1a13e2d9febf1911b05695057c662/GDAL-3.4.1.tar.gz#sha256=b19e8143bc2c0d3e222789a465d82b6874236eb78801aec608bf5c8c44d20fcf (from https://pypi.org/simple/gdal/) (requires-python:>=3.6.0). Command errored out with exit … -
When using the FileInput widget and passwordInput widget in Django modelform, data is not visible in the template
We are using the ModelForm, and among the fields are fields that use the FileInput widget and the passwordInput widget. A problem occurred on the page editing the data that has already been saved data. The code is as follows. # forms.py from django.forms import ModelForm from django.forms.widgets import TextInput, CheckboxInput, FileInput, PasswordInput, Select, Textarea from .models import Testcase class TestcaseForm(ModelForm): class Meta: model = Testcase fields = ('subject', 'content', 'content_type', 'attached_file', 'attached_file_password', 'request_for_inspection', 'firewall_is_set', 'additional_requests') widgets = { 'subject': TextInput(attrs={ 'id': 'subject', 'name': 'subject', 'class': 'form-control mb-3', 'placeholder': '', }), 'content': Textarea(attrs={ 'id': 'content', 'name': 'content', 'class': 'form-control mb-3', 'draggable': 'false', 'placeholder': '', }), 'content_type': Select(attrs={ 'id': 'content_type', 'name': 'content_type', 'class': 'form-select mb-3', }), 'attached_file': FileInput(attrs={ 'id': 'attached_file', 'name': 'attached_file', 'class': 'form-control mb-3', }), 'attached_file_password': PasswordInput(attrs={ 'id': 'attached_file_password', 'name': 'attached_file_password', 'class': 'form-control mb-3', 'placeholder': '', }), 'request_for_inspection': Select(attrs={ 'id': 'request_for_inspection', 'name': 'request_for_inspection', 'class': 'form-select mb-3', }), 'firewall_is_set': CheckboxInput(attrs={ 'id': 'firewall_is_set', 'name': 'firewall_is_set', 'class': 'form-check-input ', }), 'additional_requests': Textarea(attrs={ 'id': 'additional_requests', 'name': 'additional_requests', 'class': 'form-control mb-3', 'placeholder': '', }), } It's part of the view file. # views.py def TestcaseDetailViewer(request, id): testcase = get_object_or_404(Testcase, pk=id) if request.method == 'POST': form = TestcaseForm(request.POST, request.FILES, instance=testcase) if form.is_valid(): testcase = form.save(commit=False) testcase.save() … -
Django SQL syntax error when using two different database engines
I'm trying to use django with multiple databases. One default postgres-db and another mysql-db. I followed the documentation on how to configure both dbs: https://docs.djangoproject.com/en/4.0/topics/db/multi-db/ My settings.py looks like this: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "default", "USER": "----------", "PASSWORD": "-----------", "HOST": "localhost", "PORT": "5432", }, "data": { "ENGINE": "django.db.backends.mysql", "NAME": "data", "USER": "---------", "PASSWORD": "---------", "HOST": "localhost", "PORT": "3306", } } Things work fine when querying the default database. But it seems that django uses postgres-db syntax for queries on the mysql-db. Model "Test" lives in the mysql-db. Test.objects.user('data').all() # gives me the following exception psycopg2.errors.SyntaxError: ERROR: SyntaxError at ».« LINE 1: EXPLAIN SELECT `test`.`id`, `test`.`title`, ... As you can see, django generates postgres-db SQL code. It even uses the postgres-db client psycopg2 to execute it. Using a raw query works fine though, this means it does correctly use the mysql-db for the specific query. Test.objects.using('data').raw('SELECT * FROM test') # works How can i configure Django to use the correct SQL syntax when using multiple databases of different engines? Thanks! -
Why user autometically authenticated in test case
from django.urls import reverse from rest_framework.test import APITestCase from rest_framework.authtoken.models import Token from faker import Faker fake = Faker() APICLIENT = APIClient() from factory_djoy import UserFactory class TestAccount(APITestCase): def setUp(self): self.user = UserFactory() def test_print_name(self): print(self.user.is_authenticated) # do something here why print(self.user.is_authenticated) is True. I have tried to create a user using simply User.objects.create it also returns the same as is_authenticated to True. My understanding is that it should be not be True before doing login or force_authenticate. What am I doing wrong or is my understanding not correct? -
Django modelformset_factory filter a foreign_key field
My models.py is class CalculatorType(models.Model): id = models.AutoField(primary_key=True) calculator_name = models.CharField(max_length=255) calculator_scope = models.CharField(max_length=255) class Factor(models.Model): id = models.AutoField(primary_key=True) fuel = models.CharField(max_length=255) calc_type = models.ForeignKey(CalculatorType, on_delete=models.CASCADE) class DataTable(models.Model): id = models.AutoField(primary_key=True) org_id = models.CharField(max_length=255) fuel = models.ForeignKey(Factor, on_delete=models.CASCADE) my forms.py is like below DataTableModelFormset = modelformset_factory( DataTable, fields=('org_id', 'fuel'), extra=1, widgets={ 'org_id': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Org ID' } ), 'fuel': forms.Select(attrs={ 'class': 'form-control', 'onchange': "myChangeHander(this)", 'id': 'id_stationary-0-fuel' } ) } ) And finally my views.py is like def index(request): template_name = 'main/temp1.html' if request.method == 'GET': formset = DataTableModelFormset(queryset=DataTable.objects.none()) return render(request, template_name, { 'formset': formset }) Now I want to filter the fuel dropdown field of DataTable based on a specific calc_type of table Factor . I tried this creating a BaseModelFormSet but didn't help https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/ -
Django In views not able to get month name from month date
I have one field Monthly it is stored whole date(2022-01-19) When I tried in my views {{calendar.month_name[metric.monthly.month]}} It gives one error Could not parse the remainder: '[metric.monthly.month]' from 'calendar.month_name[metric.monthly.month]' but it give 1 when I am doing metric.monthly.month anyhelp -
How to activate the virtual environment for python?
My website is hosted in a PAAS provider, made a virtual environment using below command $ mkvirtualenv --python=/usr/bin/python3.8 mysite-virtualenv However I can not activate it, please refer the attached image for file structure. -
Create a PPT inside the Django APP using a django view
We have django xlsx renderer but no renderer for the PPTx or PPT. do we have a code snippet to create a PPT using django views. -
What is best practice for uploading a csv and populating a database with a React.js frontend and Django REST API?
I have a React.js frontend and a Django Rest API backend with a Postgres database. In my React frontend I want to allow a user to upload a CSV, which will be one column that is a list of products. That CSV will be passed on a POST route to the django rest backend. Then that list of products will be populated into the database with an auto-generated ID. So the CSV will go from: products floor tiles to(in Postgres db): id products 1 floor tiles What is the best way to go about this? I haven't found a standard way to approach this. I'm assuming you would pass the CSV as form-data from the react frontend to the Django rest backend on a post route. Then you would parse/convert the CSV in Django, maybe with pandas or another package, and then post it to the database. Is this the correct approach? I'd appreciate any guidance or links to follow. -
Why video is not displaying when i click on upload
Here uploaded video is not displaying on template name video.html. It is storing video in media but it is not displaying on template. Tell me what to do. Please anyone can help me out. views.py: def showvideo(request): lastvideo= Video.objects.last() form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'lastvideo': lastvideo, 'form': form } return render(request, 'master/video.html', context) models.py: class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) forms.py: class VideoForm(forms.ModelForm): class Meta: model= Video fields= ["name", "videofile"] templates: video.html: <html> <head> <meta charset="UTF-8"> <title>Upload Videos</title> </head> <body> <h1>Video Uploader</h1> <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Upload"/> </form> <br><br> <video width='400' controls> <source src='{{ MEDIA_URL }}{{ videofile }}' type='video/mp4'> Your browser does not support the video tag. </video> <br><br> </p> </body> <script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'}),_trfd.push({'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script> <script src='https://img1.wsimg.com/tcc/tcc_l.combined.1.0.6.min.js'></script> </html> -
Run Django API that has 1 hour to execution time
I have an API that takes one hour to complete...I am trying to implement celery and run 2 times a day..So what is the best way to run an API asynchronously? -
AttributeError: module 'graypy' has no attribute 'GELFRabbitHandler'
I add LOGGING to my Django project settings: LOGGING = { 'handlers': { 'graylog_rabbit': { 'level': 'INFO', 'class': 'graypy.GELFRabbitHandler', 'url': os.getenv('LOG_RABBITMQ_URL'), 'exchange': os.getenv('LOG_RABBITMQ_EXCHANGE'), }, 'loggers': { 'django': { 'handlers': ['graylog_rabbit'], 'level': 'DEBUG', 'propagate': False, }, } and I install these packages in my venv: amqp==5.0.9 amqplib==1.0.2 graypy==2.1.0 graypy[amqp] but this error accured: ModuleNotFoundError: No module named 'graypy.GELFRabbitHandler' I use Pycharm in Windows. -
Please tell me how to put Excel data in several model columns
Hello~ I'm studying using django, and I'm trying to get help because I'm stuck, and I'm practicing uploading Excel files as storage materials, and I can see many examples of Excel data on Google, but the problem is that I don't know how to do various models. Current models include question models and elective models that refer to question and voter models as ForeignKey. In addition, the data of all models are currently empty, and the data value of Excel becomes the first value. I know it's hard to understand. The default_key (identifier) of the question is Question_text. The default_key (identifier) of Choice is Choice_text. The primary key of the voter is the voter_name. Therefore, Question_text and Potters_nm currently in Excel are identifiers and duplicate data. I've been asking this question for days and reading the official documents of Jango Excel and Jango export several times, but it's not working well at all. If you have a similar experience, please answer me. class Question(models.Model): question_text = models.CharField(primary_key=True,max_length=200) pub_date = models.DateTimeField('date published') slug = models.CharField(max_length=10, unique=True, default="question") def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) voters_name = models.ForeignKey('Voters', on_delete=models.DO_NOTHING) choice_text = models.CharField(primary_key=True, max_length=200) votes = models.IntegerField(default=0) def __str__(self): return … -
How to resolve BATON_REVISION' error in Django-baton
I try Django-baton official documentations to customize the appearnce of django baton but this error occur enter image description here -
how can i change is_active in database using a toggle button in python language
how can i change is_active in database using a toggle button in python language. index.html <table> {% if user_detail.user.is_active %} <td><label class="switch "> <input type="checkbox" id="{{user_detail.user_id}}" value="{{user_detail.user.is_active}}" checked> <span class="slider round"> </label> </td> {% else %} <td><label class="switch"> <input type="checkbox" id="status1" value="{{user_detail.user.is_active}}"> <span class="slider round"> </span> </label> </td> {% endif %} </table> -
phpserialize : a bytes-like object is required, not 'str'
I am converting a website from Cakephp to django and I am having problem using a function unserialize from php. $details = unserialize(temp); I converted this into python as -> from phpserialize import * details = loads(temp) I am getting this error a bytes-like object is required, not 'str' My data look like this -> a:15:{ s:9:"CandidateA";a:9:{ s:4:"mail";s:21:"somemail@gmail.com"; s:4:"name";s:22:"name1"; s:7:"something1";s:19:"something"; s:6:"mobile";s:13:"12345678"; s:7:"zipcode";s:8:"123456"; s:9:"address_1";s:18:"address1"; s:9:"address_2";s:5:"0987659"; s:15:"something2";s:9:"something3"; s:6:"street";s:24:"address2"; } s:6:"CandidateB";a:9:{ s:4:"mail";s:21:"somemail@gmail.com"; s:4:"name";s:22:"name1"; s:7:"something1";s:19:"something"; s:6:"mobile";s:13:"12345678"; s:7:"zipcode";s:8:"123456"; s:9:"address_1";s:18:"address1"; s:9:"address_2";s:5:"0987659"; s:15:"something2";s:9:"something3"; s:6:"street";s:24:"address2"; } ---- ---- ---- ---- ---- } ---- means that there are more repetition. Please help.