Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
count i+1 or i-1 at Django view
i want to create a up-vote and a down-vote view from my category_request page, but how do i count the initger field i+1 or i-1? def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) try: if request.method == 'POST': category_request.up_vote() << here i guess messages.success(request, 'You have successfully Provided an Up-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.success(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) except Exception as e: messages.warning(request, 'Uuups, something went wrong, please try again. Error {}'.format(e)) models.py ... up_vote = models.IntegerField(default=0) down_vote = models.IntegerField(default=0) ... i guess that i dont have to mention that im new to Python/Django ^^ Thanks in advance -
Django template FOO_set.all returns blank
I'm trying to display the value of the model Enigme related by a ForeignKey on the model Salle. These are the classes : class Escape(models.Model): name = models.CharField(max_length=100, unique=False) def __str__(self): return self.name class Salle(models.Model): salle = models.CharField(max_length=100, unique=False) escape = models.ForeignKey(Escape, on_delete=models.CASCADE) def __str__(self): return self.salle class Enigme(models.Model): enigme_name = models.CharField(max_length=100, unique=False) salle = models.ForeignKey(Salle, on_delete=models.CASCADE) def __str__(self): return self.enigme_name My view file : def salle_escape(request): escape_named = 'Test' list_salle = Salle.objects.filter(escape__name=escape_named) context = { 'escape' : Escape.objects.get(name=escape_named), 'salle' : list_salle, } return render(request, 'chat/salle_escape.html', context) This is my template file : <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <h1>Test</h1> <h2>Liste des salles</h2> <ul> {% for s in salle %} <li>{{ s.salle }} </li> <ul> {% for enigme in s.enigme_set.all %} <li>{{ engime.enigme_name }}</li> {% endfor %} </ul> {% endfor %} </ul> </body> </html> What I'm getting, it is empty bullets : Would you have an idea about my issue ? -
Django: one of the hex, bytes, bytes_le, fields, or int arguments must be given
I am trying to filter data on based of UUIDAutoField in an API using Django. I am using PostgreSQL but while sending data from mobile app I have a string and that string UUID is on API level is not matching up with the same UUID it is giving me this error: TypeError at /api/updatestate/ one of the hex, bytes, bytes_le, fields, or int arguments must be given and I am doing this to string type uuid when I get it from API request empId = uuid.UUID(request.POST.get('employee_id')) Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 483. response = self.handle_exception(exc) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception 443. self.raise_uncaught_exception(exc) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 480. response = handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/decorators.py" in handler 53. return func(*args, **kwargs) File "/app/cfkcapi/views.py" in checkstate 78. empId = uuid.UUID(request.POST.get('employee_id')) File "/app/.heroku/python/lib/python3.6/uuid.py" in init 134. raise TypeError('one of the hex, bytes, bytes_le, fields, ' Exception Type: TypeError at /api/updatestate/ Exception Value: one of the hex, bytes, bytes_le, fields, … -
What if I delete rows from Django queryset and then filter again?
Consider the following code: questions = Question.objects.only('id', 'pqa_id', 'retain') del_questions = questions.filter(retain=False) # Some computations on del_questions del_questions.delete() add_questions = questions.filter(pqa_id=None) Will add_questions not contain questions with retain=False? I.e. is questions object re-evaluated when we run delete() on its subset del_questions? -
How to upload multiple files (images) with only one <input type="file" multiple> in Django?
I have created a photography website using Django 2.1.2. I have a model to store the pictures. Since I can only upload pictures one by one on the admin site, I started to build my own view to upload multiple pictures at once. The html-form looks like this: <form action="{% url 'pictures:uploader' %}" method="post"> {% csrf_token %} <select id="project_field" name="project"> {% for project in projects %} <option value="{{ project.id }}">{{ project.name }}</option> {% endfor %} <label for="project_field">Project</label> </select> <input id="pictures_field" type="file" name="pictures" multiple> <input class="btn" type="submit" value="Submit"> </form> projects is a list of projects, each picture should be related to a project using django.db.models.ForeignKey. The Picture model has some additional fields that should be filled on default, e.g. using the file name. When testing, I am able to select multiple files in my Browser (Firefox). But I don't know how to process the images in my view. Here is what I tried so far: from .models import Project @login_required def uploader(request): if request.method == 'GET': projects = Project.objects.order_by('-created') context = { 'projects': projects, } return render(request, 'pictures/uploader.html', context) elif request.method == 'POST': f_number = len(request.FILES) f_names = request.FILES.keys() f_string = 'Thank you for posting {} files. File names: '.format(f_number) + … -
Django Not Reflecting Changes in MySQL DB
I am running a django website using nginx + gunicorn and am running into some issues that I have not before. The website used to be hosted on a different VM, using apache, and I did not see these problems. I migrated the MySQL DB I was using to a different VM, and update settings.py to point to this new DB host. Seems like during the DB migration, some duplicate entries were created somehow, so I deleted them, but on the webpage these changes were not reflected. Making sure it was not browser cache, I could not figure out the problem. On the Django admin page, I still saw the duplicate keys, although they do not exist in the MySQL table itself. How is this possible? I understand there is some caching with querysets etc, but how is the DB on the webpage different than the actual MySQL DB? -
Django model field validation with related object and ajax changing <option>
I have two <select> chained. I initialize the form in such a way as to show in the first <select> the first element of Contients and in the second <select> the Nations belonging to the first Continent. Then i call a ajax every time the Continent change and i replace the <option> in the Nation <select> However, the form must validate only the nations belonging to the selected continent. Instead I always get the following error: ERROR <li>nation<ul class="errorlist"><li> Select a valid choice. That choice is not one of the available choices </li></ul> form.py MyForm(forms.Form): def __init__(self, *args, **kwargs): super(self).__init__(*args, **kwargs) self.fields['nations'].queryset = Nation.objects.filter(continent=Continent.object.all().first()) continents = forms.ModelChoiceField(queryset=Continent.objects.all(), empty_label=None) nations = forms.ModelChoiceField(queryset=Nation.objects.all(), empty_label=None) def clean(self): cleaned_data = super().clean() nation = cleaned_data.get("nation") continent = cleaned_data.get("continent") if nation not in Nation.object.filter(continent=continent): msg = "This nation is not on this continent." self.add_error('nation', msg) -
Is there a way to set a primary key in the URL but then continue with that pk for other paths in Django? Any documentation online?
I am creating an application which links to different sports club pages all within one site. I currently have the profile page which renders when a club is selected using the pk of that club. But once I get to the selected club page, I have no idea how use that same pk to access the other pages such as player registration based on what club the user selected in the beginning. In turn it is similar to a social media if I click on a person, it goes to that persons home page, if i select photos it will show photos of that person etc. Is there any documentation that can help me accomplish this? Any snippets of code you wish to see just let me know. Thanks -
Decoding and encoding JSON in Django
I was following some django rest framework tutorials and found some obscure codes. This snippet is from the customised user model, the project from which uses jwt for authentication. As I commented in the snippet, I can't notice the reason Why they first encodes data and decode it again. I thought this kind of pattern is not only specific to this tutorial, but quite a general pattern. Could anyone explain me please? def _generate_jwt_token(self): """ Generates a JSON Web Token that stores this user's ID and has an expiry date set to 60 days into the future. """ dt = datetime.now() + timedelta(days=60) token = jwt.encode({ #first encode here 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') #returns decoded object -
how to create a relation model with forms?
Hey i need to create a model from form. It's different way if i need to create a some another model, that have a relations with created object model from form. its must work like that -> i come on site, get form for create a model object and save new object. an then -> i have another model with relations with model from form. and i need, to create relation model object automaticly - when django taked new object from forms. tried any can help me. i make it this way, but this time i have problem. -> i have manytomany field in my relation model, and i have manytomany field ->users from form. and i cant create a relation model with this instance :( Traceback: TypeError at /ru/center/add/ Direct assignment to the forward side of a many-to-many set is prohibited. Use users_center.set() instead. but i tired to try it(( help please, how i may do it? views.py pastebin - https://pastebin.com/NmwspcpB models.py pastebin - https://pastebin.com/XJQh4Ayg -
Django Default Auth Views Url No Reverse Match
In my Django Project, I have the following in my urls.py: urlpatterns = [ path('register/', views.register, name='register'), # Registration path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), # Login Page path('logout/', auth_views.LogoutView.as_view(next_page='misc:index'), name='logout'), # Logout Page path('change_password/', auth_views.PasswordChangeView.as_view(template_name='users/change_password.html', success_url='/'), name='change_password'), # Password Change Page # Password reset pages; They take a lot of parameters path('reset_password/', auth_views.PasswordResetView.as_view( template_name='users/password_reset/password_reset_request.html', email_template_name='users/password_reset/email_password_reset.html', subject_template_name='users/password_reset/email_password_reset_subject.txt', success_url='/reset_password/check_your_email/', from_email='password-reset@sn.local', html_email_template_name='users/password_reset/email_password_reset.html' ), name='password_reset_request'), path('reset_password/check_your_email/', views.password_reset_check_your_email, name='password_reset_check_your_email'), path('reset_password/<uidb64>/<slug:token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset/password_reset_form.html', post_reset_login=True, success_url='/'), name='password_reset_form'), ] All the urls work fine, except the last one which gives me a no reverse match error. The url I am trying to use is: http://127.0.0.1:8000/reset_password/bAAAAAA/52s-c48e21c49899996ec19c/ When I try to visit it, it gives me this error: Reverse for 'password_reset_form' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['reset_password/(?P<uidb64>[^/]+)/(?P<token>[-a-zA-Z0-9_]+)/$'] I feel like I am missing something here... Any help would be grately appreciated -
How can I use WYSIWYG editor in Wagtail CMS?
I'm trying to integrate Wagtail CMS with my existing Django project. Other than this basic installation, I made a file named wagtail_hooks.py. Everything's good so far, but I need to use WYSIWYG editor on Wagtail CMS. Is there a way to access models.py for Wagtail so that I can use third-party WYSIWYG editor on model level? MY_APP/wagtail_hooks.py from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register) from .models import Store class StoreAdmin(ModelAdmin): model = Store menu_label = 'Store' # ditch this to use verbose_name_plural from model menu_icon = 'doc-full' # change as required menu_order = 10 # will put in 3rd place (000 being 1st, 100 2nd) add_to_settings_menu = False # or True to add your model to the Settings sub-menu exclude_from_explorer = False # or True to exclude pages of this type from Wagtail's explorer view list_display = ['id', 'status', 'typ', 'businessName',] search_fields = ('businessName', 'created_by__username',) # Now you just need to register your customised ModelAdmin class with Wagtail modeladmin_register(StoreAdmin) -
Is it possible to define views and templates for abstract models to be used for actual models?
Let's say I have a myapp django app and that I need to define 2 specific contact-related models, e.g. myapp.PersonContact myapp.CompanyContact Somewhat obvious thing to do is to create a new contacts app and define an abstract contacts.Contact model which can then be reused in myapp.models, e.g.: # contacts/models.py from django.db import models class Contact(models.Model): name = models.CharField(max_length=80) ... class Meta: abstract = True # myapp/models.py from contacts.models import Contact class PersonContact(Contact): person = ... class CompanyContact(Contact): company = ... My goal is to abstract as much logic as possible to the contacts app but the only thing that comes to mind is to define an Abstract class contacts.Contact and use that so that I don't have to redefine the same fields in myapp.PersonContact and myapp.CompanyContact. Is is somehow possible to define contacts.Contact related views and/or templates within the contacts app so that I don't have to create almost identical CRUD-ish views and templates for both PersonContact and CompanyContact? -
Django Rest Framework missing CSRF Token Vue
well I have my code, a few days ago it works perfectly, but now when I try to use two method it says me "CSRF Failed: CSRF token missing or incorrect". Here is my code: /* Logout Function I'm using rest_auth */ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); const router = new VueRouter({ routes: [ {path: '/logout', alias: '/logout'} ], }); new Vue({ el: '#logout', router: router, delimiters: ['${','}'], headers: {'HTTP_X_XSRF_TOKEN': csrftoken}, data:{ loading: false, newUser: { 'username': null, 'password': null}, }, mounted: function(){ }, methods: { logout: function(){ this.$http.post('/auth/logout/').then((response) => { loading = true; sessionStorage.removeItem("auth"); router.go('/login'); }).catch((err) => { console.log(err); }) } } }); this a few days ago works without a problem. Please help me! and forward thanks! -
How to migrate django 1.8 users to firebase
I try to migrate django 1.8 users to firebase, and django password algorithm is django_pbkdf2_sha256, and the firebase support PBKDF2_SHA256 Error: Unsupported hash algorithm DJANGO_PBKDF2_SHA256 How do I bypass this? Ref: https://firebase.google.com/docs/cli/auth?hl=es-419 from passlib.hash import pbkdf2_sha256, django_pbkdf2_sha256 from passlib.utils import to_bytes, to_native_str import base64 PASSWORD = 'aA123456*' ROUND = 20000 SALT = to_bytes('google') hash0 = pbkdf2_sha256.using(salt=SALT,rounds=ROUND).hash(PASSWORD) print(pbkdf2_sha256.identify(hash0)) # True print(pbkdf2_sha256.verify(PASSWORD,hash0)) # True print(hash0) # $pbkdf2-sha256$20000$Z29vZ2xl$PtFLyZHJJucUa2KBg1iJeVJsivis8JimRhFifRRKlFc # Current keys generate by django 1.8 dj = [{"model": "auth.user", "fields": {"password": "pbkdf2_sha256$20000$mkMhRA3bpiV7$GDkKvfuzu6b9YrKGk1jy3pKkA/DUIKYc9rYEuzRLoIw=", "last_login": "2019-01-07T15:30:38.959Z", "is_superuser": True, "username": "romel", "first_name": "", "last_name": "", "email": "", "is_staff": True, "is_active": True, "date_joined": "2018-11-02T18:07:14Z", "groups": [1], "user_permissions": [1]}, "pk": 2}] print('is hash 0 is valid pbkdf2_sha256 algorithm >>>', pbkdf2_sha256.identify(hash0)) // Result: True print('is hash 1 is valid pbkdf2_sha256 algorithm >>>', pbkdf2_sha256.identify(dj[0]['fields']['password'])) // Result: False print('is hash 1 is valid django_pbkdf2_sha256 algorithm >>>', django_pbkdf2_sha256.identify(dj[0]['fields']['password'])) // Result: True -
How to change the input of django form field, so HTML is rendered with specific input-type
Following situation: I want to have a small form in which a user can enter a day, a start time and an end time. For each of this three fields I want to have a date/timepicker. As I do not want to use Bootstrap or jQuery because my project is very small and I just want to keep it small I wanted to use the native HTML pickers which are shown when changing the input-type of a field to 'date' or 'time'. I tried to change the input types of my Fields according to this Question/Answer: Django form.as_p DateField not showing input type as date This did not work for me. This is my form, with the inputs. There are two approches, for the DateInput I tried it like it was shown in the linked question, for the TimeInput I tried to override the widget. from django import forms from django.contrib.admin import widgets from django.utils import timezone from django.forms.widgets import TimeInput from .models import Occupancy class UltraDateInput(forms.DateInput): input_type = 'date' class UltraTimeInput(TimeInput): input_type = 'time' class OccupancyForm(forms.ModelForm): occupancy_date = forms.DateField() start_time = forms.TimeField() end_time = forms.TimeField() class Meta: model = Occupancy exclude = ['user', 'start', 'end'] fields = ['occupancy_date', 'start_time', … -
django postgres could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1)
I just deploy Django app on aws lambda with Zappa but I am getting an error. I don't know if I have to install Postgres because I think its automatically installed from requirements.txt OperationalError at /admin/login/ could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Request Method: POST Request URL: https://tmzgl5al3h.execute-api.ap-south-1.amazonaws.com/dev/admin/login/?next=%2Fdev%2Fadmin%2F Django Version: 2.1.4 Exception Type: OperationalError Exception Value: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Exception Location: /var/task/psycopg2/init.py in connect, line 130 Python Executable: /var/lang/bin/python3.6 Python Version: 3.6.1 Python Path: ['/var/task', '/opt/python/lib/python3.6/site-packages', '/opt/python', '/var/runtime', '/var/runtime/awslambda', '/var/lang/lib/python36.zip', '/var/lang/lib/python3.6', '/var/lang/lib/python3.6/lib-dynload', '/var/lang/lib/python3.6/site-packages', '/opt/python/lib/python3.6/site-packages', '/opt/python', '/var/task'] -
How to prevent default image from being deleted when a user gets deleted?
I have a model for users profile images and when I delete a user that has the default image, the default image also gets deleted. I believe this has to do because I set the on_delete=models.CASCADE. I have tried to put on_delete=PROTECT in the ImageField but it doesn't recognize that attribute. from django.db import models from django.contrib.auth.models import User from PIL import Image 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, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) -
python-django framework error Unhandled exception in thread started by <function wrapper at 0x0000000004473F28>
I am new to python, I managed to run my code and displayed it in server fine after I updated serializers, views, URLs I am getting the following errors I am working in a windows machine, coding in pycharm models.py # -- coding: utf-8 -- from future import unicode_literals from django.db import models class users(models.Model): name = models.CharField(max_length=20) profile_name = models.CharField(max_length=20) e_mail = models.CharField(max_length=30) phone = models.CharField(max_length=15) password = models.CharField(max_length=20) confirm_password = models.CharField(max_length=20) def __str__(self): return self.name views.py # -- coding: utf-8 -- from future import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.views import Response from rest_framework import status from .models import users from .serializers import usersSerializer class userList(APIView): def get(self, request): user1 = users.objects.all() serializer = usersSerializer(user1, many=True) return Response(serializer.data) def __pos__(self): pass urls.py """eatslush URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: … -
Nginx/Apache2 WebSocket connection to failed: Error during WebSocket handshake: Unexpected response code: 404
I am using Ubuntu 18.04 LTS, Django 2.1, Python 3.6, Nginx, Gunicorn and the testing project I copied from is through this link: https://channels.readthedocs.io/en/latest/tutorial/part_1.html But i got the 404 error. WebSocket connection to 'ws://54.184.201.27/ws/chat/lobby/' failed: Error during WebSocket handshake: Unexpected response code: 404 Chat socket closed unexpectedly I got some idea from the github issues posted here: https://github.com/socketio/socket.io/issues/1942 and answers are that I should add some code to my conf file. But I still got the error. /etc/nginx/sites-available/project.conf server { listen 80; server_name 54.184.201.27; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/django-channels/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } I didn't put the proxy_set_header Host $host here as it will gave the error of wrong ip address. Any idea of how to solve the problem? -
python manage.py migrate throwing error using xamp (phpmyadmin) with Django in windows 10
Python Version - 3.7.2 Django Version - 2.1.5 getting the error after command >python manage.py migrate please find the attached error message. (py1) C:\Users\tejra\Documents\DjangoProject\Dproject>python manage.py migrate Traceback (most recent call last): File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "C:\Users\tejra\Envs\py1\lib\site-packages\MySQLdb__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "C:\Users\tejra\Envs\py1\lib\site-packages\MySQLdb\connections.py", line 204, in init super(Connection, self).init(*args, **kwargs2) _mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\management\commands\migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\mysql\validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\mysql\validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 255, in cursor return self._cursor() File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 232, in _cursor self.ensure_connection() File "C:\Users\tejra\Envs\py1\lib\site-packages\django\db\backends\base\base.py", … -
django 2 email unsubscribe link view and model
I am trying to create an unsubscribe link, to be included with update notification emails sent to users. Similar to this one. I'm teaching myself and do not know how to call uidb64 and token for creating the views. I cannot find any instruction in the django documentation. Could anyone help with this, or point me to where to begin? I have seen this, but it appears to be for Django 1.x and I do not know whether it is still applicable. -
Specifying date format in Django templates with L10N for one language
In a Django template I'm displaying a date like: {{ article.published_at|date }} which displays like: Nov. 21, 2018 I would like to change this format, but: I am using Localization, so I don't want to specify a specific date format in the template -- each language will have its own way of displaying dates. The Django DATE_FORMAT setting does not have any effect when the L10N setting is True. So how would I: Use a different format for this date when the current language is English (en) Use the current language's default date format when it's not en -
Django Migrate Exclusion of Specific Models to Different Databases
I have been struggling with this aggravation for a little bit, and I have not been able to find a definitive answer elsewhere online. I have a Django app that uses multiple databases; a default db and then a client db. The default db holds universal tables. The client db holds custom data/tables created by the client who uses my application. I understand how migrations work, but I am using 2 databases that should not have the same models included when I run migrations. client's should have the client tables and the default db should hold the universal data. It is also important to note (because of the question below) that I do not make application specific models (other than the default ones auto-generated by Django itself), I use 2 packages/applications for this: objects and objects_client, objects holds the default db models and objects_client holds the client db models. client_db is also the name I use in settings.py Now here is my issue: I know I can run python3 manage.py migrate objects_client --database=client_db and python3 manage.py migrate objects --database=default, but I don't want to have to individually specify the admin, auth, contenttypes, and sessions migrations to the default database so … -
Django Operation error: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')
I can not start my django server after running a statement through manage.py for generating class diagrams from db. And I always get this error but I don't know how to deal with it. OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') I have tried re-install all the modules relevant to mysql for django but it was useless.