Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I inspect the request Django makes to a database?
I have a management command running on an EC2 instance which fails when trying to execute ORM queries like so: File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 899, in execute_sql raise original_exception OperationalError: SSL connection has been closed unexpectedly I can connect to the same database just fine from a django-admin shell_plus on the same instance. To diagnose this, I'd like to inspect the parameters of the connection request Django is making in each case, to see what's different, but after a bit of poking through the Django source it seemed best to ask how rather than getting lost in the weeds for hours :) alternate strategies for diagnosing this also welcome! -
Django_Tables returning NonType object is not iterable Error
iam stuck in using django_tables2. i intended to display a simple table using a queryset. data in the model is being displayed in the djangoAdmin. I cant where the mistake/ error is coming from, previously the app was working fine. Django tables version: _django-tables2 2.2.1 my model.py class PM03(models.Model): date_done=models.DateField() ticket=models.CharField(unique=True,max_length=100) site_code=models.ForeignKey(Sites,on_delete=models.PROTECT) site_name=models.ForeignKey(Sites,on_delete=models.PROTECT,related_name='pm_site_name',to_field='site_name') spare_replaced_1=models.ForeignKey(Asset,related_name='pm_spare_replaced_1',on_delete=models.CASCADE,blank=True,null=True) spare_replaced_2=models.ForeignKey(Asset,related_name='pm_spare_replaced_2',on_delete=models.CASCADE,blank=True,null=True) spare_replaced_3=models.ForeignKey(Asset,related_name='pm_spare_replaced_3',on_delete=models.CASCADE,blank=True,null=True) rehabilitation=models.TextField(null=True,blank=True,help_text="indicate work done") saved_by=models.ForeignKey(User,on_delete=models.PROTECT) def __str__(self): return self.ticket,self.site_name class Meta: verbose_name='PM03' verbose_name_plural='PM03' my view.py ```class TableView(tables.SingleTableView): table_class = Asset_table queryset = Work_Orders_CR.objects.all() template_name = "test.html" ``` my tables.py ```class Asset_table(tables.Table): class Meta: model=Work_Orders_CR template_name = "django_tables2/bootstrap4.html" ``` -
Using a single ManyToMany relation table instead of ManyToMany & ForeignKey field on multiple models?
I have a Django application that handles data analysis workflows, with database models that look something like this: class Workflow(models.Model): execution_id = models.UUIDField() class WorkflowItem(models.Model): workflow = models.ForeignKey(Workflow) type = models.CharField(choices=["input", "output"]) files = models.ManyToManyField(File) class File(models.Model): path = models.CharField() class FileMetadata(models.Model): metadata = models.JSONField() file = models.ForeignKey(File) version = models.IntegerField() A given Workflow will have many WorkflowItem's, which correspond to File's which can be used by WorkflowItem's across many Workflow's. Each File can have many associated FileMetadata's, of which the entry with the max version value is typically used for a given operation. As the application has been growing, its getting tedious to build out all the different combinations of logic needed to find the entries in one table based on a given entry in another table just by using each tables' Foreign Key interface (Workflow <-> WorkflowItem <-> File <-> FileMetadata). I am considering just building a table that holds all the foreign keys for every relationship in a single place. Something like this: class WorkflowFile(models.Model): workflow = models.ForeignKey(Workflow) workflow_item = models.ForeignKey(WorkflowItem) file = models.ForeignKey(File) file_metadata = models.ForeignKey(FileMetadata) However, I am not sure if this is a good idea or not. Its not clear to me if implementing … -
Google storage backend for Django (django-storages) Bucket agnostic
In my Django models, I have a FileField which uses django-storages backend. However as to have my database pointing to an absolute path, is it possible to use Django-storages with an undefined bucket and define it per FileField. -
How do I import images into Wagtail from a managment command?
I've got a data model similar to this for storing a list of locations and a gallery of photos associated with each location: @register_snippet class Location(modelcluster.models.ClusterableModel): name = models.CharField() class LocationPhoto(Orderable): location = ParentalKey( Location, on_delete=models.CASCADE, related_name='gallery' ) image = models.ForeignKey( 'wagtailImage.Image', on_delete=models.CASCADE, related_name='+', ) alt = models.CharField(verbose_name='Alt text') I would like to create a management command that can load these locations and their associated galleries in bulk from a JSON file and a folder of images. How do I, in Python, import the images so that they end up in the media/ directory as if I had uploaded them through the Wagtail admin UI? -
How can I use Django's test client on multiple databases with ATOMIC_REQUESTS?
I have two databases setup in my settings.py, each with ATOMIC_REQUESTS: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lolomg', 'USER': 'lolomg', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': True, }, 'analytics': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'analytics', 'USER': 'lolomg', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': True, }, } If I then write any tests that use Django's test client, e.g. from django.test import TestCase class TestEndpoints(TestCase): def test_books(self): self.client.get("api/v1/books") I will get a traceback and an exception that look like this: ====================================================================== FAIL: test_books (lolomg.books.tests.test_api.EndpointsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/jordi/vcs/lolomg/lolomg/books/tests/test_api.py", line 6, in test_books resp = self.client.get(self.url) File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/test/client.py", line 535, in get response = super().get(path, data=data, secure=secure, **extra) File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/test/client.py", line 347, in get **extra, File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/test/client.py", line 422, in generic return self.request(**r) File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/test/client.py", line 503, in request raise exc_value File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.7/contextlib.py", line 73, in inner with self._recreate_cm(): File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/db/transaction.py", line 175, in __enter__ if not connection.get_autocommit(): File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/db/backends/base/base.py", line 379, in get_autocommit self.ensure_connection() File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/jordi/vcs/lolomg/lib/python3.7/site-packages/django/test/testcases.py", line … -
Tableau dashboard integration into a Django app
I am relatively new to Data Science and Python. I have built a few dashboards using Tableau (5 different dashboards using different data points) that I would like to transfer to a Python based web application, Django. Would it be possible to create a Tableau extension that integrates into a web application written in Django python web-frameworks? The web application would do certain read/write operations to datasource and send response back to Tableau Dashboard and render Tableau-Viz based on operation status. Please share your thoughts, pointers, resources, and YouTube tutorials. Thanks for any help, Ron -
request.resolver_match.kwargs only works while inside for loop?
I'm using request.resolver_match.kwargs with django to grab the url param for a view I'm trying to link to. When I use it as so <a href="{% url 'ViewPdf' uid=request.resolver_match.kwargs.uid %}">Print this page</a> I get a noreversematch error. however if I put it inside a for loop it works as so {% for uid in request.resolver_match.kwargs.uid %} <a href="{% url 'ViewPdf' uid=request.resolver_match.kwargs.uid %}">Print this page</a> {% endfor %} With the obvious side effect of having as many links as there are characters in the url param. I'm not sure why it works in the for loop but not as a standalone. -
Not receiving IPNs in paypal sandbox
"Instant Payment Notification (IPN) history" in sandbox paypal is empty although the following values are sent with django-paypal: # Paypal initial values paypal_dict = { "business": settings.SANDBOX_PAYPAL_RECEIVER_EMAIL, "amount": "2.5", "currency_code": "GBP", "item_name": "item", "notify_url": "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", "return": request.build_absolute_uri(reverse('blog:article', args=(ar_id, "payment_successful"))), "cancel_return": request.build_absolute_uri(reverse('blog:article', args=(ar_id, "payment_cancelled"))), "custom": "plan", } Paypal listener configuration: Notification URL https://www.<mysite.com>/paypal/ Message delivery Enabled All payments succeed but I don't receive any IPNs in the paypal sandbox account. The IPN simulator works correctly and i receive IPNs in my website listener. I am using django 3.0.2 and django-paypal 1.0 -
how to send selected users data from html table to a python list in django
I just want to send the users email that is define in my html table to be selected from checkbox and then send it to my app view.py to send email to them. -
Get an object in a Many-to-Many Relationship in Django
I have these two models: class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) class Instrumentation(models.Model): instrument = models.ManyToManyField(Instrument, verbose_name=_('instrument'), related_name='instrumentation', blank=True) I want to add a save method to the Instrument model where the method will check if Instrumentation already has an object that has a single relationship with the current instrument. If not, I will create an instrumentation object with one relationship to the current instrument. If so, then nothing happens. If instrumentation has another object that has relationships to violin, violin and cello. It will ignore that. For example. I am trying to save an instrument object called 'violin'. the instrument save method will search instrumentation table to see if there is an instrumentation object that contain a single relationship with violin. If it doesn't exist, then it will create the instrumentation object with a relationship with 'violin'. I have something like but I can't get the filter right: In the instrument model: def save(self, *args, **kwargs): try: exists = Instrumentation.objects.filter(name=self.name) except: new = Instrumentation.objects.create( instrument=self.pk, name=self.name,) new.save() super().save(*args, **kwargs) -
Django keep different database setting in each servers
I am deploying capistrano to Django project. And database settings differs from local to server. So at first I set linked_files in deploy.rb. append :linked_files, "app/settings.py" With this setting, deployment doesn't update the app/settings.py on server. However sometimes, I need to add app setting to this file, so it should be synced to server's. Is there any good practice to deploy django project by tools and keep only database setting in each server?? -
Show alert in template when an object has been created/edited/deleted
Summary: I am trying to create a job board website. I have a dashboard view that displays all of a user's job posts. The user can navigate here just to view their posts and the user is also redirected here after creating a new post, editing a post or deleting a post. I would like to be able to alert the user "Your post was created/edited/deleted successfully" depending on the circumstance of how they got to this page, but am not sure the best way to go about. Below is how I implemented the functionality to alert the user a post has been created, but I don't think it was the best way of doing this. The first view I created was the post_job view where a user can create a new job post. To mark if a job was new I thought to add a boolean field to the Job model: class Job(models.model): #... new = models.BooleanField(default = True) and then do this in the dashboard : @login_required def dashboard(request): jobs = Job.objects.all() new_job = False # set to true if there is a new job (user got directed to this view after posting a job) for job in … -
DJango: how to correctly use Django authentification?
I've use a tutorial to implement authentification (app registration) and it works but I do not understand well I have declare registration url in the django project myproject/urls.py path('registration/', include('django.contrib.auth.urls')), So authentification use default LoginViews, LogoutViews... I have also declare (below) but these urls are not used as even if I suppress these urls autentifications still works... what is the corect way of authentification? registration/views.py from . import views from django.contrib.auth import views as auth_views app_name='registration' urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), ]``` -
Django ListView set default queryset for get_queryset() method
I have a page with a list of posts and a search form to narrow down choices. To use the form input in the ListView I changed the get_queryset() method: from django.views import generic class PostsListView(generic.ListView): model = Posts def get_queryset(self): queryset = Posts.objects.all() # here get URL parameters from form, # filter queryset based on form inputs # then return the filtered queryset return(queryset) The search form is working nicely but the problem is that now when I first open the page with the list of posts my list view lists nothing until I fill out the search form and click submit. I would like to display all posts on the page by default before filling out the search form to search for specific posts. What is the best way to do this? -
Django: how to get size data in a queryset
my room table size data is linked with foreignkey with Master table Size data. i want to get size data query in room table. any help, would be much appreciated. i want to get size data as like my image_set in this "Room" model, i am not getting anything in size data as a result. any help or suggest would be appreciated. models.py class Room(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(blank=True, null=True, max_length=80) description = models.TextField(max_length=1080, blank=True, null=True) instruction = models.CharField(max_length=500, blank=True, null=True) price = models.DecimalField(max_digits=8, decimal_places=2) discount_price = models.DecimalField(max_digits=8, decimal_places=2) size = models.ForeignKey("Size", on_delete=models.CASCADE) capacity = models.ForeignKey("Capacity", on_delete=models.CASCADE) bed = models.ForeignKey("Bed", on_delete=models.CASCADE) services = models.ManyToManyField("Services") category = models.ManyToManyField("Category") created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ["-id"] def __str__(self): return self.title def get_absolute_url(self): return reverse("server_room_detail", kwargs={"slug":self.slug}) def get_size(self, obj): for s in Size.objects.all(): return s def get_image_url(self): img = self.roomimage_set.first() if img: return img.image.url else: return None def get_last_image_url(self): img = self.roomimage_set.last() if img: return img.image.url else: return None def image_upload_to(instance, filename): title = instance.room.title slug = slugify(title) base_name, file_extension = filename.split(".") new_filename = "%s-%s.%s"%(slug, instance.id, filename) return "room/%s/%s"%(slug, new_filename) class RoomImage(models.Model): room = models.ForeignKey("Room", on_delete=models.CASCADE) image = models.ImageField(upload_to=image_upload_to) created_on = models.DateTimeField(default=timezone.now) def __unicode__(self): … -
Submitting multiple forms to Django view with one button using Ajax
I have a basic page where an user can perform an action using a standard form. Since i need my page not to reload when the form is submitted, instead of using Django Forms to handle submitting, i'm using Ajax. When the form is submitting, an Ajax request is fired to my Django view, which at the moment should just print out the content of the request, in order to let me debug it. Everything is working, but now i want to add an option for the user to buy more items at the same time, since it's an ecommerce site. So i need a way to submit the same form multiple times with different data and with a single button. Here is the ajax function i use to send the request: $(document).ready(function () { $("#myform").submit(function (event) { callAJAX( "/myview/", {"X-CSRFToken": getCookie("csrftoken") }, parameters={ 'item': $('#item').val(), 'amount': $('#amount').val()}, 'post', function(data){ console.log('Request fired.') }, null, null ); return false; }); }); This will work:, the following form will send a standard request to my Django view containing the item and the amount chosen by the user. <form method='post' id='myform'> {% csrf_token %} <input type="text" placeholder="Item" id='item'> <input type="text" placeholder="Amount" id='amount'> <button … -
Display a Django dataset in HTML table format on a webpage and also use the same for Input on request.POST
I have the following Django Model for a Employee Leave Application system. The employees provide data for all fields except the last one - leave_decision. The input for leave decision comes in from the employee's manager. Models.py class LeaveTransactionLog(models.Model): empno = models.ForeignKey(Employee,related_name='ltl_empno',on_delete=models.PROTECT) approver_mgrno = models.IntegerField(default=0) applied_year = models.IntegerField(default=2019) applied_date = models.DateTimeField(auto_now_add=True) leave_type = models.CharField(max_length=2,choices=leave_choices,default='PL') leave_start_date = models.DateField() leave_end_date = models.DateField() leave_days = models.IntegerField(default=0) leave_decision = models.CharField(max_length=2,choices=decision_choices,default='ES') I am trying to design a Django form that will display all the leaves waiting for approval on a particular manager. Since I want the manager to see all the rows pending for his approval at the same time, the display is constructed using the HTML table as follows. Template file {% extends 'base.html' %} {% block title %} Approve/Reject/Escalate Employee Leave Applications {% endblock %} {% block body %} <h2 align="center"> Approve/Reject/Escalate Employee Leave Applications </h2> <a href = "{% url 'home' %}" class="home_from_ApproveLeaves"> Back To Homepage </a> {% block content %} <form action="{% url 'ApproveRejectEscalateForm' %}" method="post" novalidate> {% csrf_token %} <table class="LeaveTable" align="center"> <thead class="LeaveTableHead"> <tr> <th> Employee Number </th> <th> Employee Name </th> <th> Deptno </th> <th> Department Name </th> <th> Leave Type </th> <th> Start Date </th> <th> End … -
Know if django-google-analytics-app was installed
I am trying to install the Google Analytics apps in Django and when trying: django-google-analytics-app --version django-google-analytics-app -V which django-google-analytics-app I either get zsh: command not found: django-google-analytics-app or django-google-analytics-app not found How could I check if this app has been installed and how could I check its version? -
Django; Some libraries not building wheel
I'm trying to install my requirements.txt but about half of my packages fail to build. I am running python 3.6, with all packages version specified, and this did not fail 4 months ago. The error (for libsass specifically) is: Building wheel for libsass (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/fabianfossbudal/tp-django/venv/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/l6/x9ss3ln56pddwq8s8s04qml40000gn/T/pip-install-idgzl9if/libsass/setup.py'"'"'; __file__='"'"'/private/var/folders/l6/x9ss3ln56pddwq8s8s04qml40000gn/T/pip-install-idgzl9if/libsass/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/l6/x9ss3ln56pddwq8s8s04qml40000gn/T/pip-wheel-m0e2i6xw cwd: /private/var/folders/l6/x9ss3ln56pddwq8s8s04qml40000gn/T/pip-install-idgzl9if/libsass/ Complete output (21 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.6-intel-3.6 copying sass.py -> build/lib.macosx-10.6-intel-3.6 copying sassc.py -> build/lib.macosx-10.6-intel-3.6 copying sasstests.py -> build/lib.macosx-10.6-intel-3.6 creating build/lib.macosx-10.6-intel-3.6/sassutils copying sassutils/__init__.py -> build/lib.macosx-10.6-intel-3.6/sassutils copying sassutils/builder.py -> build/lib.macosx-10.6-intel-3.6/sassutils copying sassutils/distutils.py -> build/lib.macosx-10.6-intel-3.6/sassutils copying sassutils/wsgi.py -> build/lib.macosx-10.6-intel-3.6/sassutils running build_ext building '_sass' extension creating build/temp.macosx-10.6-intel-3.6 creating build/temp.macosx-10.6-intel-3.6/libsass creating build/temp.macosx-10.6-intel-3.6/libsass/src clang++ -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I./libsass/include -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c pysass.cpp -o build/temp.macosx-10.6-intel-3.6/pysass.o -c -O3 -fPIC -std=c++0x -Wall -Wno-parentheses -stdlib=libc++ -mmacosx-version-min=10.7 -Wno-error=unused-command-line-argument-hard-error-in-future xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: command 'clang++' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for libsass Running setup.py clean for libsass Failed to build libsass I have tried … -
doing too many write operations in django rest framework and postgres
I have this excel sheet where i can have as many as 3000-5000 or may be more data( email ids) and i need to insert each of these into my db one by one .I have been asked not to make these many write operations in one go .How should i go about solving this so that i don't do so many entries to database ?Any hint will be highly appreciated . The solution i could think of is this . https://www.caktusgroup.com/blog/2019/01/09/django-bulk-inserts/ -
Django doesn't render img
everyone. I'm new in Python and Django. There are 2 similar pages, images are rendered for one page, for second aren't. For 1st page I render all rows from db, for 2nd after queryset. Whats wrong? Please, show me. class ShowReviews(ListView): #1st view model = ReviewModel template_name = 'all_reviews.html' def show_review(request): #2nd view if request.method == 'POST': form = ReviewShow(request.POST) if form.is_valid(): s = form.cleaned_data.get('search') s_list = ReviewModel.objects.filter(review__contains=s) return render (request, 'search_reviews.html', {'s_list': s_list}) else: form = ReviewShow() return render (request, 'search_reviews.html', {'form': form}) class ReviewForm(forms.ModelForm): # Forms title = forms.CharField(widget=forms.Textarea) review = forms.CharField(widget=forms.Textarea) file = forms.ImageField(required=False) class Meta: model = ReviewModel fields = ['title', 'review', 'file'] class ReviewShow(forms.Form): search = forms.CharField() class ReviewModel(models.Model): # Model created_by = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) review = models.CharField(max_length=300) pub_date = models.DateTimeField(default=datetime.now()) file = models.FileField(upload_to='uploads', null=True) templates render -
return at previous view with all data in Django
my child template is loaded with an search result .Inside him i've one button to create one pdf file with form data displayed. i would like to, after the pdf is displayed at screen to return at the same page with all previous data without having to repeat the search function. Any idea ? -
Aggregate queryset to calculate percentage is always returning 0
I'm trying to write a Django queryset that aggregates the percentage of verified contracts in our system. I can't seem to get it to work though - I'm always getting '0' for the percentage, even though I know that it should be closer to 25%. My current attempts follows: In[1]: Contract.objects.aggregate( total=Count('pk'), verified=Count('pk', filter=Q(verified_date__isnull=False) ) Out[1]: {'total': 4000, 'verified': 1000} In[2]: Contract.objects.aggregate( percentage=Count('pk', filter=Q(verified_date__isnull=False)) / Count('pk') ) Out[2]: {'percentage': 0} In[3]: Contract.objects.aggregate( percentage=Count('pk', filter=Q(verified_date__isnull=False), output_field=DecimalField()) / Count('pk', output_field=DecimalField()) ) Out[3]: {'percentage': Decimal('0')} -
Django Application not working when moved to a app server
I have a Django app which works fine on my development machine. But when moved to a different location on app server for hosting, it does not work. The error django.core.exceptions.ImproperlyConfigured: 'django-pyodbc-azure' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' When I run the pip freeze command on command prompt, it does not even show the pyodbc and the other libraries installed. All it shows is Django 2.1,Django ms-sql and pytz.I cannot install the libraries on app server using pip install(prod server. No connection). The way I am moving my project from dev to prod machine is by compressing the folder, copying it and then decompressing it. Is copying an issue? Am I missing something here. Any help is appreciated.