Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter models related to models in a QuerySet
I have Book and Review models in my app, Review has foreign key field pointing to Book. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from datetime import datetime class Book(models.Model): title = models.CharField(max_length=300, null=False, blank=False) category = models.CharField(max_length=40, blank=True) class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=False) date_last_modified = models.DateTimeField(null=True) is_closed = models.BooleanField(default=False) Now, by applying some filters I have a QuerySet of Books (eg. books from certain category). books_qs = Book.objects.filter(category='World War II') Having this QuerySet I want to find most recent Review with is_closed=True for each Book up to any given date. The simplest solution is of course: desired_date = datetime(2018, 2, 12) reviews = [ book.review_set.filter(date_last_modified__lt=desired_date, is_closed=True) .latest('date_last_modified') for book in books_qs ] Is there a way to improve this to get all Reviews in one query, instead of doing it multiple times in a loop for each Book? -
Python Django: Remove null=true from Model CharField
Unfortunately I have a large model in production (Django 2.0.5) defined with null=True on CharFields: class FooterMenu(models.Model): text_de = models.CharField(verbose_name=u"Menüpunkt (de)", max_length=100, default='', blank=True, null=True) text_en = models.CharField(verbose_name=u"Menüpunkt (en)", max_length=100, default='', blank=True, null=True) text_fr = models.CharField(verbose_name=u"Menüpunkt (fr)", max_length=100, default='', blank=True, null=True) Unfortunately there are plenty of NULL Values in the postgres DB already. If I just remove the null=True and makemigrations the migrate tells me: cannot ALTER TABLE "doctor_footermenu" because it has pending trigger events I understand this happens because of the NULL values in the table. Is there a proven strategy that I can use? -
Django: Trying to make Users migration with a self-referential default value
I'm trying to set a default value on a field I added to my User model, but I'm having to do a lot of acrobativs to make it work. I want to add an 'identifier' SlugField with a default value defined in a function, like so: def create_identifier(): while True: identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15)) if not User.objects.filter(identifier=identifier).exists(): return identifier class User(AbstractUser): identifier = models.SlugField(default=create_identifier, max_length=16) def __str__(self): return self.username This exact scenario works fine on a different (not User) nodel class, but when I try to run migrations with this code for User, I get: Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/base.py", line 469, in __init__ val = field.get_default() File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default return self._get_default() File "/home/myprojectname/myprojectname/myprojectname/users/models.py", line 34, … -
Python Django: Getting None Values from empty modelform field
I have Django 2.0 running and I am getting a None Value from an empty form field. I think this field should deliver an empty string: Model: class FooterMenu(models.Model): ... text_en = models.CharField(verbose_name=u"Menüpunkt (en)", max_length=100, default='', blank=True, null=True) Modelform: class Meta: model = FooterMenu exclude = ('position', 'column') View ... form1 = FooterForm(request.POST, request.FILES, instance=obj) print(form1.cleaned_data['text_en']) Stdout: None Can anybody shed some light why this is happening? Maybe I have set stupid values in the model definition? -
GGPLOT to R - dataframe R
We are trying to convert our application that builds on shiny to Django . We have our custom library for analytics written in R and we have integrated it in our Django using rpy2 library. Now this is the situation, Our library returns ggplot2 instance for plotting graphs. We can't change that library and have to use it for analytics purpose. So what we want is to convert that ggplot2 instance into R - data frame so then we can convert it in Json and sent to our front end to plot graphs. So is there a way to do this . Is it somehow possible to convert gglplopt2 instance to data frame in R ? -
How to create foreign key linked fields in forms just like in Django Admin?
In django admin, you can add, edit, and even delete objects from another table if there is a relationship between the two. For instance, if my code looks like this: class Category(models.Model): ... class Product(models.Model): ... category = models.ForeignKey(Category) When I am editing/adding a product using the django admin site, in the category field, I have 3 buttons to add/edit/delete categories. Adding one takes to a new window, and once I submit the form, the category is added, the window is closed, and I am returned to my product form with the extra category present. How can I do this in my normal application using forms? -
Deploying Channels on Ubuntu 16.04 - websocket error
After a lot of research and trial and error, I am writing here because I have a problem deploying my dango application with Channels to Digital Ocean with Ubuntu 16.04. Sorry if there are errors below, quite a beginner here :D I have everything working well in development, including the websockets with Channel. Before I had the Channels functionality, I used the following guide to set up the server: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 and it all worked well. Now, I am trying to get my new version with Channels to work, but I can't seem to do it! My plan was to create Daphne in a systemctl and have it running in the background (on top of my existing Nginx wsgi configuration as per the Digital Ocean guide). Before doing that, to test Daphne, I tried to simply run it in the shell, through these three commands (tried each one): daphne myproject.asgi:application daphne -p 8001 myproject.asgi:application daphne -b 0.0.0.0 -p 8001 myproject.asgi:application they all run, but when I go to the webpage which connects to the websocket, I get the following error in the javascript console: failed: Error during WebSocket handshake: Unexpected response code: 200 I thought it was a firewall issue so … -
Django REST framework - injecting views
Say I have a simple application with users, groups and users are members of the groups (a M2M relationship). So I create a viewset which shall do the following: GET /group/ lists all groups GET /group/1 gives detail of a group POST /group/1/member adds a member specified in the request to group 1 GET /group/1/member lists all members of group 1 and some other CRUD operations on groups/memberships which are not relevant for my question. To make the code as readable as possible, I came up with this solution: class GroupViewSet(ModelViewSet): ... @action(detail=True, methods=["get", "post"]) def member(self, request, *args, **kwargs): return MembershipView().as_view()(request, *args, **kwargs) class MembershipView(ListCreateAPIView): # handle the membership somehow here However, this approach ends with The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`. Although manually instantiating a view inside another view and passing the request would most probably work in pure Django, the REST framework refuses to do this, as each DRF view expects a pure Django request and cannot just take an existing DRF request as it is. I have two questions: Is my design idea bad? And if yes, how shall I redesign? Do you think it will be worth creating a pull … -
Django QuerySet difference method not working
Im trying to get the difference between two QuerySets and it is important to me that the answer of this difference be a QuerySet. So, the natural solution is to use the difference method of the Django queryset. However, when trying to do that Im getting the following error: NotSupportedError: difference is not supported on this database backend. Here what Im trying to do: In [4]: type(small_qs) Out[4]: django.db.models.query.QuerySet In [5]: type(bigger_qs) Out[5]: django.db.models.query.QuerySet In [6]: bigger_qs.difference(small_qs) Important: Two QuerySets are from the same model. Other information that can be usefull: Using docker (database and django) The database backend is MariaDB (MySQL) Django version is 2.0.6 MariaDB version is 10.3.8 Here the complete output: Out[6]: ---------------------------------------------------------------- NotSupportedError Traceback (most recent call last) /usr/local/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() /usr/local/lib/python3.6/site-packages/IPython/lib/pretty.py in pretty(self, obj) 398 if cls is not object \ 399 and callable(cls.__dict__.get('__repr__')): 400 return _repr_pprint(obj, self, cycle) 401 402 return _default_pprint(obj, self, cycle) /usr/local/lib/python3.6/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle) 693 """A pprint that just redirects to the normal repr function.""" 694 # Find newlines and replace them with p.break_() 695 output = repr(obj) 696 for idx,output_line in enumerate(output.splitlines()): 697 if idx: /usr/local/lib/python3.6/site-packages/django/db/models/query.py … -
Python 3.6 Django 2.1 Creating model in CBV and URL changes
I am running python 3.6.x and django 2.1. I am using the allauth module as well but am not using the social media aspects at this time. I have a url puzzle. I have a CBV for a model. The "create" portion looks like: @method_decorator(verified_email_required, name='dispatch') class Create(CreateView): model = Profile template_name = 'Members/profile.html' form_class = ProfileForm success_url = 'Members/index.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, { 'profileForm': self.form_class(), 'profileState': "create" }) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = self.request.user profile.save() my_render = render(request, self.success_url, { 'profile': profile, 'profileState': "display" }) else: # # form has issues. send it back to the create form to fix. my_render = render(request, self.template_name, { 'profileForm': form, 'profileState': "editForCreate" }) return my_render As far as I can tell this is working as written. I have the basic django User object that is created after email verification. As per the AllAuth module, after a new User is verified a login is required and the new User process redirects to the creation of a new Profile. A Profile form is displayed and after filling it out and submitting the user is redirected to the "index" page. … -
Nginx - Django - Gunicorn: Large file uploads stalled after 30 seconds
I am trying to upload a large file (50mb to multiple GB) to my django website. I use the regular file upload method described in the django docs. It works fine for smaller files. I am serving the website with Nginx -> Gunicorn -> Django. When the filesize is larger and the upload of the file takes longer than 30 seconds, the upload request will get "stalled" as chrome calls it and just freeze. I originally thought this was a limit with nginx because the error.log said: 2018/08/03 01:13:09 [error] 1065#1065: *3 client intended to send too large body: 30681744 bytes,(...) So I tweaked the following settings: nginx.conf: ( in the http block) client_max_body_size 100m; client_body_buffer_size 100m; client_body_timeout 120; sites-available/host: ( in the server block) send_timeout 120; client_max_body_size 100m; client_body_buffer_size 100m; client_body_timeout 120; After tweaking these, the error message has gone away. The gunicorn log gives no further information. However, the documentation told me to start gunicorn with the --timeout 300 flag, so I did. The file however still does not upload and "stalls" after 30 seconds of time. Is this stalling a browser-issue? I remember uploading huge files with apache and PHP with no problems. Am I missing a … -
can I 'chain' annotate - basing one annotation expression on the results of a previous one
I have a code like that: a = EnterEvent.objects.filter(closed=True, participant=player.participant, page_name=page_name).annotate( earliest_exit=Subquery(earliest.values('timestamp')[:1], ), ).annotate(timediff = ExpressionWrapper(F('earliest_exit')-F('timestamp'),output_field=DurationField())) It results in error: Exception Type: TypeError Exception Value: can only concatenate tuple (not "list") to tuple Exception Location: /Users/chapkovski/otree2/lib/python3.6/site-packages/django/db/backends/sqlite3/operations.py in subtract_temporals, line 280 The question is: can I use the name of the field I create in annotate, in the subsequent annotate? -
Using Django User Model
I've seen people using the default django user model as a foreign key in two ways: 1) from django.contrib.auth.models import User user = models.ForeignKey(User) 2) user = models.ForeignKey('auth.User') but when implementing one-to-one relation I've only seen: from django.contrib.auth.models import User user = models.ForeignKey(User) I have two questions regarding this: 1) Are the two ways to define Foreign Keys practically the same? 2) Can you use user = models.OneToOneField('auth.user')? Thanks in Advance! -
Django AttributeError: 'tuple' object has no attribute 'get'
I have trouble getting the correct respond while I following the tutoriala link I can't get into the views whenever I run server. Please help me go through my code. I am not sure is it the problem with the version of django that I'm using and the one the tutorial is using because I notice the one in the tutorial using from django.urls import path but when I start an app it comes with from django.conf.urls. There's the different and I'm confused. Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 1.11.6 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "c:\users\CaddyKKhaw\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "c:\users\Caddy KKhaw\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\deprecation.py" in __call__ 142. response = self.process_response(request, response) File "c:\users\Caddy KKhaw\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\middleware\clickjacking.py" in process_response 32. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /polls/ Exception Value: 'tuple' object has no attribute 'get' Here's my polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("You did it this time!,"), Here's my polls/urls.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.index, name="index") ] here's my mysite/urls.py from django.conf.urls import include, url from django.contrib import admin … -
js-scroll-trigger doesn't work in Django-cms show_menu
I was trying to make a menu in Django-cms that used js-scroll-trigger class so I wrote this code for base.html : {% load cms_tags menu_tags sekizai_tags staticfiles %} <!DOCTYPE html> <html lang="{{LANGUAGE_CODE}}"> <head> <title>{% page_attribute 'page_title' %} - Creative</title> <link href="{% static "vendor/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "css/creative.min.css" %}" rel="stylesheet"> {% render_block "css" %} </head> <body id="page-top"> {% cms_toolbar %} <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">brand</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto "> {% show_menu 0 100 100 100 "menu/menu.html" %} </ul> </div> </div> </nav> {% block content %} {% endblock %} <script src="{% static "vendor/jquery/jquery.min.js" %}"></script> <script src="{% static "vendor/bootstrap/js/bootstrap.bundle.min.js" %}"></script> <!-- Plugin JavaScript --> <script src="{% static "vendor/jquery-easing/jquery.easing.min.js" %}"></script> <script src="{% static "vendor/scrollreveal/scrollreveal.min.js"%}"></script> <script src="{% static "vendor/magnific-popup/jquery.magnific-popup.min.js"%}"></script> <!-- Custom scripts for this template --> <script src="{% static "js/creative.min.js" %}"></script> {% render_block "js" %} </body> </html> and in menu/menu.html I have: {% load cms_tags menu_tags %} <ul class="navbar-nav ml-auto"> {% for child in children %} <!-- no child pages --> {% if child.is_leaf_node %} <li class="nav-item nav-link "><a class="nav-link js-scroll-trigger" href="{{ child.get_absolute_url }}"> {{child.get_menu_title }}</a></li> … -
Using {% url %} reverse with unicode characters in the parameters (Django)
I have a Django site where one can click on the tags (I use tagulous) of a post to view a list of all posts that use that tag. It works fine, except when the string is unicode. Specifically, it's this line of my template that gives me an error: <a href="{% url 'fortykwords:tag' tag.name %}">{{ tag.name }}</a> It gives me the error Reverse for 'tag' with arguments '('你好',)' not found. 1 pattern(s) tried: ['tag\\/(?P<input_tag>[-a-zA-Z0-9_]+)$'] This is the urls.py: path('tag/<slug:input_tag>', views.tag_view, name='tag'), This is the view from views.py: def tag_view(request, input_tag): latest_post_list = Post.objects.filter(tags=input_tag, status__exact="published") context = {'latest_post_list': latest_post_list, 'page_tag': input_tag} return render(request, 'fortykwords/tag.html', context) What should I change so that I can make reverse of links with unicode arguments? -
Using apostrophes in Django settings.py when telling the location of the templates directory
I need to say where the templates file is for my Django app and my user file has an apostrophe in it. Can someone help me out with this one? TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["/Users/Harry's PC/Desktop/django_tutorials/mySite/personal"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then the exception type is: TemplateDoesNotExist when running the server. -
ImportError: Failed to import test module:
im having an issue with a tutorial im following. we have gotten to the point of testing and i continue to get an error when running python manage.py test Here is my error: (restapi) chrismaltez@Chriss-MacBook-Pro:~/Desktop/pycharmprojects/UDEMY/restapi/src$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: src.status.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: src.status.tests Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/restapi/src/status/tests.py", line 6, in <module> from .models import Status File "/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/restapi/src/status/models.py", line 20, in <module> class Status(models.Model): #fb status, instagram post, tween, linkedin post File "/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/restapi/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class src.status.models.Status doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. ---------------------------------------------------------------------- Ran 3 tests in 0.096s I dont understand why i get this error because i have status in the installed apps here: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party 'rest_framework', #local 'accounts', 'status', 'updates', ] and then here is my models that its saying i am having an error with: from django.conf import settings from django.db import models def … -
DRF pass data into RelatedField
I have a serializer and a related field for generic foreign key relationship that should be used to serialize content_object which is a ContentType instance. I need to check the type of the Notification object that I'm serializing inside the related field to properly know which additional fields to serialize into the data parameter in there. What is the best way to achieve this? class NotificationRelatedField(serializers.RelatedField): def to_representation(self, value): data = {} # Need to check notification 'type' here return data class NotificationRetrieveSerializer(serializers.ModelSerializer): content_object = NotificationRelatedField(read_only=True) class Meta: model = Notification fields = [ 'id', 'created_at', 'is_read', 'type', 'content_object', ] -
Pip package a django project
The target is to create a pip package of a Django project. The goal is to make the web application quickly installable anywhere just by doing pip install. The use cases are 2 that I can think of: Manually start the application using a console_scripts like client-web-up that should be the equivalent to type manage.py runserver. This is what I'm focused on right now. create some sort of script to generate configuration files for apache, nginx etc... for later. Steps taken Created a main folder client_web for my pip package. Moved all my project into client_web folder. Created a setup.py as shown below. Edited manage.py file so its content can be executed by an function named entry(). Publish the pip package which downloads and installs correctly. from setuptools import setup setup( name="client-web", ..., version="2018.08.03.3", packages=[ "client_web", "client_web.controller", "client_web.measurement", "client_web.webapp", "client_web.controller.migrations", "client_web.measurement.migrations", ], include_package_data=True, install_requires=[ ... ], entry_points={ "console_scripts": [ "client-web-up=client_web.manage:entry" ] } ) The problem If i type the following in the terminal: $ client-web-up Traceback (most recent call last): File "/usr/local/bin/client-web-up", line 26, in <module> sys.exit(entry()) File "/usr/local/lib/python3.7/site-packages/client_web/manage.py", line 33, in entry main(); File "/usr/local/lib/python3.7/site-packages/client_web/manage.py", line 30, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", … -
Django + React production setup
It looks like a very basic question and I'm confused by the fact that I cannot find any sensible tutorial on that. I'm trying to setup Django + React production build. After running all kinds of transpilation, minification etc. I end up having .js and .css bundles, index.html and several other files like favicon, service-worker.js etc. Now I need to serve this with Django. All of these files are static files and should probably be served as static files by the http server (nginx in my case). The variant I came up with was to modify index.html to make it a valid Django template: {% load static %} in the beginning, replace all hardcoded links with {% static 'filepath' %} and serve it using TemplateView, other files are served by nginx. This works fine, however, modifying build results looks like a bad idea. Generated bundles contain a unique hash for each build and I would need to replace that hash in the template after each build. I obviously can automate it but it looks weird. I would prefer not to touch build results at all, but how should I serve static files then? nginx is configured to serve static files … -
Django "Page not Found" when trying to log into admin & other login screen
I am able to successfully load all pages within my Django application that require a simple HTTP Get request to obtain from my A2Hosting server. However, when I attempt to visit the administration page (mydomain.com/admin) I can view it and enter any credentials to login, yet upon pressing "Login" it tells me that the referenced page does not exist. This also happens when I am visiting the login page I have set up using the view at django.contrib.auth.views.login - I can view the page to enter credentials, however the page returns the same error "Not Found - The requested URL /accounts/login/ was not found on this server." I have successfully tested this on Heroku and on a local server, which is successful on both accounts. It seems like the hosting service is blocking POST requests to the Django application, proving it unable to correctly find the mapping between URL and view. urls.py ... urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] ... settings.py ... LOGIN_URL = '/accounts/login/' ... -
Django Haystack - Searching on Custom Field
I have a Model which contains many CharField with choices options like MULTIPLE_BUSINESS_TYPE_ACTIVE = "MULTIBUS" FACILITY_SUSPENDED_OR_REVOKED_OR_OOB = "LOCKEDFAC" LOCKED_STATUS_CHOICES = ( (MULTIPLE_BUSINESS_TYPE_ACTIVE, "The facility was found to " "be active for multiple business types"), (FACILITY_SUSPENDED_OR_REVOKED_OR_OOB, "The facility was found to be revoked, suspended ") ) So when user type multiple business types I should get all the result with locked status as MULTIBUS Is this possible ? -
Django download Excel File with AJAX
I have a problem that I can't find nowhere a solution that match what I need. I have this AJAX call when I click on a button: $.ajax({ type: 'POST', url: '{% url "tests" %}', traditional: true, data : {'mydata': list,"excel": "" }, success: function (data, textStatus) { //Test }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("some error " + String(errorThrown) + String(textStatus) + String(XMLHttpRequest.responseText)); } }); And in the views.py: if request.method == "POST" and request.is_ajax(): if 'excel' in request.POST: data = request.POST.getlist('mydata') if data: tests = Test.objects.filter(pk__in=data) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Test.xlsx' xlsx_data = WriteToExcelTests(tests) response.write(xlsx_data) return response This works fine if I do not use AJAX (because I have another case when I don't use AJAX) and the file is downloaded in the browser but in this case I can't download the file, it does not give any error but it does not download the file. How can I force this to download the file? -
How to search with spaces in django
I want search with spaces for example solar systems The result is solar%20systems and cero results def search(request, searchtopic): article = infotb.objects.filter(topic__icontains=searchtopic).values('text') return render(request,'search.html') in other case if i search for solar i have results but it is incorrect i read this but i think i need other option, because i dont have 2 fields its only 1 for me, only the content Django search for strings containing spaces