Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not loading static CSS file
I have looked around on this site as well as others and still have not found a solution that works for why django is not loading my css file my settings.py file: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] in my html file: {% load static %} <link rel="stylesheet" href="{% static '/css/my_style.css' %}"> My file tree: todo_app static todo_app todo_list db.sqlite3 manage.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo_list', ] Any help would be greatly appreciated. I tried using the STATIC_ROOT as shown on a different thread but there was no change with that. -
django using ModelAdmin.list_editable in view
I have a model: class Question(models.Model): question_text = models.CharField(max_length=200, unique=True) pub_date = jmodels.jDateField(verbose_name='date published') def __str__(self): return self.question_text I want to edit one field of all objects of this model in a view via ModelAdmin.list_editable (from the documentation: Set list_editable to a list of field names on the model which will allow editing on the change list page. That is, fields listed in list_editable will be displayed as form widgets on the change list page, allowing users to edit and save multiple rows at once) (I want to edit this in a view not admin) for better understanding this can be the result: enter image description here Is it possible? -
Download a File through Django
I am making a file serving system that organizes different files based on categories. Once a user finds the file they need, they click a download button and it downloads it. These files are of all different kinds pdf, ai, video, etc. I was using the download attribute on HTML and it was working find locally but then I found that it didn't work when I pushed it to a hosting service. I have read 20 different posts about using Content-Dispostion but I am having trouble even getting to that point. I don't have much to go on at all but below is my attempt to even access the file to be able to push it back to the user. Honestly I am just not sure of where to go from here. I just want the use to be able to click a button and the django-filer file downloads Let me know if I need to inlclude anything else. def asset_detail_view(request, slug, *args, **kwargs): obj = get_object_or_404(Asset.objects.prefetch_related('file_set'), slug=slug) context = { 'object': obj, } return render(request, 'detail_view.html', context) def search(request): queryset = Asset.objects.prefetch_related('file_set').all() filter_set = AssetFilter(request.GET, queryset=queryset) return render(request, 'asset_filter_view.html', {'filter': filter_set}) def download(request, slug): download = File.objects.filter( asset__slug=slug ).first() … -
Django Using reverse() with multiple URLs that include the same app
So I have a django project with a single app, and I have two different url patterns mapped to this one app. I currently have this mostly working, however for a few cases using reverse() results in the wrong namespace. My base urls.py looks like this: from django.conf.urls import url, include from django.views.generic.base import RedirectView urlpatterns = [ url(r'^api/', include('api_project.api_app.urls', namespace='api')), url(r'^beta/api/', include('api_project.api_app.urls', namespace='beta')), url(r'^$', RedirectView.as_view(url='api', permanent=False), name='index') ] In most cases reverse works as expected, e.g. using /beta/endpoint has links on the page that look like: /beta/endpoint/example However, in a few cases using /beta/endpoint has links like: /api/endpoint/different-example My question is less about how reverse determines which namespace to use, but instead is this the appropriate way to use two namespaces for the same app? Is this something I should approach completely differently? Most of my research so far has not resulted in much success, so I'm thinking this might be fundamentally the wrong approach. If this approach is okay, then I'm curious why reverse is inconsistent in which namespace it returns. -
Error when creating admin in django tutorial
I am following the Django tutorial and am stuck on the second part, where I have to create an admin account. I followed everything described in the tutorial up to that point and get the following error: Traceback (most recent call last): File "e:\venvs\django_tutorial_venv\lib\site-packages\django\utils\module_loading.py", line 20, in import_string return getattr(module, class_name) AttributeError: module 'django.contrib.auth.password_validation' has no attribute ' UserAttributeSimilarityValidator' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 26, in get_password_validators klass = import_string(validator['NAME']) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\utils\module_loading.py", line 24, in import_string ) from err ImportError: Module "django.contrib.auth.password_validation" does not define a " UserAttributeSimilarityValidator" attribute/class During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 163, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 29, in get_password_validators raise ImproperlyConfigured(msg % validator['NAME']) … -
Fill model field with default value instead of null
I have my model defined like this: class Activity(models.Model): country = models.CharField(max_length=100, default="Unknown") country field is filled from JSON response, but sometimes is not available. I am currently getting django.db.utils.IntegrityError: NOT NULL constraint failed: explorer_api_activity.country I have tried different combinations of null=True, blank=True and getting rid of the default, and also deleting migrations and the database, but to no avail. I want to fill the field with "Unknown" whenever null is encountered. How do I do this? -
Auto create related model
I am wondering if it's possible to auto create a related model upon creation of the first model. This is the models class Team(models.Model): name = models.CharField(max_length=55) class TeamMember(models.Model): team = models.ForeignKey('Team', on_delete=models.CASCADE, null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) So what I want to do is something like this on the 'Team' model class Team(models.Model): name = models.CharField(max_length=55) @on_new.do_this TeamMember.team = self TeamMember.user = request.user TeamMember.save() I have tried to find any documentation about this. But only found some example about onetoonefields. But nothing about this. Appreciate any help. Cheers! -
Why does img.thumbnail adjustment raises FileNotFoundError [Errno2] No such file directory?
I have a django blog application that is deployed on Heroku and has images being served from AWS S3 Bucket. When a user attempts to upload an image, we use PIL to thumbnail resize the dimensions based on an if condition (as shown in models.py below). When I attempt to update profile image, it throws the dreaded: FileNotFoundError at /profile/ [Errno 2] No such file or directory: 'profile_pics/0umkn7tybif11.jpg' The traceback of the error also shows what appear to be these key lines: /app/users/signals.py in save_profile instance.profile.save() ... ▶ Local vars /app/users/models.py in save img.save(self.image.name) ... ▶ Local vars /app/.heroku/python/lib/python3.6/site-packages/PIL/Image.py in save fp = builtins.open(filename, "w+b") ... ▶ Local vars My models.py file seems to contain the code being addressed in this error: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.core.files.storage import default_storage as storage class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open(storage.open(self.image.name)) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.name) Lastly, if I remove the following code from the models.py file, the app functions properly: if img.height > 300 or img.width > 300: output_size … -
Send data, query a table based on that data and render
I'm developing a spatial data infrastructure. It's based on a webapp created with Django. The webapp has a map, you can draw polygons on it. Based on the polygon you drew, specific data should be returned to the client. So the flow looks like this: you put points on the map, it becomes a polygon after the third point. You press a button which triggers a putData js function and sends data to the appropiate view with a GET request & the view puts the data in a postgres datatable. All fine until this point. In the putData function's success callback I specify another get request, without data. The view which handles this request gets the last row from the above specified postgres table, make queries to another datatable with the values from the last row and renders the result of the query with a html page. The problem is that the render never happens. The page where I pressed the button just stays like it is, and no redirect happens. TL;DR: I want to put data in a postgres table with a get request, get values from that table with, query a second table and render a second html … -
Django filter query and or and
I'd like to use AND OR AND in one filter method, is it possible to do without custom query? Something like that: .filter((Q(condtion) & Q(condition)) | (Q(condition) & Q(condition))) -
Wordpress as a blog with already existing django app
I have an existing django app, and I want to add a blog to it, and we decided to use WordPress for the blog as a subdomain "www.example.com/blog" for the sake of seo. so Django is served by Nginx and uses Postgress database, I assume that WP will use MySQL and will still be served by Nginx, So how can I tweak the Nginx config to make this happen, because I tried old solutions and none of them worked. and if you have another suggestion please advice, FYI, the server is Ubuntu 18.04 and php7.2 is installed. -
Which programming languages are the best way to develope mail marketing automation like Mailchimp, Sendgrid etc?
Do you think which programming languages combination (backend and frontend) for the best choice to develop apps like Mailchimp, Sendgrid, Campaign Monitor etc email marketing automations? Because as you know these apps needs ingenious SQL queries. Also, these apps have real time email design editor, advanced contact list management, comprehensive reports, unsubscriber handling, triggering campaigns and marketing automation campaigns, storing sample newsletter templates, API integrations. Surely I know, mail hosting, IP blocks and some reliable certificates are play key role in email marketing. What are your thoughts of this subject? I look forward to your precious and informative replies! Thanks in advance. -
Django 2.1 on Heroku "relation "auth_user" does not exist" with postgres
I'm trying to create a django app on heroku, i was trying to log in into the admin interface but every time it was giving this error : relation "auth_user" does not exist and i can't understand why, i'm using postgresql with the heroku-postgress ad-don. I've run all the migrations and tried dropping the database and recreating it. I'm using the django-heroku module to configure the database. I don't really know what information might be useful so if you need something i'll edit the question. Thanks in advance to everyone. -
Remote username Django
I need to get remote username in django. I mean the username logged into windows. Like getting logged in username in views.py user=request.user. Is there any command to get remote username? -
django filters objects from different model
this is my django models: class Videos(models.Model): Title = models.CharField(max_length=100, unique=False, help_text='video title') Description = models.TextField(null=True, unique=False, blank=True) Tags = models.CharField(max_length=250, unique=False, blank=True) Category = models.CharField("Category", max_length=32, default='28', choices=CATEGORIES, null=False, blank=False) Language = models.CharField("Language", max_length=32, default='EN', choices=LANGUAGES, null=False, blank=False) file = models.FileField(upload_to='videos/', null=True, blank=False, validators=[FileExtensionValidator(allowed_extensions=['mp4'])] ) Playlist = models.CharField(max_length=100, unique=False) title_gen = models.BooleanField(default=False) class TitleVideo(models.Model): video = models.ForeignKey(Videos, related_name='video_id', null=False, blank=False, on_delete=models.CASCADE) converted = models.BooleanField( default=False, help_text='video has ben converted (True | False)') publicato = models.BooleanField( default=False, help_text='video has ben published (True | False)') i need to get all Videos who have TitleVideo.converted = false and Videos.title_gen =True, how i can do this ? -
django.db.utils.OperationalError: no such column: <app>_connections_friends.connections_id
I have an User object class User(AbstractBaseUser, PermissionsMixin, Base): username = models.CharField(db_index=True, null=False, unique=True, max_length=255) mobile = PhoneNumberField(db_index=True, null=False, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And I have the following Connections object class Connections(Base): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True) friends = models.ManyToManyField(User, related_name='friend_set', symmetrical=True) followers = models.ManyToManyField(User, related_name="follower_set", symmetrical=False) followings = models.ManyToManyField(User, related_name="following_set", symmetrical=False) When I run the following line, sender = User.objects.get(id=kwargs.get('sender_id')) receiver = User.objects.get(id=kwargs.get('receiver_id')) sender_connections, created = Connections.objects.get_or_create(owner=sender) sender_connections.friends.add(receiver) I get the following error, django.db.utils.OperationalError: no such column: <appname>_connections_friends.connections_id I'm not sure what am I doing wrong here? -
Prevent users from creating Django account with username on list
In Django Rest Framework, I've got a post model that can be filtered by both usernames from my user object, and country names from a country objects. It just adds a ?search= to the end of the API. From the frontend, it uses the same form to add this query onto the end of the url. I'd like to avoid confusion of returning both country names and user names that are the same. For example, if someone searched for Ireland, by preventing users from making an account with the username Ireland, it would only return Posts with country Ireland associated with the post (ManyToMany relationship to posts). Is anything like this possible outside of creating a user for every country? -
AttributeError django
I've just create django project and added app. Runserer was fine first time, but I added some code and get huge amount of errors. This is the view in the new app named HotelAuth. from django.http import JsonResponse def test(request): context = { 'tittle': 'some tittle', 'description': 'descr' } return JsonResponse(context) Installed Apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.HotelAuth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'HotelAuth', ] urls of project from django.contrib import admin from django.urls import path from django.contrib.HotelAuth.views import test urlpatterns = [ path('admin/', admin.site.urls), path('', test) ] That is all i modified, and get errors in pictire -
Page not found media docfiles
hi i'm try open docx file with the path absolute, someone files open ok but others files dont open and get the error: Page not found (404) the path is this: media/gestionDocumental/Operativos/Produccion/PR/01 Planificacion y prod de balanceado/ANEXO 4._Encendido y apagado de la mezcladora #2.docx this path is correct and the files get this name, but i dont understan why dont open this file, this i my code: function openFile(path){ console.log(path); var hostName=window.location.host+"/" var linkDoc="http://"+hostName+path; window.open(linkDoc, '_blank', 'location=yes,height=600,width=900,scrollbars=yes,status=yes'); }//end function openFile this code use in javascript to open and force donwload this file but get the error.. please any suggest.. or idea thanks..!! -
Django Rest Framework url_pattern of @action
I need to pass instance id after last / of my @action name method, and I seriously have no idea how... I have a UserViewSet, which url to access list is : /users/, then i have action called favorite_posts, which is detail=False because I'm filtering by current logged user, and the action refer to user posts, I wanna be able to pass the post_id like /users/favorite_posts/1/, because in this case it's more friendly to me than /users/1/favorite_posts/ which I could obtain setting detail=True. Is there any way to do that? -
Django: Display different data from a view based on URL using if elif
I have about 1000 records worth of data and I would like to display the subsets of that data in the same template file based on category. I am having trouble finding a solution that really works. Below is what I have so for but I am pretty sure there is a much more efficient way to do this. View def man_org_list(request): manufacturers = Organization.objects.filter(member__member_flag=1, member__member_type='Manufacturer').order_by('id') suppliers = Organization.objects.filter(member__member_flag=1, member__member_type='Supplier').order_by('id') distributor = Organization.objects.filter(member__member_flag=1, member__member_type='distributor').order_by('id') return render(request, 'profiles/man_dash.html', {'man': manufacturers, 'sup': suppliers, 'dist': distributor}) urls.py urlpatterns = [ url(r'^$', views.org_list, name='org_list'), url(r'^(?P<id>\d+)/$', views.org_details, name='org_details'), url(r'^man_dash/', views.man_org_list, name='man_org_list') ] Part of the code I am trying to change base on category: {% if request.get_full_path == '/profiles/man_dash/manufacturers/' %} {% for org in man %} <tr> <th scope="row">{{ org.id }}</th> <td>{{ org.org_name }}</td> <td>{{ org.org_type }}</td> {% for member in org.member.all %} <td>{{ member.member_flag }}</td> {% endfor %} {% for c_score in org.c_score.all %} <td>{{ c_score.completeness_score }}%</td> {% endfor %} <td><a href="{% url 'org_details' org.id %}" target="_blank">View</a></td> </tr> {% endfor %} {% endif %} As you can see in the snippet I am using request.get_full_path to match the url path to display the data. However, using this approach I would have to copy over … -
PosGis and Django-Tenants
(Using the library django-tenants for tenant separated multi-tenancy) For PostGis support the docs say to add ORIGINAL_BACKEND = "django.contrib.gis.db.backends.postgis". I have this, however, when I go to create a new tenant I get the following error: Traceback (most recent call last): File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\celery\app\trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\celery\app\trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) File "C:\Users\Cole\Documents\GitHub\Elevate-RA-Django-App\returns_app\apps\tenant_stores\tasks.py", line 28, in create_tenant_task tenant.save() File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\models.py", line 93, in save self.create_schema(check_if_exists=True, verbosity=verbosity) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\models.py", line 143, in create_schema verbosity=verbosity) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 141, in call_command return command.execute(*args, **defaults) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\management\commands\migrate_schemas.py", line 63, in handle executor.run_migrations(tenants=tenants) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\migration_executors\standard.py", line 15, in run_migrations run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants)) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django_tenants\migration_executors\base.py", line 34, in run_migrations MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 77, in handle connection.prepare_database() File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 26, in prepare_database cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "c:\users\cole\appdata\local\programs\python\python36-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) … -
Django restpagination
I'm trying to paginate using django rest framework. Here is my code. my views.py: class SmallPagesPagination(PageNumberPagination): page_size = 6 class ExceptionModelView(generics.ListAPIView): queryset = ExceptionModel.objects.all() pagination_class = SmallPagesPagination def get(self, request, *args, **kwargs): serializer = ExceptionModelSerializer(queryset, many=True) page = self.paginate_queryset(serializer.data) return self.get_paginated_response(page) in settings.py: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', } my error: Internal Server Error: /app/exceptions/ Traceback (most recent call last): File "/home/danee/enviroments/edu/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/danee/enviroments/edu/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/danee/enviroments/edu/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [29/Nov/2018 16:39:49] "GET /app/exceptions/ HTTP/1.1" 500 16023 -
How to import Django model in Beautiful Soup
I have problem to import django model to script in python (Beautiful Soup). The script name scrapy_link.py and try this from app.appmod.models import Article. And I have error: from app.appmod.models import Article ModuleNotFoundError: No module named 'app.appmod' My folder structure look this: project myvenv app app settings.py, urls,py, init.py, etc. appmod models.py, views.py, admin.py, etc. scrapy_link.py -
Django order of message tags
I wonder if it is possible to change the order of the message tags of a django message with extra tags. from django.contrib import messages messages.success(request, 'success message', extra_tags='safe') And in my template i use {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {% if 'safe' in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %} </div> {% endfor %} {% endif %} With this i the class of the div will be: <div class="alert alert-safe success"> but i want to have the two tags switched, so that i can use the bootstrap class. Is this possible?