Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WebGL warning: texImage: Alpha-premult and y-flip are deprecated for non-DOM-Element uploads
So I have been trying to use Map-box to plot coordinates in my App, but when I provide the .png file to act as marker, i get this following error: WebGL warning: texImage: Alpha-premult and y-flip are deprecated for non-DOM-Element uploads. Screenshot -
How to get different data in queryset ForeignKey?
This is one of my models: class MyModel(models.Model): field_1 = models.ForeignKey(Table_1, related_name='some_name') field_2 = models.ForeignKey(Table_2, related_name='other_name') # other fields The queryset I get for this model contains id for the Foreign Keys. I want to get unique_id instead. I tried using .values, but it didn't solve the purpose, because it returns dicts, but I require the model objects instead. So what should I do to get unique_id in the queryset object? -
Issue with Django filtering
I have a problem with my code and I don't know how to fix it! I used Django Filters and Django Tables 2 to build a filterable list from a db table. The filter in itself works fine, but I found out that if I leave all filters empty I get the entire table on the web page, while in this case I want zero results. Any suggestion / advice would be greatly welcomed! See code below: tables.py from .models import Casualty import django_tables2 as tables from django_tables2 import TemplateColumn from django_tables2.utils import A class CasualtyTable(tables.Table): edit = TemplateColumn(template_name='casualties_update_column.html', verbose_name='') delete = TemplateColumn(template_name='casualties_delete_column.html', verbose_name='') def before_render(self, request): if request.user.has_perm('casualty.change_bar'): self.columns.show('edit') else: self.columns.hide('edit') if request.user.has_perm('casualty.delete_bar'): self.columns.show('delete') else: self.columns.hide('delete') class Meta: model = Casualty exclude = ('author', 'added_by', 'updated_by', 'date_created', 'date_updated') attrs = {"class": "casualties" , "style": "overflow-x:auto;"} filters.py import django_filters from .models import Casualty class CasualtyFilter(django_filters.FilterSet): first_name = django_filters.CharFilter(label = 'First Name', lookup_expr='contains') last_name = django_filters.CharFilter(label = 'Last Name', lookup_expr='contains') middle_name = django_filters.CharFilter(label = 'Middle Name', lookup_expr='contains') ref_nr = django_filters.CharFilter(label = 'Ref Nr', lookup_expr='contains') service_nr = django_filters.CharFilter(label = 'Service Nr', lookup_expr='contains') rank = django_filters.CharFilter(label = 'Rank', lookup_expr='contains') regiment = django_filters.CharFilter(label = 'Regiment', lookup_expr='contains') how_they_died = django_filters.CharFilter(label = 'How Died', lookup_expr='contains') date_of_death … -
how to optimize the query here with select_related?
i have class A(models.Model): field_a = models.OneToOneField(B, on_delete=models.CASCADE) class B(models.Model): field_b = models.charField() how to write the most optimum query here using select_related or something else? My use case is to get the field_a of model A. queryset_b = B.objects.get(field_b="some name") queryset_a = A.objects.get(b=queryset_b).field_a it hits the db twice. Can i do this thing in one db hit using select_related? -
How Can I Use Django 3 with MongoDB?
Is there a way that I can use Django 3 + MongoDB because djongo (the package which integrates MongoDB and Django) requires Django 2.x. Note that I don't want to move to Django 3 for specific reasons. I just wanna explore it. and I need MongoDB because I am writing a data analysis web app (since NoSQL Databases Perform well when working with large data sets). thanks in advance. -
Unable to add User to new Group in Django unittest
Adding a User to a new Group (in a Django unittest) results in Django.core.exceptions.FieldError This exception has got me stumped. I am merely writing the following unittest as an example to learn the Django unittest system before I use the rest_framework APITestCases. TLDR; I have reset my environment, tested in the Django debug interactive environment with the same code and attempted to add the user multiple ways. The unittest still fails, the debug shell still works... Details I wrote the following test (for conscientiousness I omitted the assert statements...) class modelsTests(TestCase): def testUserModel(self): # we should begin with no users... self.assertEquals( User.objects.count(), 0 ) # create some demo users, 2 exactly... User.objects.create(username="test user", email="test@unittest.com") # add the first user to a group, not the second Group.objects.create(name="Test") user = User.objects.first() user.groups.add(Group.objects.get(name="Test")) # create the second user without any groups User.objects.create(username="another user", email="anothertest@unittest.com") I then run the test (which includes several assert statements after the snippet) with, py manage.py test testdrivendevelopment.tests This returns the following error code and stack trace, Creating test database for alias 'default'... System check identified no issues (0 silenced). F.E ====================================================================== ERROR: testUserModel (testdrivendevelopment.tests.test_models.modelsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\alber\OneDrive - UTS\UTS\ProgSoc\TDD workshop\testdrivendevelopment\tests\test_models.py", line 40, in … -
Сreate a full copy of the object from UpdateView or from ListView in Django
I have Class Based views for my models. I want to create a full copy of the object and go to editing it. I would like to do this from UpdateView with a special button for copying, but it is a good option from the list of objects. How can I do this? Below is the code for one of the models. My ListView: class KeysView( LoginRequiredMixin, CustomPermissionRequired, ListView, ): model = ApiKey context_object_name = 'apikey' paginate_by = 20 template_name = 'db_visual/apiKeys.html' def get_queryset(self): filter_kwargs = {} filter_args = [] search = self.request.GET.get('search', '') if search: filter_args.append( Q(description__icontains=search) | Q(id__icontains=search) ) return ApiKey.objects.filter(*filter_args, **filter_kwargs) \ .order_by('-id') def get_context_data(self, **kwargs): context = super(KeysView, self).get_context_data(**kwargs) context['search'] = self.request.GET.get('search', '') return context My UpdateView: class UpdateKeyView( SuccessMessageMixin, CustomPermissionRequired, UpdateView ): model = ApiKey pk_url_kwarg = 'apikey_id' template_name = 'db_visual/update_key.html' form_class = KeyForm success_url = reverse_lazy('keys') success_message = "Ключ <a href='%(url)s'>%(description)s</a> " \ "успешно изменен!" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, url=reverse_lazy( 'update_key', kwargs={'apikey_id': self.object.id} ), ) -
Django ForeignKey Which field?
I have just started learning Django and one thing in models about ForeignKey was unclear to me. So lets say I have one model like this: class Webpage(models.Model): name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) name2 = models.CharField(max_length=264, unique=True) class Records(models.Model): site = models.ForeignKey(Webpage) So when creating Records entry for testing I see ForeignKey is referenced to Name field of Webpage. My confusion is why exactly name? As I know ForeignKey is referencing to primary key and if you are not giving primary_key attribute to any fields it will create 'id' field and make that as primary_key. So then why not 'id' field but 'name'. Sorry if this is repeat question, I just couldn`t find answer. -
What are efficient ways to return data from an sql database wich is ordered depending on an other service?
I have a database serving a huge and highly normalized resource and an API serving customized recommendation for every items in this database. I want to be able to give a paginated list of items matching search criteria and ordered depending on the recommendation API. For example if a user searched for bands with the Jazz type I would want to return a list of all of the matching band ordered depending on the results of our recommendation API. Our recommendation API gives a list of all bands with a recommendation score which is unique for each users. The best thing i can think of so far is to get a page of recommendation, and do an ORDER BY CASE query with each band ordered depeding on the result of the recommendation: SELECT "band"."id" FROM "band" WHERE "band"."kind_id" = 42 ORDER BY CASE WHEN ("band"."id" = 123) THEN 100 ... WHEN ("band"."id" = 456) THEN 1 ELSE 0 END DESC LIMIT 100 In django this same query looks like this: search = {"kind__name": "Jazz"} recommendations = [ When(id=api_response["id"], then=Value(api_response["score"])) for api_response in api_responses ] queryset = ( Band.objects.annotate( recommendations=Case( *recommendations, default=Value(0), output_field=IntegerField(), ) ) .filter(**search) .order_by("-recommendations")[0:100] ) Then do the … -
Wsgi script and the newest django with Python 3.5
We are trying to deploy one more web-application on our VPS. There is one flask application in production already, which is held by Python 3.5 interpreter. Now we need another one - django app. We have configured our apache2 to host both of then (django is working on subdomain, whereas flask is on the 'root' domain. Everything is okay here. But, since flask application is using global python interpreter (version 3.5) we cannot run django since it requires version 3.6 or newer. Here is django WSGI script: import os import sys print('Python version is ... ') # 3.5 python_home = '/var/www/mysite/venv' activate_this = python_home + '/bin/activate_this.py' exec( open(activate_this).read() ) print(sys.executable) # in case of virtualenv it refers to /usr/bin/python3.5 import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/mysite/mysite") from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() We could have upgraded our interpreter to 3.6, but since established flask app is in production we are not allowed to do so by our managers.. And it is okay probably If we go with virtualenv nevertheless it created virtual environment with existing global interpreter , as is written above version 3.5. And this is where we are stuck now. Apache2 log is constanlty saying to us: [wsgi:error] … -
Django - How can I add formset in the tabular format data?
Here is my following code that can adding new rows when populating data in the input fields. <html> <head> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-theme.min.css"> <script type="text/javascript" src="js/jquery-3.5.0.min.js"></script> </head> <body class="container"> <h1 align="center">Module Testing</h1> <form method="post" class="form-inline"> <div align="center"> <input type="text" id="id" name="id" placeholder="ID" class="form-control"> <input type="text" id ="name" name="test_name" placeholder="Test Name" class="form-control"> <input type="text" id="result" name="result" placeholder="Result" class="form-control"> <input type="text" id="units" name="units" placeholder="UOM" class="form-control"> <button type="button" id="btn-add" class="btn btn-info">Add</button> </div> </form> <hr> <form method="post"> <table class="table"> <thead> <tr> <th> #ID </th> <th> Test Name </th> <th> Result </th> <th> UOM </th> </tr> </thead> <tbody> </tbody> </table> <button type="submit" id="btn-submit" class="btn btn-info">Submit</button> </form> <script> $(function(){ $('#btn-add').click(function(){ var id = $('#id').val(); var name = $('#name').val(); var result = $('#result').val(); var units = $('#units').val(); var tr = '<tr><td>'+id+'</td><td>'+name+'</td><td>'+result+'</td><td>'+units+'</td></tr>'; $('tbody').append(tr); }); }); </script> </body> </html> How can I add formset in the above code in order to save all the data in the database in the single click. I'm new to django. Thanks. -
django: How do I test Update View (And form)?
I'm trying to test and Update View which works perfectly fine when using it via the browser. But I want to add more automated tests. Note: This is my first django app. In my class based test case I have implemented setUpwhich generates the needed objects and user. Then I login with the created user and try to update the object: login = self.client.login(username='testuser', password='123456') response = self.client.post( reverse('edit_batch', kwargs={'pk': self.id}), {'project': self.project.id, 'container': self.container.id, 'comment': 'Updated'}) #fails here status_code = 400 (if not debugged) self.assertEqual(response.status_code, 302) The updated field is comment. When I run this, the test fails because status_code is 400. However when I debug through the views and form, for unknown reason then this part doesn't fail and I do get a 302 response. eg. there seems to be some kind of race condition going on. This is already very weird. What am I doing wrong??? When this assert actual does pass due to debugging, I then fail on the next assert which checks if the updated actually happened: self.batch.refresh_from_db() self.assertEqual(self.batch.comment, 'Updated') self.batch.comment remains unchanged (None) and I can see when debugging and the form gets saved the updated field comment is still set to None. Not … -
Django - Python - URL didn't match any of these
When I write code like this without.html in the end of about/: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), path('categories/', views.categories, name='categories'), path('docAdd/', views.docAdd, name='docAdd') ] I get errors when click on about in the navbar of my webpage, error in that case is : " The current path, about.html, didn't match any of these." But when I change about/ to about.html/ then I can click on about in navbar and page opens, but when I switch from about to contact in navbar I get error like: "The current path, about.html/contact.html, didn't match any of these." I can't seem to solve this, please help. This is the code with about.html/: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about.html/', views.about, name='about'), path('contact.html/', views.contact, name='contact'), path('categories.html/', views.categories, name='categories'), path('docAdd.html/', views.docAdd, name='docAdd') ] views.py code: from django.shortcuts import render from . models import Document # Create your views here. def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def contact(request): return render(request, 'contact.html') def categories(request): return render(request, 'categories.html') def docAdd(request): return render(request, 'docAdd.html') This is the error: Page not found (404) Request … -
How to fetch when One of ManytoMany member is ON
I have model Machine which has a few switches (many to many). I am making filter to fetch when more than one switch is 'On'. queryset.filter(switchs__is_on=True) does not work. how can I solve this?? class Machine switchs = models.ManyToManyField(Station) class Switch(models.Model): is_on = models.BooleanField() class MachineFilter(filters.FilterSet): on_switch = filters.BooleanFilter(method='on_switch_filter') class MachineFilter(filters.FilterSet): def on_switch_filter(self, queryset, name, value): if name == 'on_switch' and value: return queryset.filter(switchs__is_on=True) // it doesn't work -
Django 1.11 - How to send mails using a mail server which supports NTLM authentication only
I'm using Django 1.11 and want to send mails by using an Exchange 2013 server which only supports NTLM for SMTP authentification. I realized that the default email backend django.core.mail.backends.smtp.EmailBackend only supports LOGIN, PLAIN or CRAM-MD5 for authentication. Luckily, I found another promising backend (https://github.com/shadiakiki1986/django-smtp-ntlm-backend) for SMTP with NTLM authentication. Installation of the backend was successful but it does not work. The following happens at the Python console: >>> from django.core.mail import send_mail >>> send_mail('test subject', 'message', 'email@address.com', ['recipient@gmail.com'], fail_silently=False,) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/usr/local/lib/python2.7/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "smtplib.py", line 736, in sendmail self.rset() File "smtplib.py", line 470, in rset return self.docmd("rset") File "smtplib.py", line 395, in docmd return self.getreply() File "smtplib.py", line 369, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed Relevant settings in settings.py: EMAIL_ENABLE=True EMAIL_BACKEND=django_smtp_ntlm_backendNTLMEmail EMAIL_HOST=<mailserver> EMAIL_PORT=25 EMAIL_HOST_USER=<domain>\<user> EMAIL_HOST_PASSWORD=<password> DEFAULT_FROM_EMAIL=<email> EMAIL_USE_SSL=False EMAIL_USE_TLS=False These settings are working fine using a SMTP testing tool called Swaks. Does anybody have experience with using Exchange and NTLM authentication for sending emails … -
Django ForeignKey from external Database
I'm working with 2 Databases, 1 external not managed by Django and the other internal. Thi is the external database now working on models and in Admin site: class Client(models.Model):# IMPORT FROM MYSQL code = models.CharField(max_length=3, primary_key=True) name = models.CharField(max_length=250) region_id = models.IntegerField(db_column="RegionId") class Meta: managed = False db_table = 'client' And this is the one managed by Django on the other DB: class ClientJuno(models.Model): LABORATORIES = (('SCR','SCREENS'), ('DVR','DVMR'),) client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) profiles = models.ManyToManyField(JunoProfile) laboratory = models.CharField(max_length=20, choices=LABORATORIES) See error on opening this last model. Can't find table Client. OperationalError at /admin/settings/clientjules/ no such table: client Request Method: GET Request URL: http://127.0.0.1:8000/admin/settings/clientjules/ Django Version: 2.2.11 Exception Type: OperationalError Exception Value: no such table: client Exception Location: /usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /usr/local/bin/python Python Version: 3.6.10 Python Path: ['/app/mmike', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Mon, 20 Apr 2020 08:11:26 +0000 enter image description here -
passing dictionary value from python to sql stored pocedure
is it possible to pass a dictionary like section value 1 10 2 3 or list section1 [10.2,3,4,5], section2 [1,a,10,"friend"] from python to stored procedure of sql-server. I connected to sql server using pyodbc, from django.db import connection In the stored procedure i need to write xml object based on this parameter. I could have created the table but i dont want to do many operation from python to sql server. How do i do it? -
How to change fields for entire queryset?
I am saving text files with data in the models for moving it from one environment to another. This is one of my models: class MyModel(models.Model): field_1 = models.ForeignKey(Table_1, related_name='some_name') field_2 = models.ForeignKey(Table_2, related_name='other_name') For this model I want to save the data with unique_id instead of id in field_1 and field_2. How can I achieve this for my entire queryset? I tried using .values('field_1__unique_id', 'field_2__unique_id'), but since I am using iterator while saving the data, it threw an error: AttributeError: 'dict' object has no attribute '_meta' in this export function: def export_data(queryset_iterator): first_object = next(queryset_iterator) for field in first_object._meta.get_fields(): # remaining function What am I doing wrong, and what changes should I do on my queryset before giving it to iterator, and without changing export_data function? -
problem facing in connecting Django project with Postgresql
I have tried a lot but couldn't work the error remains the same -
Is there a Python headless browser suitable for Behave without using Selenium or a real browser
I've a history in the PHP/Symfony world, so I am familiar with using Behat (like Behave) without having to use a full Selenium setup. To achieve this they use a GoutteDriver (written in PHP) instead of driving a real web browser like Chrome or Firefox. Is it possible to do something similar in Python (specifically, Django) with Behave? -
How to make javascripts on html work in Django?
I have some scripts written on my html page like: <script> // sidenav const sidenav = document.querySelector('.sidenav'); M.Sidenav.init(sidenav); </script> its not working in my website. Do I need to put {% static '' %} ? If so, where? -
json.decoder.JSONDecodeError in Django view
I am trying to convert a javascript array into a python dictionary using json.loads but I am getting json.decoder.JSONDecodeError: Extra data: line 1 column 3 (char 2). Why is that ? The array looks like like that: sortableArray: 11e,11e,11e,11e,11e,253,11e,245,11e,213,11e,211 and I grab it from the view using : sortableArray = request.POST.get('sortableArray') json_data = json.loads(sortableArray) The full js: var modalForm = document.getElementById("modalForm"); if (modalForm !== null ){ modalForm.addEventListener('submit', function(e) { var formData = new FormData(modalForm); e.preventDefault(); var request = new XMLHttpRequest(); request.open(modalForm.method, modalForm.action, true); var cookies = parse_cookies(); request.setRequestHeader('X-CSRFToken', cookies['csrftoken']); request.onload = function() { var data = JSON.parse(this.response); if (data.addRow) { addRow('habitsTable', data.habit_name, data.habit_id); } }; formData.append('sortableArray', sortable.toArray()); request.send(formData); }); }; and the view: def modal_view(request): data = dict() data.update(update_formset(request)) data.update(new_habit(request)) sortableArray = request.POST.get('sortableArray') json_data = json.loads(sortableArray) return JsonResponse(data) the error message: json_data = json.loads(sortableArray) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 340, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 3 (char 2) -
Merge values to list in django queryset
I have a simple model in django with three fields first_name = models.CharField() last_name = models.CharField() username = models.CharField() What I want is if the first_name and last_name are same for user I will get a list of username in the queryset as <QuerySet [{'first_name': 'foo', 'last_name': 'bar', 'username': ['user1', 'user3']},{'first_name': 'abc', 'last_name': 'xyz', 'username': ['user2']},{'first_name': 'foo', 'last_name': 'bar', 'username': ['user1', 'user3']} -
reverse URL error while using PasswordResetView in django
I am implementing password reset functionality using default PasswordResetView. # account/urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name= 'account' urlpatterns = [ path('', views.dashboard, name='dashboard'), path('signup/', views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='account/login.html'), name='login' ), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('profile/', views.view_profile, name='view_profile'), path('profile/edit/', views.edit_profile, name='edit_profile'), path('profile/password/', views.change_password, name='change_password'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='account/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='account/password_reset_done.html'), name='password_reset_done'), ] Even though I have defined url corresponding to name="password_reset_done", I am still getting the below error when I submit email to the form rendered by accessing password-reset/ url. -
Factory boy set fixed many to many data
I have a userfactory using following pattern class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda n: '0' + str(int('1800000001') + n)) first_name = factory.Faker('first_name') email = factory.LazyAttribute(lambda o: '%s@example.org' % o.username) password = factory.PostGenerationMethodCall('set_password', 'QuickMed') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group) I want to create bulk amount of fake data using UserFactory.create_batch(2) But group 'admin' is not set. How can I set groups value when creating fake data