Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Previous solution for Django-MySQL collation no longer works
Have been using Django 2.x and MySQL 5.7 together for dozen of projects. Long ago had run across the problem of differing charsets/collations between different tables/columns triggering the "1215, 'Cannot add foreign key constraint'" IntegrityError. For at least a year or more, the problem was solved by adding the following to all my database definitions in settings.py: init_command": "SET character_set_connection=utf8mb4, collation_connection=utf8mb4_unicode_ci; All of the tables created and updated by Django through migrations after adding the init command were indeed set to utf8mbf_unicode_ci. (I went back and verified this today.) Now, out of nowhere: spent hours today troubleshooting a problem of failing migrations on an older project. Didn't originally look at the collation issue because nothing had been changed on either the database or in the Django connector. Lo and behold, all new tables are created as utf8mb4_general_ci, thus crashing as foreign keys tried to be written to existing _unicode_ci tables, despite no changes having been made to the init_command. I attempted to convert/rollback all affected tables using ALTER TABLE to convert to my desired collation, but any changes made by a migrations file implicitly converts again to _general_ci. I've looked back at my last few projects, and I see that … -
Extracting min and max value of Django model feature in template
I have a model like this: class Integer(models.Model): integer_value = models.IntegerField(default=0) current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) share = models.IntegerField(default=0) market = models.ForeignKey( IntegerMarket, on_delete=models.CASCADE, related_name='integers', default=None) def __str__(self): return str(self.integer_value) class Meta: ordering = ['integer_value'] In my template, for a given instance of IntegerMarket, I would like to extract the minimum and maximum values of integer_value, in order to then define the min and max value of an axis in JavaScript. For example, I might have an instance of IntegerMarket featuring five integers, with integer_value 1 through 5, respectively. I would then like to extract 1 as min and 5 as max. What's the most straightforward way to do this? -
Does form_valid() in django saves the ModelForm instance by default?
The official documentation says that form_valid() is called when valid form data is POSTed. And doesn't say anything about saving data. But I'm reading a book where it says that the default behavior of this method is saving the instance (for modelforms ) and redirecting user to success_url . So, I'm a bit confused. -
How to add a text delimiter correctly in Python
I want to export some data from DB to CSV file. I need to add a '|' delimiter to specific fields. At the moment when I export file, I use something like that: - To specific fields (at the end and beginning) I add '|': .... if response.value_display.startswith('|'): sheets[response.sheet.session][response.input.id] = response.value_display else: sheets[response.sheet.session][response.input.id] = '|'+response.value_display+'|' .... And I have CSV writer function settings like that: self.writer = csv.writer(self.queue, dialect=dialect, lineterminator='\n', quotechar='', quoting=csv.QUOTE_NONE, escapechar=' ', ** kwargs) Now It works, but when I have DateTime fields(where is space) writer adds some extra space. When I have default settings (sometimes) at the end and beginning CSV writer add double-quotes but I don't know why and what it depends on. -
How to reverse path for custom user when testing Django Rest Framework
I'm building a Django 3 app using a Custom User. I'm trying to test the Custom User, but I can't get the url using reverse. I'm using Django Rest Framework. myapp.api.urls.py: app_name = 'myApp' from django.urls import include, path, re_path urlpatterns = [ ... path('users/', include('users.urls'), name='UsersURLS'), ] myapp.users.urls.py from django.urls import include, path from . import api app_name = 'users' # namespace for reverse urlpatterns = [ path('', api.UserListView.as_view(), name='UsersPath'), ] myapp.users.api.py class UserListView(generics.ListCreateAPIView): queryset = models.CustomUser.objects.all() serializer_class = serializers.UserSerializer authentication_classes = (TokenAuthentication,) And in test_users_api.py: from users.api import UserListView user_detail_url = reverse('myApp:UsersURLS-list') ... def test_user_detail(self): self.client.force_authenticate(user=self.user) response = self.client.post(user_detail_url, {'pk': self.user.id }, format='json') Whatever I try for the reverse, I get an error that is it not a valid view or function name reverse('myApp:UsersURLS-list') reverse('users:UsersPath-list') reverse(UserListView) I'd be grateful for any idea what I'm doing wrong, and how to get the reverse URL. I have it working for the rest of my endpoints which use router, but I can't see what's needed for my Custom User, which I set up following a tutorial and it works fine otherwise. -
Want to fetch data from website and update in my django's sqlite database
I'm trying to fetch json data from a website and update my sqlite database in Django to show on the localhost. I am really stuck here. Please help me and could you please suggest me any website to take help? Thank you -
How to send form information to my personal email?
I built a website in Django, I have a form that stores the information of my clients in my database, but I want that when a person sends their info I receive an email with their information instead of checking my database data. -
Django REST Framework - Assertion Error: Class PropertySerializer missing "Meta.model" attribute
The Serializer class is not finding the model attribute I have defined in the Meta class. I can't seem to figure out what I am doing wrong. I have provided snippets of my code below: # models.py class Property(models.Model): name = models.CharField(max_length=255, blank=False) created_on = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') rent_type = models.CharField(blank=False, verbose_name='Rent Type', max_length=20, choices=RENT_TYPE) location = models.CharField(max_length=60, blank=False) duration_length = models.CharField(blank=False, max_length=20, choices=DURATION, verbose_name='Duration Length') available_from = models.DateField(auto_now=True, verbose_name='Available From') price = models.BigIntegerField() furnishing = models.CharField(verbose_name='Furnishing', max_length=20, choices=FURNISHING) number_of_rooms = models.IntegerField(verbose_name='Number of Rooms', blank=False) number_of_bathrooms = models.IntegerField(verbose_name='Number of Bathrooms', blank=False) class Meta: verbose_name = 'Property' verbose_name_plural = 'Properties' ordering = ['-created_on'] ``` # serializers.py from rest_framework import serializers from .models import Property, Image class PropertySerializer(serializers.HyperlinkedModelSerializer): class Meta: model: Property fields: '__all__' class ImageSerializer(serializers.HyperlinkedModelSerializer): class Meta: model: Image fields: '__all__' # urls.py from django.urls import path, include from .views import PropertyViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'properties', PropertyViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] When I visit the endpoint localhost:8000/properties then I get such error. What am I missing or what am I doing wrong? Below is the Trackback -
unable to make a successful call from android using retrofit with csrf token
I'm new to django and got struck with csrf tokens. I'm making a post request from android using retrofit to my django server which is using csrf protection. I had obtained the csrf token by making a get request first and then I'm passing this csrftoken from the body of POST request. However, my server is showing 'CSRF cookie not set' error. The server is responding well to the calls from POSTMAN but when I make calls from android, I get this error. I think there is some simple thing I'm missing, but I'm not able to figure it out. -
How to do URL masking with Django?
On a Django 1.9 project I need to redirect: https://example.com/app/ to https://examplebucket.s3.amazonaws.com/app/index.html But I need https://examplce.com/app/ to be still visible on the browser address bar... I know this must be possible in theory with Django because the previous team working on this project did a setup to serve the /static/ media files from an S3 bucket. And if I access those static files via https://example.com/static/app/index.html, they are served from the S3 bucket but the browser address bar still shows the original url I input. I'm deploying an Ionic Browser project and I want the files (including the index) to be served from the S3 but the url needs to be user friendly, thats the reason. -
Is I should duplicate fields in two related models
I have two related models. First model Fixture with following fields class Fixture(models.Model): fixture_id = models.IntegerField() team_id = models.ForeignKey("Team") team_logo = models.ForeignKey("Team") and second model Team with following fields class Team(models.Model): team_id = models.IntegerField() team_logo = models.URLField() In above code some fields in fixture model like team_id and team_logo are duplicate team_id and team_logo fields in Team model. If team_id in fixture model need me to establish relation with team model but team_logo is doing nothing only duplicate. Here is my question accordind the first database normalization rule "each record should be unique" is it right way to store in fixture model team_logo? -
Can't update info in Django-forms
So I wanna update a router info in a form, I was able to do the one for adding a router, but now I have to show his info and update it. I am able to make the correct info showing but I'm not able to get the info from the form I checked a lot a lot of way that I found in stack and documentation like ModalForms but I haven't been lucky All the code can be seen here: https://imgur.com/a/uM5NHwT -
How do I make excel spreadsheets downloadable in Django?
I'm writing a web application that generates reports from a local database. I want to generate an excel spreadsheet and immediately cause the user to download it. However, when I try to return the file via HttpResponse, I can not open the file. However, if I try to open the file in storage, the file opens perfectly fine. This is using Django 2.1 (for database reasons, I'm not using 2.2) and I'm generating the file with xlrd. There is another excel spreadsheet that will need to be generated and downloaded that uses the openpyxl library (both libraries serve very distinct purposes IMO). This spreadsheet is not very large (5x6 column s xrows). I've looked at other similar stack overflow questions and followed their instructions. Specifically, I am talking about this answer: https://stackoverflow.com/a/36394206/6411417 As you can see in my code, the logic is nearly the same and yet I can not open the downloaded excel spreadsheets. The only difference is that my file name is generated when the file is generated and returned into the file_name variable. def make_lrm_summary_file(request): file_path = make_lrm_summary() if os.path.exists(file_path): with open(file_path, 'r') as fh: response = HttpResponse(fh.read, content_type="application/vnd.ms-excel") response['Content-Disposition'] = f'inline; filename="{ os.path.basename(file_path) }"' return response … -
Error when deploying django project with apache: "wsgi:error No module named 'django' "
I am building out a webpage on django. I have recently deployed it using linode. Everything worked fine and the site was up and running. I have now made some changes and added features to my django project. I have pulled the newest version onto my linode server and since then the website does not work anymore. I have not changed anything with the WSGI configuration. When looking at the apache2/error.log I get the following error: mod_wsgi (pid=1076): Exception occurred processing WSGI script '/home/.../../Dialogue_Classifier/wsgi.py'. Traceback (most recent call last): File "/home/../../Dialogue_Classifier/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' mod_wsgi (pid=1075): Failed to exec Python script file '/home/../../Dialogue_Classifier/wsgi.py'. mod_wsgi (pid=1075): Exception occurred processing WSGI script '/home/../../Dialogue_Classifier/wsgi.py'. Traceback (most recent call last): File "/home/../../Dialogue_Classifier/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' mod_wsgi (pid=1076): Failed to exec Python script file '/home/../../Dialogue_Classifier/wsgi.py'. mod_wsgi (pid=1076): Exception occurred processing WSGI script '/home/../../Dialogue_Classifier/wsgi.py'. Traceback (most recent call last): File "/home/../../Dialogue_Classifier/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' The module django is definitely installed in my venv - and as I said everything worked fine before I did a git … -
Can someone explain how to upgrade Django to another long-term support (LTS) release?
So Dood has a nice Django update graph... https://arunrocks.com/django-release-schedule-and-python-3/ And I would like to upgrade from Django 1.11.17 to 2.2. I'm seeing recommendations from the Django project to incrementally upgrade. But how is a pip install --upgrade django going to change the current Django project from python 2.7 to python 3.6? Preciate it! -
Django admin import export - 'NoneType' object is not callable
In Django admin page i am trying to import the student table using the import_export library but it gives an TypeError at /admin/catalog/student/import/ 'NoneType' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/admin/catalog/student/import/ Django Version: 2.2.2 Exception Type: TypeError Exception Value: 'NoneType' object is not callable Exception Location: C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\import_export\admin.py in write_to_tmp_storage, line 229 Python Executable: C:\Users\sdixit23.EAD\Envs\my_django_environment\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\sdixit23.EAD\django_projects\django_projects\glacier', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\Scripts\python37.zip', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\DLLs', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\Scripts', 'c:\users\sdixit23.ead\appdata\local\programs\python\python37-32\Lib', 'c:\users\sdixit23.ead\appdata\local\programs\python\python37-32\DLLs', 'C:\Users\sdixit23.EAD\Envs\my_django_environment', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf'] Server time: Wed, 28 Aug 2019 17:31:27 +0100 I have tried checking the models.py and admin.py files. I even tried recreating the site again but i have no clue why its not working. In fact its not working for any of my models. admin.py class StudentAdmin(ImportExportModelAdmin): list_display = ('student_ID', 'student_First_Name', 'student_Last_Name', 'student_DOB', 'gender', 'student_Gmail', 'parent_Name', 'parent_Email', 'contact_Number', 'city', 'country', 'comments', ) # Register the admin class with the associated model admin.site.register(Student, StudentAdmin) models.py class Student(models.Model): """Model representing a Student.""" student_ID = models.CharField(primary_key=True, max_length=10, help_text='Enter Student ID as PYNNN') student_First_Name = models.CharField(max_length=100, help_text='Enter Student First Name') student_Last_Name = models.CharField(max_length=100, help_text='Enter Student First Name') student_DOB = models.DateField(help_text='Enter Date of Birth as YYYY-MM-DD', null=True) gender = models.CharField( max_length=10, choices=STUDENT_GENDER, blank=True, default='', help_text='Enter Student Gender', ) … -
How to use two models from different apps in one template
I want two models from different apps to be rendered in one template. For example in my home page there are list of posts showing post author and post content accordingly. When I will click on author tag I want to show author profile at the top and list of posts by that author bellow. I am using class based view (ListView andd DetailView). In my 'users app' I have Profile model and in 'blog app' I have Post model. blog/models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') phone = models.CharField(max_length=10, blank=True) def __str__(self): return f'{self.user.username} Profile' users/views.py class ProfileDetailView(DetailView): model = Profile # to get two model in one page def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['posts'] = Post.objects.all() return context my template <div class=""> <legend class="border-bottom mb-4">Profile Info</legend> <div class="media"> <img class="rounded-circle account-img" src="{{ object.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{object.user.username}}</h2> <p class="text-secondary">{{object.user.email}}</p> <p class="text-secondary">{{object.user.profile.phone}}</p> </div> </div> </div> <div class=""> <legend class="border-bottom mb-4">User's Posts</legend> <h2 class="account-heading">{{?????}}</h2> <p class="text-secondary">{{??????}}</p> </div> So, my question is how to make queries to get posts … -
qs - Exclude by not in bulk
I have Dog model which has name and color, and i have list of tuples that contains (name, color) of dogs that I want to exclude. How can I achieve a queryset that would be filter dogs that not exist in that list? class Dog(BaseModel): name = models.CharField(max_length=255) color = models.CharField(max_length=255) Dog.objects.all() >> [<Dog: name='Lucky', color='Brown'>, <Dog: name='Lucky', color='White'>, <Dog: name='Maple', color='Brown'> ,<Dog: name='Maple', color='Black'>, <Dog: name='Maple', color='White'>] list = [('Maple', 'White'), ('Lucky', 'Brown')] What im looking for is something like that: Dog.objects.custom_exclude(list) >> [<Dog: name='Lucky', color='White'>, <Dog: name='Maple', color='Brown'> ,<Dog: name='Maple', color='Black'>] -
Is there a way to make django admin actions list always visible?
On my django admin interface, I'm trying to make a command available all the time, my problem is that the actions list is only visible when there is at least one result in the list view. The idea is that, my command will create a bunch of models from an API request, so initially there might not be any. Any ideas on how to override this default behaviour? I've already tried overriding get_actions (but that didn't display the list) and get_queryset (to return a fake queryset so that the change_list thinks there is at least one result) but none of them panned out class myBookAdmin(admin.ModelAdmin): actions = ['pull_book_info'] def pull_book_info(self, request=None, extra_context=None): call_command('pull_book_info') pull_book_info.short_description = 'Pull info from API' So yeah, the idea is that I can select my 'pull_book_info' command even when there are no books in the list. Additionally, it would be ideal if someone could shed some light into how to submit that command without selecting anything from the list below EDIT: python 1.11 and django 2 -
Django Pagination with django-filter not working
I Haved Installed django-filters , i want to paginated the data both search and without search -
Push to heroic fails
I am following this tutorial https://www.codementor.io/jamesezechukwu/how-to-deploy-django-app-on-heroku-dtsee04d4 for deploying my Django app to heroku. This is my first Django app: Push rejected, failed to compile Python app. I'm currently running python 3.7.0. this is set in my runtime.txt file: python-3.7.0 stack trace: Enumerating objects: 11614, done. Counting objects: 100% (11614/11614), done. Delta compression using up to 4 threads Compressing objects: 100% (8294/8294), done. Writing objects: 100% (11614/11614), 42.09 MiB | 3.12 MiB/s, done. Total 11614 (delta 2534), reused 8489 (delta 2166) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.7.0 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Traceback (most recent call last): remote: File "<string>", line 1, in <module> remote: File "/tmp/pip-build-r7xse4_1/django-dbbackup/setup.py", line 59, in <module> remote: install_requires=get_requirements(), remote: File "/tmp/pip-build-r7xse4_1/django-dbbackup/setup.py", line 45, in get_requirements remote: import pysftp # @UnusedImport remote: File "/app/.heroku/python/lib/python3.7/site-packages/pysftp.py", line 10, in <module> remote: import paramiko remote: File "/app/.heroku/python/lib/python3.7/site-packages/paramiko/__init__.py", line 30, in <module> remote: from paramiko.transport import SecurityOptions, Transport remote: File "/app/.heroku/python/lib/python3.7/site-packages/paramiko/transport.py", line 61, in <module> remote: from paramiko.sftp_client import SFTPClient remote: File … -
Is there a way to enforce "one of theses inputs but not all are required" for Django forms?
I'm writing a function that updates one of three possible fields in Django--either a boolean, a string, or an integer. I attempted to to it this way: class AccountsForm(forms.Form): update_key = forms.CharField(required=True) update_value = forms.ComboField(fields=[forms.CharField(), forms.IntegerField(), forms.BooleanField()], required=True) But this is not the functionality I'm looking for, as it expects a combination of a CharField+IntegerField+BooleanField. I need at exactly one of the three fields to be present in the form. Is this possible with django forms? -
django-rest-framework: Adding bulk operation in a ModelViewSet
I have many endpoints which use ModelViewSet to manage CRUD operations for my models. What I am trying to do, is to add bulk create, update, and delete at these same endpoints. In other words, I want to add POST, PUT, PATCH and DELETE to the collection endpoint (e.g.: /api/v1/my-model). There is a django-rest-framework-bulk package available, but it seems to be abandoned (hasn't been updated in 4 years) and I'm not comfortable using a package in production that is no longer active. Additionally, There are several similar questions here that have solutions, as well as blog posts I've found. However, they all seem to use the base ViewSet, or APIView, which would require re-writing all of my existing ModelViewSet code. Finally, there is the option of using the @action decorator, however this would require me to have a separate list endpoint (e.g.- /api/v1/my-model/bulk) which I'd like to avoid. Are there any other ways to accomplish this while keeping my existing ModelViewSet views? I've been looking at GenericViewSet and mixins, and am wondering if creating my own mixin might be the way to go. However, looking at the mixin code, it doesn't appear that you can specify an HTTP Request method … -
DRF: Always apply default permission class
When a permission is defined in a view, I would like to always check if the requesting user has that permission. Let's say I have a basic permission check like this: class HasPermission(permissions.BasePermission): def has_permission(self, request, view, obj=None): if hasattr(view, 'permission_required'): return request.user.has_perm(view.permission_required) return True I have added it as default permission in my settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PERMISSION_CLASSES': [ 'apps.api.permissions.HasPermission' ], } This works, but as soon as I define permission_classes inside a View, the default will be overriden. Is there any clean and proper way to do it? I could probably just write a Mixin and do the same inside dispatch but wanted to use the Permission classes as they were recommended. -
Establishing relationships between two models
I am creating an app of soccer stats and faced some misunderstanding about establishing relationships between models. I created two models. First of them League with the following fields class League(models.Model): league_id = models.IntegerField(primary_key=True) country = models.CharField() country_code = models.CharField() and second Country model with following fields. class Country(models.Midel): country = models.CharField() country_code = models.CharField() I need to establish relationship between both models. Based on logic of my database one league row can contain only one country. Country table in database didnt contain any information about leagues related to it. In league table each row contain information about country to which league is related. I think that i should use one-to-many relationship. Is my thoughts right?