Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Update Record before save
Model: class Tester: test = models.ForeignKey(Platform) count = models.Integer() status = models.CharField(max_length=1, default='A') I need to change the status to 'D' every time I insert a new record for the same test. I tried using Signals pre_save, but that function went into a loop. I would really appreciate any help. -
MongoDB Atlas connection issue with Django
I am trying to connect my Django application with the Atlas MongoDB cloud database using Djongo. The setting file database section is, DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'mydb', 'HOST': 'mongodb+srv://user:' + urllib.parse.quote_plus('password') + '@xx-xxxxx.mongodb.net/test?retryWrites=true&w=majority', 'USER': 'user', 'PASSWORD': 'password', } } But after running python manage.py migrate, it is throwing the following error, File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names return get_names(cursor) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\database.py", line 856, in list_collection_names … -
Django environment/setup issue: AttributeError: 'Settings' object has no attribute 'USE_REDIS'
I am new to django and docker setup environment. I have an existing django project that I need to deploy on my local server. I am configuring my python environment on Windows for Linux Ubuntu 18.04 TLS. I am able to do my setup with pipenv install. Following django packages got installed: Django==3.0.5 django-cors-headers==3.2.1 django-debug-toolbar==2.2 django-environ==0.4.5 django-filter==2.2.0 django-polymorphic==2.1.2 django-storages==1.9.1 djangorestframework==3.11.0 but when I run django-admin --version, I get error: AttributeError: 'Settings' object has no attribute 'USE_REDIS' Full stack-trace is as given below: Traceback (most recent call last): File "/home/username/.local/share/virtualenvs/project_code/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/username/.local/share/virtualenvs/project_code/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/mnt/c/Users/pgupta15/git_repos/uppley-backend/catalystlab/models.py", line 11, in <module> from catalystlab.data.models.entity import Tag, Type, Entity, update_types File "/mnt/c/Users/pgupta15/git_repos/uppley-backend/catalystlab/data/__init__.py", line 32, … -
Django form containing different types of fields
I'm wanting to add a MultipleChoiceField with a CheckboxSelectMultiple widget to a model/form containing other types of input. I am wondering how I can do this and add classes to the entire MultipleChoiceField as well as classes to each of the choices (for bootstrap). I have tried adding a class to the whole MultipleChoiceField using: preferred_subjects.widget.attrs.update({'class': 'form-control'}) but it doesn't work. Even if it did, I also want to add classes to each of the options, but I am unsure how. I usually output forms using {{ form|crispy }} but since I want to add classes to each of my MultipleChoiceField options im guessing i'll need to use {% for option in fieldset %} and add classes as each is output. But the problem is I have other types of input in that same form which I don't want to add the class names to. Here is my code: class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, default='') dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) subjects = model.CharField(max_length=200, default='') class PersonalInformationForm(forms.ModelForm): SUBS = ( ('MATH', 'Maths'), ('ENG', 'English'), ) subjects = forms.MultipleChoiceField(choices=SUBS, widget=forms.CheckboxSelectMultiple()) class Meta: model = PersonalInformation fields = ['first_name', 'gender', 'subjects'] Summary - I want to … -
Is there any method to display list items in django template with variable name as atrributes?
I want to display all the tags related to post but in different color-badge. But in place of color variable there is nothing appears and when i do with the just constant numbers like colors.0 it works but i don't want one color, I want to be change the color as the tags changes. here is my views.py file: def blogs(request): posts = Post.objects.order_by('-posted_on') tags = Post.tags.most_common()[:5] colors = [ 'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark' ] context = { 'posts': posts, 'tags': tags, 'colors': colors } return render(request, 'writeups/blogs.html', context) and my blogs.html template: {% for post in posts %} <div class="card border-dark mb-3 w-100"> <div class="card-header">{{ post.posted_on|date:"F d, Y" }}</div> <div class="card-body text-secondary"> <h5 class="card-title">{{ post.title }}</h5> <p class="card-text">{{ post.description }}</p> {% for tag in post.tags.all %} {% with forloop.counter as color %} <span class="badge badge-{{ colors.color }}">{{ tag }}</span> {% endwith %} {% endfor %} </div> </div> {% endfor %} -
How to start and stop celery beat and workers in Django?
I'm getting some data from an API every 30 seconds and insert to mongoDB periodically. hence, I used celery to process it in the background. celery.py as follow: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): from example.tasks import API sender.add_periodic_task(30, API.s(), name='Api') I have tasks.py as follow: @shared_task def API(): data=request.get(url).json() db.collectionName.insert_many(data) Then, I used two commands to run the task in the background periodically: celery -A DjangoCelery1 beat -l info celery -A DjangoCelery1 worker -l info Everything all right and data is getting from the API and saved in MongoDB. Now, I want to able to start and stop all running tasks by press a button on a web page. What should I do for this? -
Django - How to check all the attributes of a queryset?
I am looking a way to get all the attributes of a variable after we set the value in it using queryset. For example...refer below code... using user.id or user.first_name i can get the value for that attribute. But if i want to check what all other attributes it has? Is there a way i can get. If we use user then it will just return which is what we have defined in admin.py. Code, i am using Django Shell from django.contrib.auth.models import User user=User.objects.get(id=1) user.first_name # Will return some value say testUser user.id # will return some value say 1 -
Django Rest Framework return user profile along with api token after login or registration
I've got the following serializer: from rest_framework import serializers from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from kofiapi.api.users.models import User, UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('dob', 'phone', 'receive_newsletter') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.name) instance.save() profile.dob = profile_data.get('dob', profile.dob) profile.phone = profile_data.get('phone', profile.phone) profile.receive_newsletter = profile_data.get('receive_newsletter', profile.receive_newsletter) profile.save() return instance and these are the respective routes I have: router = DefaultRouter() router.register(r"users", UserViewSet) urlpatterns = [ path('', include(router.urls)), path('rest-auth/', include('rest_auth.urls')), #path('rest-auth/registration/', include('rest_auth.registration.urls')), ] I'm using: 'rest_framework', 'rest_framework.authtoken', 'rest_auth', configured as: AUTH_USER_MODEL = 'users.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } when I log in I'm getting back only the token key: { "key": "8c0d808c0413932e478be8882b2ae829efa74b3e" } how can I make it to return user info along with the key upon registration/login? Something like: { "key": "8c0d808c0413932e478be8882b2ae829efa74b3e", "user": { // user data } } -
Python crashes when including a template
this is the first time that i ask something here so excuse me if im been not so clear about the issue. At my views, i have the def home that renders the template home.html passing two variables: posts and trendList. Home.html: <div class="create"> {% include 'snippets/create.html' %} </div> <div class="main"> <div class="feed"> {% block detail %} {% endblock detail %} {% include 'snippets/post.html' %} </div> <div class="trends"> {% include 'snippets/trendList.html' %} </div> </div> The code only freezes when i do the 'include post.html'. If i call it in block format, it does not load the post.html inside the block. Post.html <div class="post"> <p> {{ post.text }}</p> <p> {{ post.created_at }}</p> <p> {{ post.author }}</p> <a href="{% url 'who_liked' pk=post.pk %}" >{{ post.likes.count }}</a><br> <a type="button" href="{{ post.pk }}" >Like</a> </div> {% endfor %} But if i click in an object of trendList, it works fine, redirecting me to the home.html with the template loading inside the blocks. I don't know why 'include post.html' crashes the program and putting it in blocks will do nothing. Thanks in advance. -
Django - Rendering a template multiple times in a loop
I have a Django view that receives a list of selected files in request. I want to iterate over all files and render the same template for each file (one after the other). Is there a way/hack to re-render the template with the modified context without returning from the view? Or is there a way to do it with javascript using local-storage, i.e., calling the view for each file (one after the other)? -
Why am I getting a Django Reslover404 Error?
I'm studying Django with djbook and so far created my 'polls' app. It works fine but when I added a log file, there is an error message in it: Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/usr/lib/python3.8/site-packages/django/urls/resolvers.py", line 567, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>], [<URLResolver <module 'polls.urls' from '/home/DeadMoroz/mysite/polls/urls.py'> (polls:polls) 'polls/'>]], 'path': ''} ... During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/template/base.py", line 848, in _resolve_lookup raise VariableDoesNotExist("Failed lookup for key " django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver <module 'polls.urls' from '/home/DeadMoroz/mysite/polls/urls.py'> (polls:polls) 'polls/'> Not Found: / My 'polls/urls.py' file seems to be the same as in Django Book: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Here's my project file structure: polls/ ---logs/ ------debug.log ---migrations/ ---static/ ------polls/ ---------images/ ------------background.gif ------style.css ---templates/ ------admin/ ---------base_site.html ------polls/ ---------detail.html ---------index.html ---------results.html ---__init.py__ ---admin.py ---apps.py ---models.py ---tests.py ---urls.py ---views.py I'm very … -
Django: How to update an Integerfield and decrement its value
This seemingly innocuous problem has turned out to be quite difficult to find any information on. I just want to decrement the value of an Integerfield column by 1 in my database, by calling a function. views.py function call StudentProfile.objects.add_lesson(student_id) managers.py class StudentQuerySet(models.QuerySet): def add_lesson(self, sid): self.filter(student_id=sid).update(remaining_lessons=remaining - 1) class StudentProfileManager(models.Manager): def add_lesson(self, sid): self.get_queryset().add_lesson(sid) Full StudentProfile model class StudentProfile(models.Model): student = models.OneToOneField( User, related_name='student', primary_key=True, parent_link=True, on_delete=models.CASCADE) portrait = models.ImageField( upload_to='studentphotos', verbose_name=_('Student Photo')) about_me = models.TextField(verbose_name=_("About Me")) spoken_languages = models.CharField(max_length=255) teacher_default = models.OneToOneField( 'teachers.TeacherProfile', related_name='teacher_default', parent_link=True, on_delete=models.CASCADE, default=None, blank=True, null=True) membership_start = models.DateTimeField( verbose_name="Membership Start Date", default=now, editable=False) membership_end = models.DateTimeField( verbose_name="Membership End Date", default=now, editable=False) remaining_lessons = models.IntegerField( verbose_name="Membership remaining lessons", default=0) objects = StudentProfileManager() def __str__(self): return User.objects.get_student_name(self.student_id) I know this is totally wrong, any help is appreciated. -
How can I validate uniqueness of an instance in a collection in django rest framework
I have the following models. class ServerGroup(models.Model): name = models.SlugField(unique=True) factor = models.IntegerField() class ServerGroupMember(models.Model): class Meta: unique_together = ( ("server_group", "position"), ("server_group", "server"), ) position = models.IntegerField() server_group = models.ForeignKey( "ServerGroup", related_name="servers", on_delete=models.CASCADE ) server = models.ForeignKey("Server", on_delete=models.CASCADE) A ServerGroup has a couple of properties, name and factor, and a collection of ServerGroupMember objects. Each ServerGroupMember object, contains an integer position and a reference to a Server object. For a given ServerGroup the position must be unique, and for a given ServerGroup the server must be unique. However, globally, the position and server objects do not have to be unique, as in 2 ServerGroups may contain a server at postion 1, and the same Server may appear in multiple Server Groups, just not multiple times in the same Server Group. Given that I have the following serializers, how can I validate the above? The model currently does validate the condition at the database level, but will raise a unique constraint error if I attempt to violate it. What I want is to be able to detect this in my views, such that I can return an appropriate validation error message response before it has a chance to hit the … -
What is the most performant way to store an image as base64 dataURL?
I am using Django 3.0 with PostgreSQL 12. I need to store an image and render it on a page as base64 for use in a javascript function. Is it more performant to: store the image as TextField and save the raw base64 in the database store the image as a file on the server (using filefield), and convert the image server side to base64 before returning it in context store the image as a file on the server, and convert the image client side to base64? The images are all <10kb big, and typically would be less than 50 per page. However there may be a large number of page loads with concurrent users. -
makemigrations isn't working- how to fix it?
I have a dockerized django project. I'm trying to make migrations, but I keep getting this error. What does this mean, and how can I fix it? I am really new to this, so please be as detailed as possible! Thank you The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", … -
Django call HttpResponse view in Javascript file
I want to call a HttpResponse from a view in my main.js file, but I'm getting this error in the console //localhost:8000/%7B%%20url%20'join_dpt'%20%%7D 404 (Not Found), everything was fine when I had all in a same index.html file but now I don't want to have the scrips in the index.html so I moved it to a main.js file. This is how I'm calling the HttpResponse (I was doing the same in the index.html file and it was fine) d3.json("{% url 'join_dpt' %}") this is how my folders order: -- django -- env -- app -- project -- urls.py -- static -- css -- js -- main.js -- templates -- index.html and I have this in my settings.py STATIC_URL = '/static/' #new STATICFILES_DIRS =( os.path.join(BASE_DIR,'static'), ) any ideas on how can I solve this? -
How to get data from Query set?
I have this data from forms <QueryDict: { 'csrfmiddlewaretoken': ['GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt', 'GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt', 'GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt', 'GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt'], 'User': ['11', '11', '12', '13'], 'month': ['march', 'march', 'february', 'july'], 'regularFee': ['1500', '988', '7656', '7000'], 'extraFee': ['0', '0', '23', '7'], 'discount': ['234', '0', '0', '7'], 'Total': ['1500', '987', '1500', '7000']}> can anyone please tell me how to extract data from this I want a new dictionary which will have index as key and value will be another dictionary of data, which will include information of each user if request.method == 'POST': keys = [] length = 0 for key in request.POST.keys(): keys.append(key) length = len(request.POST[key]) for index in range(length): dict_messForm = {} for key in keys: dict_messForm.update({key:request.POST[key][index]}) forms.append(messFeeForm(dict_messForm)) this is giving me an error 'string index out of range'...... how can I create forms from this QueryDict ? -
Connecting django to MS SQL Server using odbc
I'm getting an error when trying to execute manage.py runserver. I've installed django-pyodbc and the odbc driver 17 for sql server. Do I need to import pyodbc somewhere in the project? I am very new to django and python in general but I want to use ms sql server instead of sqlite. This is the code in manage.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'HOST': 'localhost', 'USER': 'user', 'PASSWORD': 'password', 'OPTIONS': {'ODBC Driver 17 for SQL Server', } } } Here is the error: (venv) C:\Users\Kirk\PycharmProjects\PyShop>manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001770CD61438> Traceback (most recent call last): File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Kirk\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Django Rest Framework CI Pipeline
I'm configuring an aws pipeline for my django application that uses elasticsearch, redis-celery and DRF. I'm don't have any devops experience. from best practices. How many stages should my pipeline included? And what are they? -
Adding Slugs to URL pattern
I want users to access posts using either the PK or Slug value. I can get http://localhost:8000/post/8/ to work but not http://localhost:8000/post/working-in-malaysia/. I have looked at a few posts on Stack Overflow but I don't want http://localhost:8000/post/8/working-in-malaysia. And I don't want it to be a case of either the PK works. Or the slug works. I want the user to be able to enter either. Below you can see my failed attempts. path('post/<int:pk>/', views.post_detail, name='post-detail'), #path('post/<slug:the_slug>/', views.post_detail, name='post-detail-slug'), #path('post/<slug:slug>/', views.post_detail, name='post-detail-slug'), #path('post/(?P<slug>[-\w]+)/$', views.post_detail, name='post-detail-slug'), path('post/<slug>', views.post_detail, name='post-detail-slug'), -
Paginate Filtered Search
I have a search form for the users on my page. It is actually a form with POST method, which get all inserted parameters from POST in my function and based on that parameters (check which parameters was filled in form) doing search in my database and sending it back to user like this (searched data are fetched query set based on users searching) paginator = Paginator(searched_data, 15) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'online_db/terema_kensaku.html', {'page_obj': page_obj}) which works fine, but it has one problem. This ALL happens in my function under if request.method == "POST": And of course if user press NEXT PAGE button on this searched data, he is performing a GET action, so there are no data - no NEXT PAGE. Even if I try to do the same under if request.method == "GET": it's not possible, because I'm not able to get a parameters from users (POST form) to perform database filtering on all data from database. My views.py is too long with a lot of paramaters and variables, so I'm not gonna paste it here but it works like this right now. def terema_kensaku(request): if request.method == "POST": search_data = [] search_list = … -
How to add prefix "token" on django-yasg?
I've installed django-rest-framework and django-yasg to generate the swagger documentation, when i try to use the ui from django-yasg the authentication does not use the prefix Token on the Authentication header, e.g: Header needed for django-rest-framework: "Authentication: Token XXX" Header generated by the django-yasg: "Authentication: XXX" I also have found this issue; https://github.com/axnsan12/drf-yasg/issues/367 saying that i need to add the prefix token through the swagger-ui, but how can i do this? This my swagger settings: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Token': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' }, }, 'USE_SESSION_AUTH': False } -
Django select2 not loadign value on formset extra-views
Select2 is not showing the search or values on the formset to be selected like this, but on the updateView for the individual objects it works fine. form.py class AvaliadorForm(forms.ModelForm): """Defini avaliador""" class Meta(): model = Resultado fields = ['avaliador'] #TODO Não esta funcionando widgets = { # TODO mudar DB para postersql e adiciona unaccent em search fields 'avaliador': s2forms.ModelSelect2Widget( model=User, search_fields=['nome_completo__icontains', 'matricula__icontains'], attrs={'data-minimum-input-length': 0}), } def __init__(self, *args, **kwargs): """Definie user como o user passado em get_kwargs""" super(AvaliadorForm, self).__init__(*args, **kwargs) # filtra os avaliadores com base no is_avaliador self.fields['avaliador'].queryset = User.objects.filter( is_avaliador=True) view.py class AvaliadorFormSetView(PermissionRequiredMixin, ModelFormSetView): "Defini avaliadores em bloco, com base no semestre" model = Resultado template_name = 'cc/manage_avaliadores.html' success_url = reverse_lazy('cc:solicitacoes') factory_kwargs = {'extra': 0} permission_required = 'user.can_add_avaliador' form_class = AvaliadorForm def get_queryset(self): slug = self.kwargs['slug'] return super(AvaliadorFormSetView, self).get_queryset().filter(solicitacao__semestre_solicitacao__slug=slug) I'm also using django-extra-views to render the formset. THe field avaliador is a foregein Key -
Override Django LoginView Error Message With Custom AuthenticationForm
I have a class-based view that subclasses LoginView. from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): def get_success_url(self): url = self.get_redirect_url() return url or reverse_lazy('knowledgebase:user_home', kwargs={ 'username':self.request.user.username, }) I want to override the error message if a user's email is not yet active because they have to click a link sent to their email address. The current default message looks like this: Instead of saying: Please enter a correct email address and password. Note that both fields may be case-sensitive. I want to say something to the effect of: Please confirm your email so you can log in. I tried: accounts/forms.py from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import gettext as _ class PickyAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( _("Please confirm your email so you can log in."), code='inactive', ) accounts/views.py class CustomLoginView(LoginView): # 1. <--- note: this is a class-based view form_class = PickyAuthenticationForm # 2. <--- note: define form here? def get_success_url(self): url = self.get_redirect_url() return url or reverse_lazy('knowledgebase:user_home', kwargs={ 'username':self.request.user.username, }) The result is absolutely no effect when I try to log in with a user that does exist, but hasn't verified their email address yet. -
Django django-cors-headers returning `Access-Control-Allow-Origin` header
I feel like I get CORS issues every time I set up a new server. Does anyone see something I’m missing? Access to fetch at 'https://staging-app.example.com/api/token/' from origin 'https://staging.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I’m using django-cors-headers==3.2.1 My Middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] Other settings: ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'https://staging.example.com', ] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True` CORS_ORIGIN_REGEX_WHITELIST = [ 'https://staging.example.com', ] I’ve implemented every single solution I could find on this thread: "No 'Access-Control-Allow-Origin' header is present on the requested resource" in django What else am I missing? What else can I try?