Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving Django static files from private S3 bucket using CloudFront
I am running Django 3.2.16 and Python 3.7.3. I want to serve my static Django files from a private AWS S3 bucket. I am using django-storages 1.13.1 and boto3 1.24.85. I have been following this article: https://shrinidhinhegde.medium.com/how-to-serve-django-static-files-in-a-production-environment-from-a-private-s3-bucket-using-aee840a5a643 I have my S3 and CloudFront infrastructure set up. However, I am having trouble with the AWS_CLOUDFRONT_KEY and AWS_CLOUDFRONT_KEY_ID in my settings.py. I am using python-decouple 3.3. I generated private and public keys with 'openssl genrsa -out private_key.pem 2048' and 'openssl rsa -pubout -in private_key.pem -out public_key.pem' from a cygwin window on my Windows PC. In my .ini file I have the the two keys entered like this: AWS_CLOUDFRONT_KEY=-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAn05f+B/dcarBHa4hTyPCSYgP9x39qnN74yLDmy4QGw8MaRaB lftda77PNuwj/DTjUc59YPlMM8HIS9D436I3ngPEnhn5B3ojfu80xr5zCIZXIynW d827CKjKjaputHQu5L2ef13YYpMqUIaaLuxhvKyVcpla1c1gBPVOlyAe9QWJdazq SrkyHO3DakBfK2bySr433EkYTDx0AwLJ4iVBAuo71pYgRXipJ+G84d9q1kAPK8RU ... UOb3kifExjFSsmtAUgfmog99HOgcdxDkHcMR/FR/0jz6ji0gsE/G4nsQioYYY4Hq bxnZAoGAG/sVbReKOpcHQo4bxJ+F4SzjyN+TQF7rNI3qgUe6S7xlHVsuzPgwPPrv q2Ax8mi24weX4VdxmXupT1rZ+DpNQN2K6YPtn/kaP93oh7dPpoMiC3jmNKUO3Zkr jbj6BO/UbcvI7noxgMTTCjSCHs2/VE6tuOkS635AH6HjO1Ag6i4= -----END RSA PRIVATE KEY----- and AWS_CLOUDFRONT_KEY_ID=-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn05f+B/dcarBHa4hTyPC ... JlEKvnt+sVI5aBI0o9ylSvIHqpnYeN8vsRswRbLUYti9k5wCjrhmKZTH5PudPruw MQIDAQAB -----END PUBLIC KEY----- I am using a tab at the beginning of each continuation line of the two KEYs in my .ini file to satisfy decouple's config. The public key has been added to CloudFront. I read the two keys into my settings.py file with: AWS_CLOUDFRONT_KEY = config('AWS_CLOUDFRONT_KEY') AWS_CLOUDFRONT_KEY_ID = config('AWS_CLOUDFRONT_KEY_ID') That let's me launch the Django app. When I go to the web site, though, I am getting an … -
Javascript this.value onchange not working
I'm trying to get the value of a form input usign JS: HTML: <td onchange="validate_hours(this)">{{ form.monday }}</td> JS: function validate_hours(elem) { console.log(elem.value) } But I receive "undefined", this makes sence to me but doesn't work, any idea about why? I found a solution, I used firstChild to get the input and now is returning the value: JS function validate_hours(elem) { input = elem.firstChild.value console.log(input) } -
How to refresh an id using innerHTML when a button is clicked
I have the following JS code and I am trying to reload the content of the innerHTML not just insert it as it is. Here is the script <button value="true" id="customSwitches">Button</button> <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click','#customSwitches', function(event){ event.preventDefault(); document.getElementById("table").innerHTML = `{% include 'app/table.html' %}`; }, }); }); </script> -
Django Error (admin.E106) ModelInline must have a 'model' attribute
Was just following the tutorials from Django documentation. In Writing your first Django app, part 7, the tutorial was adding the Choice section when a user is adding a Question. In the documentation, the code seems to work fine, but in my system, for some reason it isn't working. Please tell me where I got it wrong. code: from django.contrib import admin from .models import Choice, Question # Register your models here. class ChoiceInline(admin.TabularInline): model: Choice extra: 3 class QuestionAdmin(admin.ModelAdmin): # fields = ['pub_date', 'question_text'] fieldsets = [ (None, {'fields': ['question_text']}), ('Date Information', {'fields': ['pub_date'], 'classes':['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) Error: <class 'polls.admin.QuestionAdmin'>: (admin.E105) 'polls.admin.ChoiceInline' must have a 'model' attribute. -
Django: RecursionError: maximum recursion depth exceeded while calling a Python object
I'm trying to create a superuser using python manage.py createsuperuser. I got RecursionError: maximum recursion depth exceeded while calling a Python object. Models.py import datetime from django.db import models import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserManager(BaseUserManager): # Creating Super User def create_superuser(self, first_name, last_name, email, password, **kwargs): kwargs.setdefault('is_admin', True) kwargs.setdefault('is_staff', True) kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', True) if kwargs.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True' ) if kwargs.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True' ) return self.create_superuser(first_name, last_name, email, password, **kwargs) # Creating User def create_user(self, first_name, last_name, email, username, password, **kwargs): email = self.normalize_email(email) # User Object user = self.model(email=email, username=username, password=password, first_name=first_name, last_name=last_name, **kwargs) # Saving User user.save() return user Admin.py class UserAdmin(UserAdmin): model = User list_display=["first_name", "last_name", "username", "email", "created_time", "last_login"] list_filter = ['is_active', 'is_staff',] admin.site.register(User, UserAdmin) Error Traceback (most recent call last): File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\template_layer\manage.py", line 22, in <module> main() File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\template_layer\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- … -
django import_export Users password not encoded
i use library from import_export.admin import ImportExportModelAdmin to make admin enterface get file xls ..csv ..etc so I can enter a lot of data just by entre one file with all data the problem is when I export fill Users and then fail all data I find the password not encoded my admin.py file from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin from import_export.admin import ImportExportModelAdmin from student.models import Students, CustomUser class UserModel(UserAdmin): pass class UserModel2(ImportExportModelAdmin): pass admin.site.register(CustomUser , UserModel2) i dont know how to use from django.contrib.auth.hashers import make_password to solve this problem -
Package management issue with Poetry virtual environment and Django
I spent a good deal of time the past two days trying to use poetry correctly. I'm not new to poetry and have used it for a while. But in this DJANGO project I just started with a buddy, after adding packages, some of them needed to be added again via 'python -m pip install '. Once I did that, the django project passed a check and I could also migrate tables. It really bothers me that I'm using a virtual management package that doesn't appear to always work. I like poetry and want to use it. Some of the packages I had to pip install are django and pymysql. I also use pyenv. I'm running python version 3.10.6. I did things such as deleting the .venv folder (mine gets created in the project directory) checking with pip freeze that these packages are not already installed, and then doing a poetry update to re-create .venv. Any suggestions or ideas? I really need to focus on my django project and not be farting around all the time with package issues so I would like to either fix this or at least have a better idea of what is going wrong so … -
docker nginx django gunicorn not serving static files in production
Trying to deploy website with nginx + gunicorn + docker + django. But ngingx isn't serving static files. Following are the configurations: Django project structure settings file production.py STATIC_URL = "/static/" """STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )""" STATIC_ROOT = "/app/forex/static/admin/" Docker file for nginx FROM nginx:1.19.0 COPY ./default.conf /etc/nginx/conf.d/default.conf nginx configurations upstream django { server website:8000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { proxy_pass http://django; } location /media/ { alias /app/media/; } location /static/ { alias /app/forex/static/admin/; } } Gunicorn docker file FROM python:3 ADD requirements.txt /app/requirements.txt ADD . /app WORKDIR /app EXPOSE 8000:8000 RUN pip install --upgrade pip && pip install -r /app/requirements.txt RUN python manage.py collectstatic --no-input --settings=forex.settings.production CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "forex.wsgi:application", "DJANGO_SETTINGS_MODULE=forex.settings.production"] docker-compose.yml services: website: build: context: . dockerfile: Dockerfile.app env_file: - env container_name: website_container_8 nginx: build: ./nginx volumes: - static:/app/forex/static/admin/ ports: - "80:80" depends_on: - website volumes: static: FROM nginx container, it isn't copying static files. What do I need to change to make it working? -
No Change detect in table format
I face a problem in migrations when I run makemigrations command no change detect in my table and one more thing I get this error on just one table, all other tables create and change successfully. One more thing app name added in INSTALLED_APPS and I use xampp as a server. Thanks -
Generating continuous default names for new objects in Django
I want to create a model with a default name field. e.g If its the first object, the default name will be: new, then new1, new2 ... How do I accomplish this in Django models? -
Django Rest Framework cannot override viewset list() method
I have a model: class Investment(models.Model): status = models.CharField() @property def email_main(self): return self.account.email and a serializer: class InvestmentSerializer(serializers.ModelSerializer): email_main = serializers.ReadOnlyField() class Meta: model = Investment fields = '__all__' and finally a view: class InvestmentView(LoggingMixin, viewsets.ModelViewSet): queryset = Investment.objects.all() serializer_class = InvestmentSerializer permission_classes = [AllowAny] filter_backends = [DjangoFilterBackend] filterset_fields = ['email_main'] def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) print('request.query_params ', request.query_params) if request.query_params.email_main: queryset = Investments.objects.get(account__email='something') serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I'm trying to override the list method to check if the parameter has email_main so I can filter the results with the email property. But I can't even see the print function inside the method. What might I be missing? -
Django-filters - How to add autocomplete feature
I have made filters using django-filters. As a result I get a dropdown menu. Is it possible to add an autocomplete/search field to this dropdown? I have already tried to add the Select2Widget widget as indicated in another post, but the only thing that changes is that it adds an empty field before the dotted line. But it won't let me write anything. Maybe something is missing in the template??? Stackoverflow don't let me add images yet so I share the code I have. filters.py import django_filters from django_select2.forms import Select2Widget from .models import Consumo, Cliente AÑO_CHOICES = (('2021', '2021'), ('2022', '2022'),) class ConsumoFilter(django_filters.FilterSet): año = django_filters.ChoiceFilter(choices=AÑO_CHOICES, label='Año', widget=Select2Widget(attrs={'style':'width: 20ch', 'class':'form-select form-select-sm'})) name = django_filters.ModelChoiceFilter(queryset=Cliente.objects.all(), label='Clientes', widget=Select2Widget(attrs={'style':'width: 85ch','class': 'form-select form-select-sm'})) class Meta: model = Consumo fields = ['name', 'año'] template {% extends 'clientes/base.html' %} {% load static %} {% block title %}Title{% endblock %} {% block head %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> {% endblock %} {% block content %} <div class="card" style="margin-top: 20px; margin-bottom: 20px;"> <div class="card-body"> <h4 class="card-title">Consumos</h4> <h6 class="card-subtitle mb-2 text-muted">Consumos por cliente</h6> <hr> <div class="container"> <div class="row"> <div class="col-lg-12"> <form method="get"> {{ consumo_filter.form }} <br> <button type="submit" … -
serialize a Post Table which has a Like table connected to it by Fk
hi,since I am just noobie in DRF I need your help in serializing the Post table. I have a Post model like this : class Post(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) title = models.CharField(max_length=255) descripotion = models.TextField(blank=True) link = models.CharField(max_length=255, blank=True) def __str__(self): return self.title And then there is a like Model which is related to Post model by FK class Like(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) post= models.ForeignKey( 'Post', on_delete=models.CASCADE ) def __str__(self): return self.id and this is my serializers.py for Post table class PostSerializers(serializers.ModelSerializer): user = UserSerializer( required = False ) class Meta: model = Post fields = [ 'id', 'title', 'link','user','descripotion'] read_only_fields = ['id'] this returns the following response { "id": 5, "title": "string", "link": "string", "user": { "email": "admin@mail.com", "name": "sia" }, "descripotion": "string" } But I want a response to have the Like counts in it { "id": 5, "title": "string", "link": "string", "user": { "email": "admin@mail.com", "name": "sia" }, "descripotion": "string", "like_count: 50 " } -
Django Rest Framework filtering against serializer method fields
In my serializers, I have added the custom field "step_type" that grabs a value from another model. class AccountSerializer(serializers.ModelSerializer): step_type= serializers.SerializerMethodField() class Meta: model = Account fields = '__all__' def get_step_type(self, obj): step = Step.objects.get(step_name=obj.step_name) return step.step_type I want to use query parameters to filter my REST API class AccountViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = Account.objects.all().order_by('-date') query_step_type = self.request.query_params.get("type") if query_step_type is not None: queryset = queryset.filter(step_type=query_step_type) return queryset However, this won't work because step_type isn't part of the original model fields. How can I filter the queryset using the step type serializer method field? -
How to extract data from json response made by an api in python, Django
I am creating a charge and I want from it to take its 'hosted_url' in order to redirect a user from page. I am trying to extract it from json, but I newbie and don't know how ... url = "https://api.commerce.coinbase.com/charges" payload = { "local_price": { "amount": 1, "currency": USDT }, "name": "Test for fun", "description": "Project 2", "pricing_type": "fixed_price" } headers = { "accept": "application/json", "X-CC-Version": "2018-03-22", "X-CC-Api-Key" : "**********", "content-type": "application/json" } response = requests.post(url, json=payload, headers=headers) print(response.text) This is a code to make a request to an api in order to create a charge and in JSON Response I get field: "hosted_url": "https://commerce.coinbase.com/charges/123DVAS", I want somehow to put this message '123DVAS' in variable or to make a redirect like this: return render(request, 'https://commerce.coinbase.com/charges/123DVAS') -
Django Serializer with Websockets not working due to request and HyperLinkedModelSerializer
I am trying to use a websockets to send a queryset to my frontend using a model serializer. When I test this out I receive the following message: "HyperlinkedIdentityField" requires the request in the serializer context. Add context={'request': request} when instantiating the serializer. This is my frontend test code: function websocket_test(){ ws.send(JSON.stringify({ action: "list", request_id: new Date().getTime() })) } This is my serializer: class InstructorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Instructor fields='__all__' This is my consumer: class Instructors_Consumer( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, GenericAsyncAPIConsumer): queryset=Instructor.objects.all() serializer_class=InstructorSerializer I don't quite understand what is going wrong. The error raised mentions adding a context keyword when I instantiate the serializer; however I have no clue on why it would need the request or where to instantiate. Any help would be greatly appreciated as I'm completely lost on how to fix this issue. Thank you. -
social-auth-app-django facebook authentication url blocked
My settings.py has the following : LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'login' SOCIAL_AUTH_URL_NAMESPACE = 'social' AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.instagram.InstagramOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_PIPELINE = [ 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.auth_allowed', ] SOCIAL_AUTH_FACEBOOK_KEY = "..." SOCIAL_AUTH_FACEBOOK_SECRET = "..." INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'rest_framework.authtoken', "core", 'social_django', 'sslserver', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) myapp.urls.py: urlpatterns = [ path("admin/", admin.site.urls), path('', include('core.urls')), path('social-auth/', include('social_django.urls', namespace="social")), ] core.urls.py urlpatterns = [ path("", views.title, name="title"), path("home", views.home, name="home"), path("login", views.login, name="login"), path('logout', views.logout, name='logout'), ] core.views.py def title(request): return render(request, 'title.html') def login(request): return render(request, 'login.html') @login_required def home(request): return render(request, 'home.html') @login_required def logout(request): try: del request.session['uid'] except: pass auth.logout(request) return redirect('login') templates.registration.login.html <button class="btn btn-primary mb-2"> <a href="{% url 'social:begin' 'facebook' %}">Login with Facebook</a> </button> I've added localhost in I've added the full localhost website I've added the redicection url But still I get the blocked url error when clicking on the button "login with facebook" I've looked everywhere on the internet and could not find the issue. Any idea please? -
Django - effective method to check if one user follows another user (many-to-many relations)
Basically I'm implementing pretty straightforward feature - in which one user might go to another user profile page and follow/unfollow him. In order to steer the user interface logic I'd like to know if one user already follows another user (or not). I implemented a method in django that works, but I think it's rather nasty. Any suggestions how this query could be simplified with Django ORM queries? Thank you for your suggestions! class User(AbstractUser): follows = models.ManyToManyField("self", blank = True, null = True, symmetrical=False, related_name="followers") pass def serialize(self): return{ "followsCount" : self.follows.all().count(), "followersCount": self.followers.all().count() } def checkFollows(self, followCandidate ): # basically it checks if user of the application follows a candidate which profile is he viewing by iterating through a collection of users that he follows. for item in q: if item == followCandidate: return True return False -
Django wrap text inside form
Hi i try wrap a text inside my form but nothing works. I tried to style or insert {{ forms|crispy|wordwrap:50 }} but that doesn't work either,the text continues to overflow without a line break does anyone have a solution ? ===page.html=== {% extends 'accounts/main.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <br> <style> #id_Note{ padding-bottom: 600px; word-break: break-all; } </style> <h4>Add note</h4> <div class="row"> <div class="col-md-12"> <div class="card card-body"> <form class="note" action="" method="POST"> {% csrf_token %} {{ forms|crispy|wordwrap:50 }} <input class="btn btn-primary" type="submit" value="Enregistrer" name="Enregistrer"> </form> </div> </div> </div> {% endblock %} -
Getting error while eb deploy : ERROR: NotAuthorizedError - Operation Denied. Access Denied
ERROR: NotAuthorizedError - Operation Denied. Access Denied Stack: Django application hosted on AWS using Elasticbeanstalk. Everything was working fine the last time I deployed using eb deploy for my QA environment. Now suddenly getting this error that I'm not authorized to perform this action. Checked the credentials and key-pair as well. Nothing in the settings has been updated after the last deployment. The only thing that is different from the previous deployment is packages since requiremnents.txt has been updated. eb ssh is working fine as well. -
React-Django csrf token Authentication
I'm really stuck here, and I've tried everything I've seen online. I followed this guide to perform react-Django csrf token Authentication. when I send a request to csrf cookie it looks like everything works in the backend (django) side: [05/Oct/2022 22:21:59] "GET /accounts/csrf_cookie HTTP/1.1" 200 29 @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({'success': 'CSRF cookie set'}) And same from the frontend (react) side: 1. {data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …} 1. config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} 2. data: {success: 'CSRF cookie set'} 3. headers: {content-length: '29', content-type: 'application/json'} 4. request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} 5. status: 200 6. statusText: "OK" 7. [[Prototype]]: Object useEffect(() => { const fetchData = async () => { try { const res = await axios.get( `${process.env.REACT_APP_API_URL}/accounts/csrf_cookie` ); console.log(res); } catch (err) { console.log(err); } }; fetchData(); setcsrftoken(getCookie("csrftoken")); }, []); Again it seems as if the whole process was completed successfully, the problem is that in practice no cookie appears in my browser! If I manually enter http://127.0.0.1:8000//accounts/csrf_cookie I do get the cookie for the browser... I would appreciate … -
do not display already selected items as choices in the dropdown in django admin inline but preserve already selected
I am using Tabularinline class inside the django admin for many to many relation. I want to filter the queryset so already selected can't be chosen. I tried to override formfield_for_foreignkey method and it partially does the job. Choices are in the desired they (What is already selected are not present in the choices) but the default state is empty for the fields which already exist and when I try to submit a form it throughs an error indicating that the field is required (which should be this way) I don't know how to achieve this goal without overriding the admin template This is how the admin panel looks like -
Django Rest API Cache with Radis & seeking sugestion
Problem I have a backend with Django (Wagtail CMS) and a frontend with react. I am using them as a news site. I am new in Django and my other teammate manages the front end. I am providing them with wagtail's default API with some customization(I have exposed all needed fields in BaseAPIView). In my API there were 25 blog posts for the first time and now there are 60 posts. The first time the API loading time was 1.02 sec and now the API load time is 1.69sec. I am afraid of what will happen when the posts hit 5000+! Because I am not limiting anything in the API. Plan I am planning to use radis cache for the API. But I can't understand what should I set in the API views! because my API views is this. #api.py from wagtail.api.v2.views import PagesAPIViewSet,BaseAPIViewSet api_router = WagtailAPIRouter('wagtailapi') class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] meta_fields = ["type","seo_title","search_description","first_published_at"] body_fields = ["id","type","seo_title","search_description","first_published_at","title"] listing_default_fields = ["type","seo_title","search_description","first_published_at","id","title","alternative_title","news_slug","blog_image","video_thumbnail","categories","blog_authors","excerpt","content","content2","tags","story_type"] nested_default_fields = [] def get_queryset(self): return super().get_queryset().filter(story_type='Story').order_by('-first_published_at') name = "stories" model = AddStory api_router.register_endpoint("stories", ProdPagesAPIViewSet) Will adding radis cache in API solve the loading problem or should I add … -
Django - command createsuperuser creates superuser in the default database when passing the --database parameter
I have three Postgre databases in my project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'default', 'USER': 'user', 'PASSWORD': 'password', }, 'clients_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'clients_db', 'USER': 'user', 'PASSWORD': 'password', }, 'other': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'other', 'USER': 'user', 'PASSWORD': 'password', }, } And three apps: clients, users and myapp. The app clients have a router for the clients_db database: class ClientsRouter: route_app_labels = {'clients'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'clients_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'clients_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'clients_db' return None The other two apps uses the same database. I can run migrations and migrate just fine using the commands: python manage.py makemigrations Then, to apply migrations to the default database: python manage.py migrate And to apply migrations to the other database: python manage.py migrate --database other But when I try to run the command to create a superuser in the other database, it creates a superuser in the default database instead. The command: python … -
How can I allow the user to edit comments in a Django Blog using DetailView and UpdateView on the same page?
I've been at this for a couple days and have followed a few different tutorials to get what I want. I'm pretty close....I just can't figure out how to get the user to be able to edit their comment. I've tried several different approaches...Here's what I have so far... My Models... class Suggestion(models.Model): id = models.UUIDField(default=uuid.uuid4,primary_key=True,unique=True) created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='suggestion_created_by') last_update = models.DateTimeField(editable=False,null=True) suggestion_creation_date = models.DateTimeField(editable=False,null=True) suggestion_name = models.CharField(max_length=255,null=True) suggestion_status = HTMLField(blank=True,null=True) suggestion = HTMLField(blank=True,null=True) unique_identifier = models.CharField(max_length=64,null=True,blank=True) class Meta: ordering = ["suggestion_name"] def __str__(self): return self.suggestion_name def get_absolute_url(self): return reverse("Suggestions:suggestion_detail",kwargs={'pk':self.pk}) class SuggestionComment(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) comment = models.CharField(max_length=255,blank=True) created_on = models.DateTimeField(default=timezone.now) suggestion = models.ForeignKey('Suggestion',on_delete=models.CASCADE,related_name='suggestion_comments') upvotes = models.ManyToManyField(User,blank=True,related_name='suggestion_comment_upvotes') def get_absolute_url(self): return reverse("Suggestions:suggestion-detail", kwargs={"pk": self.suggestion.pk}) My Templates... DetailView.. <!DOCTYPE html> {% extends "base21.html" %} <title>{% block title %} LevelSet Suggestion By Name Detail {% endblock %}</title> {% block body_block %} <div class="box12"> <h1 class="title">{{ suggestion_detail.suggestion_name }}</h1> <div class="spacer281"> {{ suggestion_detail.suggestion|safe }} </div> {% if suggestion_detail.suggestion_status != None %} <div class="spacer280"> <h2>Status - </h2> </div> <div class="spacer76"> {{ suggestion_detail.suggestion_status|safe }} </div> {% endif %} <div class="spacer285"> {% include 'suggestion_comments.html' %} </div> </div> </div> {% endblock %} suggestion_comments.html ( Include ) <form method='POST' class="comment-form"> {% csrf_token %} <div class="spacer284"> {{ form.comment }} </div> <button …