Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Output the Json Response dictionary to the django template
I'm just starting to learn django. Please tell me how I can better implement my idea. JsonResponse sends a response to a separate url (url_to_django/load_table/), how do I output this dictionary to group.html? Html <tbody id="table_person_id"> {% if pers %} {% for pers in persons_list %} <tr> <th scope="row"><div><input class="form-check-input" type="checkbox" id="checkboxNoLabel1" value="" aria-label="..."></div></th> <th scope="row">{{forloop.counter}}</th> <th scope="col">{{persons_list.Id_Group}}</th> <th scope="col">{{persons_list.get_Type_Participation_display}}</th> <th scope="col">{{persons_list.display_id_people}}</th> <th scope="col">{{persons_list.Competencies}}</th> <td> <button value="{{person.Id_Group}}" onclick="delete_person(this.value)">delete</button> </td> </tr> {% endfor %} {% endif %} </tbody> <script> function loadTable() { let xhttpTableGrops = new XMLHttpRequest() xhttpTableGrops.onreadystatechange = function (data) { if (this.readyState === 4 && this.status === 200) { document.getElementById("table_person_id").innerHTML = this.response } } xhttpTableGrops.open("GET", "/main/url_to_django/load_table/", true) xhttpTableGrops.send() } </script> Urls.py urlpatterns = [ path('', views.start, name="start"), path('group', views.Groups.as_view(), name='group'), path( 'url_to_django/load_table/', views.load_table, name='load_table') Views.py def load_table(request): if request.method == "GET": if request.user: try: persons = AkpGroup.objects.filter(Id_Incidents=120) # запрос в базу данных except AkpGroup.objects.DoesNotExist: persons = None pers = persons.all().values() persons_list = list(pers) return JsonResponse(persons_list, safe=False) else: return HttpResponse(status=403) else: return HttpResponse(status=405) -
How avoid duplicate records when use annotate() in queryset
I get this queryset for some method an receive one record candidates_qs = self.filter_job_type_language_zones(job_type_id, filter_languages, filter_zones) Then i need to cast a charfield to integerfield to compare against some value candidates_qs = self.filter_job_type_language_zones(job_type_id, filter_languages, filter_zones) candidates_qs = candidates_qs.annotate( # cast answer_text as integer to compare with question value as_integer=Cast('candidatejobtype__questions_answers__answer_text', IntegerField())) After that my queryset have duplicated records. I try distinct() but didn't work. How avoid duplicate records? -
Korean version of Reddit: Failed to load resource: the server responded with a status of 403
I had so much fun with MSOutlookit (a website basically rekinning Reddit into an Outlook interface). So I’m building a Korean version of it, using their codes (https://github.com/attaxia/MSOutlookit). Im basically scrapping posts from a website called DCInside (a Reddit-like website popular in Korea) Here is the problem. An image scrapped from a post in this website is only shown on my website when Chrome Developer Mode is enabled. When the mode isn’t turned on, I get 403 error. At first, i thought it was a size problem of img on css. But doesnt seem to solve the issue. Here is the code i used <div class="crawl_contents"> {{ data.content|safe }} </div> Please help me guys! -
How to display tableau dashboard in Django?
I want to embedded Tableau dashboard result into one of the html pages in Django. Can it be done? Thank you for any advice! -
Add new value and old value columns in Django simple history
I need to implement a History model and track some events like: New project, Edit project, etc I found this app that does almost exactly what I want. I've been following the documentation but I have a problem. The tables created contain the following columns: history_user, history_date, history_change_reason, history_id, history_type Which is great, but I would also like to have some info about what fields changed in case there is an Update type event. How could I add a New value and Old value columns to the rows generated by the app? I've found this about History Diffing but it's not clear to me how to hook it up. All my models look like this right now: class ModelName(models.Model): #model fields history = HistoricalRecords() -
how to make breakpoint pycharm pyx file?
I have installed cython, whenever tried for a breakpoint using python (.pyx) file PyCharm IDE, I could not create breakpoint (.pyx) file, -
Not able to view static files on template
This project is working but unable to view uploaded files on template name upload.html. This is storing uploaded files in control _ static folder, it works fine but when I click on view file in upload.html template, it is not displaying the uploaded file. Please help me to solve this. Please usermaster app: views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['control_uploadfile']) model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def handle_uploaded_file(f): with open('usermaster/control_static/control_files/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"usermaster/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return HttpResponseRedirect('/usermaster/controlfile/') def upload(request): cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'cmachines':cmachines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machinename', '') operation_no = request.POST.get('operationname','') choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no) cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'cmachines':cmachines,'choiced_cmachine':choiced_cmachine}) models.py: class Controlmachine(models.Model): machine_name = models.CharField(max_length=100) operation_no = models.IntegerField() control_uploadfile = models.FileField(upload_to='control_files/') class Meta: db_table = "controlmachine" forms.py: class ControlForm(forms.ModelForm): class Meta: model = Controlmachine fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/ widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }), 'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }), } Templates/usermaster/: control_show.html: {% extends 'usermaster/home.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> … -
Deploying Django on IIS 10 but I see directory
I try deploying django app to my local server but my web application is not display. But in webbrowser is display directory, Thankenter image description here