Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Why is my form not being saved to my database?
Hi I'm developing a website for an online store using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") … -
Celery task called three times, but the data supplied to the task does not change
I have a Document model with a FileField for uploading images, pdfs, etc., and ImageFields for eight different images sizes created from the single uploaded file. I convert the uploaded image into 8 different sizes using Pillow. I allow multiple file uploads in the DocumentAdmin, and in save_model I create a thumbnail and large image for display in the DocumentAdmin page, and then use a celery task (with redis) to create the other different image sizes in the background and save them to the Document model. My code creates the different images correctly, but I seem to have a strange situation in the celery task. The celery task uses the same code to create the different image sizes as the code used in save_model to create the thumb and large image. The relevant part of the save_model code: def save_model(self, request, obj, form, change): if form.is_valid(): if not change: # Uploading one or more images files = request.FILES.getlist('storage_file_name') if files: for f in files: original_file_name, extension = os.path.splitext(f.name) new_file_name = original_file_name + "." + settings.DEFAULT_IMAGE_EXTENSION obj2 = Document() # save the original file if extension.lower() == ".pdf": obj2.pdf_file = f else: obj2.storage_file_name = f save_document_images(obj2, new_file_name, image_file=f, rot_angle=0, thumbnail=True, xsmall=False, … -
how can be solved AttributeError: 'QuerySet' object has no attribute 'exits'.?
This error occurs while trying to signup I got this error when i tried to login the signup page which I have created. Exception Location: C:\Users\Sunil\PycharmProjects\PyShop\products\views.py in register, line 32 Python Executable: C:\Users\Sunil\PycharmProjects\PyShop\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Sunil\PycharmProjects\PyShop', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32', 'C:\Users\Sunil\PycharmProjects\PyShop\venv', 'C:\Users\Sunil\PycharmProjects\PyShop\venv\lib\site-packages', 'C:\Users\Sunil\PycharmProjects\PyShop\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg'] -
How to get location based Admin views in Django?
I am new to Django and I am working on online food ordering system. I am going to use Django for backend. I am not sure about how to show various admin views based on different restaurants suppose I have restaurants in 3 three cities A,B and C. How to implement different admin views for A,B and C so that each restaurant can view it's order in it's admin views. Also how to make driver view and how to separate delivery boy login and how to assign ordered to him. Also which API to use to detect location and assign order. Anyone know how to complete this project using Django? -
pre_save signal method being called after model's save method
I'm using pre_save signal for performing some functionality, but when I used print statements to print log, I found that my Model's save method is being called before the pre_save bound method, from what I know pre_save method should be called before, I'm posting my Part of my Code for reference: Models.py : class RedeemCode(models.Model): code = models.CharField(max_length=128) reward = models.ForeignKey(Reward, on_delete=models.CASCADE) is_active = models.BooleanField(default = True) class Meta: unique_together = ['code'] def save(self, **kwargs): print("In model save method") super().save(**kwargs) in Views.py my pre_save method: @receiver(pre_save,sender=RedeemCode) def send_noti(sender, instance, **kwargs): print("Pre_save Method called ----->",instance) When I add new values from admin panel , and submit it, The model's save method is called First it prints In model save method and later pre_save bound method is called, so the output is like: In model save method Pre_save Method called From my understanding shouldn't the pre_save bound method be called first and then save method of Model,and output should be like this : Pre_save Method called In model save method I don't understand what is happening , could anyone please explain why this is happening or If I'm doing something wrong , thanks in Advance:) -
Filtering code example optimization issue in Django Rest Framework (DRF) or Not
Recently I came up with the following code in DRF documentation for filtering the queryset in an APIListView, class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Purchase.objects.all() username = self.request.query_params.get('username', None) if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset It seems if the above code snippet is written as follow, it will be more efficient, class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = None username = self.request.query_params.get('username', None) if username is not None: queryset = queryset.filter(purchaser__username=username) else: queryset = Purchase.objects.all() return queryset Am wrong ? or am i miss something about Django ORM ? -
Alternative approach to retrieve the "self" value while using "queryset" instead of using "def get_queryset(self)"
Usual Approach def get_queryset(self): return Test.objects.values( 'test_id', 'test__title').annotate( Count('test_id'), count=Sum(Case(When(~Q(user=self.request.user), then='count'), default=0, output_field=IntegerField())) ).filter(test_id__count__gt=0) While using the above approach, columns sorting functionality is not working. But while using the below approach using queryset, sorting functionality is working but unable to get the self value, so I commented the line containing self. Current Approach queryset = Test.objects.values( 'test_id', 'test__title').annotate( Count('test_id'), #count=Sum(Case(When(~Q(user=self.request.user), then='count'), default=0, output_field=IntegerField())) ).filter(test_id__count__gt=0) As of now, I commented the line containing self ... #count=Sum(.... It would be helpful, if I able to retreive the self value while using queryset. Thanks in advance.