Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to publish a page in Wagtail CMS?
I'm trying to publish a page in Wagtail CMS, but I'm having trouble with the publishing process. I can access the Wagtail admin interface, but I can't seem to find the "Publish" button in the preview mode.The root page ("Welcome to your new Wagtail site!") is visible, but the page I created is not. Here are the steps I've taken: Created a new page in the Wagtail admin interface. Edited the page content and saved it as a draft. Tried to preview the page, but there's no "Publish" button in the preview mode. I've also tried going to the "Pages" section in the admin interface, finding the page I created and got to the promote and edit the slug as test1, when I go to the link with slug, I get the following error: Page not found (404) Request Method: GET Request URL: https://chat-jj.pythonanywhere.com/test1/ Raised by: wagtail.views.serve Using the URLconf defined in PyChat.urls, Django tried these URL patterns, in this order: admin/ documents/ _util/authenticate_with_password/<int:page_view_restriction_id>/<int:page_id>/ [name='wagtailcore_authenticate_with_password'] _util/login/ [name='wagtailcore_login'] ^((?:[\w\-]+/)*)$ [name='wagtail_serve'] The current path, test1/, matched the last one. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display … -
How to get data from django database model
What I did: views.py class CandidateView(View): def get(self, request, **kwargs): pk = kwargs['pk'] candidates = Resume.objects.get(pk=pk) posts = Post.objects.all().values() post_contents = [] for post in posts: if isinstance(post, dict) : continue elif isinstance(post, Post): post_contents.append(post.content) return render(request, 'blog/candidate.html', {'candidate':candidates, 'posts': post_contents}) models.py class Resume(models.Model): name = models.CharField(max_length=100) dob = models.DateField(auto_now=False, auto_now_add=False) gender = models.CharField(max_length=100) locality = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.PositiveIntegerField() state = models.CharField(choices=STATE_CHOICE, max_length=50) mobile = models.PositiveIntegerField() email = models.EmailField() job_city = models.CharField(max_length=50) profile_image = models.ImageField(upload_to='profileimg', blank=True) my_file = models.FileField(upload_to='doc', blank=True) blog_post = models.CharField(max_length=100000) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='posts', null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I'm new to Django and I want to get my blog content from Post model to CandidateView. Main idea is getting all the blog content and showing it into resume. but I cant figure it out how to do it or what I am doing wrong. -
Why does adding `only()` to my queryset cause an N+1?
I have a Django queryset called qs. When I evaluate it, it executes the following SQL query: SELECT "projects_issue"."id", "projects_issue"."name", "projects_issue"."milestone_id" FROM "projects_issue" WHERE "projects_issue"."milestone_id" = 1 ORDER BY "projects_issue"."name" ASC LIMIT 21 Now I only want to select the id field, so I evaluate qs.only("id"). This executes more than one query: SELECT "projects_issue"."id" FROM "projects_issue" WHERE "projects_issue"."milestone_id" = 1 ORDER BY "projects_issue"."name" ASC LIMIT 21 SELECT "projects_issue"."id", "projects_issue"."milestone_id" FROM "projects_issue" WHERE "projects_issue"."id" = 1 LIMIT 21 SELECT "projects_issue"."id", "projects_issue"."milestone_id" FROM "projects_issue" WHERE "projects_issue"."id" = 2 LIMIT 21 The extra queries are an N+1, executing a query for each returned item in the queryset. I don't have any Django signals registered. What could be causing these extra queries? Is there anything I can look for in the queryset to introspect it and understand this behaviour better? -
Django restframework user email already exists error
I am trying to write a login view in django restframe work to authenticate a user into the application but each time I send a request to the server I keep getting this error `{ 'email': ['email already exist'] }`` here is how I wrote my login serializer class UserLoginSerializer(serializers.ModelSerializer): full_name: str = serializers.CharField(source='get_name', read_only=True) tokens: str = serializers.CharField(source='get_token', read_only=True) class Meta: model = User fields = ( 'id', 'full_name', 'email', 'password', 'is_superuser', 'is_seller', 'created_at', 'profile_pic', 'tokens' ) extra_kwargs = { 'password' : {'write_only':True, 'required': True}, 'id': {'read_only': True}, 'is_superuser': {'read_only': True}, 'is_seller': {'read_only': True}, 'created_at': {'read_only': True}, 'profile_pic': {'read_only': True} } def validate(self, data: dict) -> dict: email: str = data.get('email', '') password: str = data.get('password', '') print(password, email) user: auth = auth.authenticate(email=email, password=password) print(user) data = { 'email': user.email, 'tokens': user.get_token() } return data and here is how I wrote my loginapiview class UserLoginAPIView(generics.GenericAPIView): serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) -
"error": "invalid_client" django-oauth-toolkit with grant_type = 'authentication_code'
So, i'm following this tutorial to apply oauth2 in my django project I handled to get an client_id, secret, code_verifier and code as it is described in the tutorial but then the tutorial asks the following: Now that you have the user authorization is time to get an access token: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=${ID}" -d "client_secret=${SECRET}" -d "code=${CODE}" -d "code_verifier=${CODE_VERIFIER}" -d "redirect_uri=http://127.0.0.1:8000/noexist/callback" -d "grant_type=authorization_code" I tried everything, checked the credentials 100 of times but the terminal output is always: {"error": "invalid_client"} I can't see what is wrong -
issue while trying to install misaka
Collecting misaka Using cached misaka-2.1.1.tar.gz (125 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: cffi>=1.0.0 in c:\users\owner\appdata\local\programs\python\python39\lib\site-packages (from misaka) (1.16.0) Requirement already satisfied: pycparser in c:\users\owner\appdata\local\programs\python\python39\lib\site-packages (from cffi>=1.0.0->misaka) (2.22) Building wheels for collected packages: misaka Building wheel for misaka (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [27 lines of output] c:\users\owner\appdata\local\programs\python\python39\lib\site-packages\setuptools_init_.py:81: _DeprecatedInstaller: setuptools.installer and fetch_build_eggs are deprecated. !! ******************************************************************************** Requirements should be satisfied by a PEP 517 installer. If you are using pip, you can try `pip install --use-pep517`. ******************************************************************************** !! dist.fetch_build_eggs(dist.setup_requires) running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-39 creating build\lib.win-amd64-cpython-39\misaka copying misaka\api.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\callbacks.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\constants.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\utils.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\__init__.py -> build\lib.win-amd64-cpython-39\misaka running build_ext generating cffi module 'build\\temp.win-amd64-cpython-39\\Release\\misaka._hoedown.c' creating build\temp.win-amd64-cpython-39 creating build\temp.win-amd64-cpython-39\Release building 'misaka._hoedown' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for misaka Running setup.py clean for misaka Failed to build misaka ERROR: Could not build wheels for misaka, which is required to … -
How can do reset password with django and angular
i don t know what is the problem exactly i try only with backend everything works any solutions pls ? i want when the user try to connect can click on reset password after that they enter the email and they will receive the email How can do reset password with django and angular How can do reset password with django and angular How can do reset password with django and angular How can do reset password with django and angular -
Refresh JWT Tokens using PyJWT
Upon using a login system bases on authentication tokens stored in cookies, I am encountering issues while trying to refresh the token without using login and password again. Is it possible to refresh the jwt tokens using PyJWT ? def get(self, request): token = request.COOKIES.get('userJwt') if token is None: raise AuthenticationFailed('Unauthenticated!') response = Response(status=200) try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: # payload['exp'] = datetime.utcnow() + timedelta(seconds=20) # new_token = jwt.encode(payload, "secret", algorithm="HS256") # response.set_cookie(key='userJwt', value=new_token, httponly=True) return Response({"message": "Expired"}, status=200) user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) response.data = serializer.data return response -
Django view function returns status code 302 when using @login_required decorator
In my views.py file in my Django app, I use the @login_required decorator for every method in the file. When the user logs in, all method function normally except for one, the getFields method. I cannot put my hand one what is going wrong regarding this one method. when I remove the @login_required decorator is functions normally. Why is it not detecting that the user is logged in for that one method? View function: @login_required def getFields(request): try: POST = json.loads(request.body) fields = Field.objects.all() field_list = [] for field in fields: field_list.append(field.to_dict()) print(field_list) return JsonResponse({ 'status': 200, 'fields': field_list }) except(ObjectDoesNotExist): return JsonResponse({ 'status': 404 }) urls.py: from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.login,name="login"), path('logout', views.logout,name='logout'), path('editProfile', views.editProfile,name='EditProfile'), path('createTable',views.creatTable,name="createTable"), path("accounts/", include("django.contrib.auth.urls")), path('signup',views.signup,name="signup"), path('forgotPassword',views.forgotPassword,name="forgotPassword"), path('getTable', views.getTable, name="getTable"), path('modifyrow', views.modifyrow, name="modifyrow"), path('deleteRow', views.deleteRow, name="deleteRow"), path('addColumn', views.addColumn, name="addColumn"), path('deleteColumn', views.deleteColumn, name='deleteColumn'), path('EditColumn', views.EditColumn, name='EditColumn'), path('getExperts', views.getExperts, name='getExperts'), path('sendemail', views.sendemail, name='sendemail'), path('getFields', views.getFields,name='getFields'), path('createExpert', views.createExpert,name='createExpert'), Calling the method using javascript: try{ const response = await fetch(`http://127.0.0.1:8000/getFields`,{ method:'GET', headers:{ 'Content-Type': 'application-json', 'X-CSRFToken': Cookies.get('csrftoken'), }, credentails: 'include' }) -
Check if payment is complete in Django Template
I use django with jinja tempates + frontend. I need to connect QR Code to pay products in the cart. I use official Bank API to create payment, but there is no redirect URL after successed payment, so I need to empty the user's cart after successful payment, but I don't know how. Cart is working on frontend with localStorage and frontend clear cart when user go to payments/success url. But with this method I can't redirect user to this url because QR Code does not support it. How can I check if the payment is successfully done and frontend can clear user's cart? To be clear, Bank API send callback when the payment is completed, but I don't think if its can help with my problem I've seen QR code payment on other sites, they somehow knew my payment was successful and showed me a notification + emptied my cart. -
coding error when adding a category via the admin panel
I have created a database for categories, an error appears when adding: IntegrityError at /admin/goods/categorymodel/add/ ������������: INSERT ������ UPDATE �� �������������� "django_admin_log" ���������������� ���������������������� ���������������� ���������� "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: �������� (user_id)=(5) ���������������������� �� �������������� "auth_user". I was redefining a custom model to my own I have also redefined email or username authorization backends.py: class UserModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserModel.objects.get( Q(username=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: return None except MultipleObjectsReturned: return UserModel.objects.filter(email=username).order_by('id').first() else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None the error occurs when I try to add a category how can I fix the error? Django: 4.2.11 Python: 3.11.8 I found information about redefining authorization, but it didn't help -
i need help django-pytest invalid token error due to fixtures or token generator
fixtures.py, this is where my fixtures are located from django.test import Client from pearmonie.auth.models import User from pearmonie.settings.models import BusinessSettings import pytest @pytest.fixture def BASE_URL(): return "http://localhost:8000" @pytest.fixture def user_sub_info(): return {"email": "a@gmail.com", "fcm_token": ""} @pytest.fixture def user_info(): return { "phone": "+234955443322", "password": "Password.1", } @pytest.fixture def user_info_mail(): return { "phone": "+234955443322", "password": "Password.1", "email": "a@gmail.com", } @pytest.fixture(scope="session", autouse=True) def HTTP_AUTHORIZATION(): return {"HTTP_AUTHORIZATION": ""} @pytest.mark.django_db() def user(user_info, user_sub_info): user = User.objects.create(email=user_sub_info["email"], **user_info) BusinessSettings.objects.create(business_name="my store", user=user) return user @pytest.fixture(scope="session", autouse=True) def client(): return Client() @pytest.fixture def codes(): return { "otp": "000000", "transaction_pin1": "000000", "transaction_pin2": "111111", "pinId": "222222", } auth/tests.py import pytest from pearmonie.auth.models import Otp, User from pearmonie.auth.lambdas import gen_token from utils.fixtures import ( client, HTTP_AUTHORIZATION, BASE_URL, user_info, user_sub_info, codes, user_fixture, user_info_mail ) @pytest.mark.django_db def test_auth( client, BASE_URL, HTTP_AUTHORIZATION, user_fixture, user_info, user_sub_info, user_info_mail, codes ): client.login(**user_info) otp = Otp.objects.create(code=codes["otp"], pinId=codes["pinId"], user=user_fixture, is_verified=True) assert otp.code == codes["otp"] assert otp.is_verified token = gen_token(data = user_info_mail) HTTP_AUTHORIZATION["Authorization"] = token assert HTTP_AUTHORIZATION["Authorization"] == token password_reset_response = client.post( f"{BASE_URL}/auth/password/reset/", { "phone": user_info["phone"], "code": otp.code, "new_password": "HardPass@2022..", "fcm_token": user_sub_info["fcm_token"], }, **HTTP_AUTHORIZATION, content_type="application/json", ) assert password_reset_response.status_code == 200 assert password_reset_response.headers["Authorization"] @pytest.mark.django_db def test_transaction_pin(client, HTTP_AUTHORIZATION, BASE_URL, codes): check_pin_response = client.get( f"{BASE_URL}/auth/pin/check/", **HTTP_AUTHORIZATION, content_type="application/json", ) assert check_pin_response.status_code == 200 create_pin_response … -
beginner to django and need to know how to start off
Basically i started learning Django 2 weeks ago and went to a learning institute for that environment but the teacher for Django isn't sure himself how to explain since he is new to teaching and explaining to other people so i want your guys opinion on how to start off, to get some simple ideas on it. Like i have tried couple of videos on YouTube some tutorials asked CHATGPT couple of questions and "ETC" but none of them are close to that teachers teaching manner so it started to cause some confusion within me on what to find or what to do. -
502 Gateway Error AWS Elastic Beanstalk Django
I am trying to deploy a Django app to Elastic Beanstalk. I used AWS CodePipeline as my CI/CD process. The instance is able to successfully deploy, but when I click on the domain it gives me a 502 gateway error. I suspect this is from the Gunicorn server not running. My environment platform is Python 3.11 Linux 2023. I suspect that the Gunicorn is not running since it cannot find my WSGIPath because of the way my AWS CodePipeline is setup. AWS CodePipeline reads from my repository which has a 'node' folder (containing my frontend) and a 'python' folder (containing my Django app). My 'python/.ebextensions/django.config' contains the following configuration: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myproject.wsgi:application I am guessing that my path is not set correctly since 'myproject' isn't at the root level. And so, I tried the following configuration as well: option_settings: aws:elasticbeanstalk:application:environment: PYTHONPATH: "/opt/python/current/app/python:$PYTHONPATH" DJANGO_SETTINGS_MODULE: myproject.settings aws:elasticbeanstalk:container:python: WSGIPath: myproject.wsgi:application This still gives me a 502 error so I am not sure where to proceed from here. I am confused as to how to properly set my PYTHONPATH so that 'myproject' is found. I cannot find the documentation as to what path the application files are stored. '/opt/python/current/' and '/var/app/current' come up … -
Django Site + Model Translation
I am working on a Django website and I want to have multiple languages for the website. The project has a model called Product. Product has 3 fields ( name, description and info ) that I would like to be translated for all of the Product Objects. I would also like to translate the static parts of the website ( navbar, footer, etc ). What would be the best approach to do that? -
Django 404 using get_queryset()
This is part of my views.py class CommentDetail(generics.RetrieveUpdateDestroyAPIView): def get_queryset(self): event_id = self.kwargs['pk'] comment_id = self.kwargs['comment_pk'] event = Event.objects.get(id=event_id) queryset = Comment.objects.filter(event=event, id=comment_id) return queryset serializer_class = CommentSerializer This is the url: path('<int:pk>/comments/<int:comment_pk>/', views.CommentDetail.as_view(), name='comment-detail'), This is the model: class Comment(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE , related_name='comments_for_event') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) content = models.TextField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author} on {self.event.title} : {self.content}' I'm getting a 404 response for some reason with this endpoint: http://127.0.0.1:8000/groups/2/messages/3/ I tried to add a print statements like this: class CommentDetail(generics.RetrieveUpdateDestroyAPIView): def get_queryset(self): event_id = self.kwargs['pk'] comment_id = self.kwargs['comment_pk'] print('Event ID:', event_id) print('Comment ID:', comment_id) event = Event.objects.get(id=event_id) queryset = Comment.objects.filter(event=event, id=comment_id) print('Queryset:', queryset) return queryset serializer_class = CommentSerializer And I'm getting this output: Event ID: 24 Comment ID: 2 Queryset: <QuerySet [<Comment: myuser on First event : It was amazing !!>]> Not Found: /events/24/comments/2/ which means that the query does find the right object, but something is still wrong because I'm getting 404: HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "No Comment matches the given query." } -
the html template fragment is not updated correctly when working with ajax
I have a Django template that displays a hierarchy of workers using the django mttp library. {% extends "base.html" %} {% load static mptt_tags %} {% block content %} <ul class="root" > <button type="button" id="full-button">Click</button> {% recursetree object_list %} <li> {{node.first_name}} {{node.last_name}} {{node.middle_name}} {% if not node.is_leaf_node %} <ul class="children" id="update"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="{% static "scripts/treeOpen.js" %}"></script> {% endblock content %} When the page is first loaded, only the first two levels of the hierarchy are displayed. The task is to implement lazy loading so that the user clicks on the button and only after that all levels are loaded. I am trying to do this using Ajax $(document).ready(function () { $('#full-button').click(function (event) { console.log("work") openFull(); }); function openFull() { $.ajax({ url: '/tree/', method: 'GET', data: { 'full': 1 }, success: function (data) { console.log('success') $('.root').html(data); }, error: function (xhr, textStatus, errorThrown) { console.log('Error ajax request: ' + errorThrown); } }); } }); and in fact, in the console, I have a success suppression database, that is, ajax works correctly, but the code fragment is not updated correctly. I have such a problem as on the screen … -
django: Unsupported lookup for ForeignKey annotated fields
In a django application, I have a Question model with a custom manager: class QuestionManager(models.Manager): def get_queryset(self): return QuestionQS(self.model).get_queryset() class Question(models.Model): objects = QuestionManager() text = models.CharField(max_length=255) label = models.CharField(max_length=40) and a Choice model which has a foreign key to Question: class Choice(models.Model): question = models.ForeignKey(Question, related_name="choices", on_delete=models.PROTECT) text = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) In my Queryset class I have a custom annotation (annotate_flages method to annotate status) that I expect it to be included in every queryset and another custom annotation (extra_annotations method that annotates is_editable) which I want to include manually: class QuestionQS(models.QuerySet): def get_queryset(self): return self.annotate_flags() def annotate_flags(self): qs = self.annotate( status=Case( When(label__icontains="active", then=Value(1)), When(label__icontains="closed", then=Value(0)), default=Value(0), output_field=IntegerField(), ) ) return qs def extra_annotations(self): one_hour_ago = timezone.now() - datetime.timedelta(hours=1) return self.prefetch_related( Prefetch( "choices", queryset=Choice.objects.annotate( is_editable=Case( When( Q(Q(created_at__gt=one_hour_ago) & Q(question__status=1)), then=True, ), default=False, output_field=BooleanField(), ) ), ) ) My problem is that the default annotations (status) are included in the querysets but I do not have access to them from my custom extra_annotations method. When calling the custom method like: questions = Question.objects.get_queryset().extra_annotations() I get unsupported lookup error: Unsupported lookup 'status' for ForeignKey or join on the field not permitted. -
Django queryset filter on a ManyToMany with custom fields
I have the following Django models Block and Condition that are related to eash other through a custom ManyToMany relationship which has customs fields and a custom DB table: from django.db import models class CustomCondition(models.Model): name = models.CharField("custom condition name") class Meta: db_table = "custom_conditions" def __str__(self) -> str: return self.name class BlockCondition(models.Model): block = models.ForeignKey( "Block", related_name="block_condition_as_block", on_delete=models.CASCADE, ) custom_condition = models.ForeignKey( "CustomCondition", related_name="block_condition_as_custom_condition", on_delete=models.CASCADE, ) choice = models.CharField( "choice", choices=[ ("NO_CONDITION", "No condition"), ("ACTIVATED", "Activated"), ("NOT_ACTIVATED", "Not activated"), ], default="NO_CONDITION", ) class Meta: db_table = "block_conditions" def __str__(self) -> str: return self.custom_condition.name class Block(models.Model): name = models.CharField("name", null=False) block_conditions = models.ManyToManyField( CustomCondition, through="BlockCondition", blank=True, default=None, related_name="blocks_as_block_condition", ) class Meta: db_table = "blocks" Now I want to filter blocks for each condition name and where that condition name is activated: for c in CustomCondition.objects.all(): if c.name: filtered_blocks = Block.objects.filter( block_conditions__custom_condition__name=c.name ) filtered_blocks = filtered_blocks.filter( block_conditions__choice__in=["ACTIVATED", "NO_CONDITION"] ) print(filtered_blocks) But I get the following Django error: django.core.exceptions.FieldError: Unsupported lookup 'custom_condition' for ForeignKey or join on the field not permitted. What am I doing wrong here? -
Django Parler Models + Prepopulated Fields issue
I am trying to use django-parler to translate my models. I am using TranslateableModel and TranslatedFields. This is what my class looks like: class Category(TranslatableModel): translations = TranslatedFields( category_name = models.CharField(_('name'), max_length=50, unique=True), description = models.TextField(_('description'), max_length=255, blank=True), ) slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(_('image'), default='default_category_image.jpg', upload_to='category_photos') But I get this error: **django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'categories.admin.CategoryAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'category_name', which is not a field of 'categories.Category'.** The error is caused because in my model's admin class slug is a prepopulated field: class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('category_name', )} If I put the slug field within the TranslatedFields I get the errors: <class 'categories.admin.CategoryAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not a field of 'categories.Category'. <class 'categories.admin.CategoryAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'category_name', which is not a field of 'categories.Category'. How would I fix this error while still having a slug in my model? -
Access values of manyToMany field before saving
This is my Classroom model: class Classroom(models.Model): name = models.CharField(max_length=120) faculty = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='faculty') students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='students') def save(self, *args, **kwargs): for faculty in self.faculty.all(): if not faculty.user_type == 'faculty': raise ValidationError('Only users with user type as \'faculty\' can be assigned as faculty to a classroom') for student in self.students.all(): if not student.user_type == 'student': raise ValidationError('Only users with user type as \'student\' can be assigned as students to a classroom') return super(Classroom, self).save(*args, **kwargs) def __str__(self): return self.name The user model has a property called user_type which is either faculty or student. In the Classroom model I want to make sure that only users with user_type as faculty can be selected as faculty and similarly for students. On trying to add data using django admin, I receive the following error: ValueError at /admin/classroom/classroom/add/ "<Classroom: Some Class>" needs to have a value for field "id" before this many-to-many relationship can be used. Not sure how to fix it, kindly guide. Thanks in advance. -
How to implement `others` for a Django Model Choices-CharField?
I have a Django model that has several CharFields. A lot of these represent information of the type Item Type 1 Item Type 2 Others The usual way of defining choices for a CharField is models.CharField( max_length=255, choices=ChoiceList.choices, # Defining Choices ) As you would have guessed, this fails to meet my requirements since I cannot pass it anything(Others) apart from the pre-defined choices. I cannot discard the choices parameter since I need the model to have the choices information for each field. This will be used to fetch all legal options for a particular field. I tried using a custom validator function def validate_choice(value, choices): if value == "Others:": print(value, choices) valid_choices = [choice[0] for choice in choices] if not value.startswith("Others:") and value not in valid_choices: raise ValidationError(f"{value} is not a valid choice") (For simplicity, I defined my logic as Either the value is in the Choice List Or it starts with Others: (To indicate that it is a deliberate Other value) And subsequently, I modified the CharField as follows, to use the new Validator Function models.CharField( max_length=255, choices=IPCSections.choices, validators=[partial(validate_choice, choices=ChoiceList.choices)], ) I then noticed that The Choice validation (By Django) happens before the custom validator is called. Which, … -
Django no reloading
I am working on django project, and I need a page switching without reloading, it should be switched between pages smoothly like react. Can I achieve this? I asked ChatGPT, and tried bunch of examples, but it never helped -
How do I make APIs calls between django and Next.js 13 while being on the server side?
I am making a chat app using nextjs 13 and django as backend. But I'm stuck in authentication and other api calls which requires bearer. If I logged in then how can I save the tokens to the server because sometimes I want to make api calls from sever and may this requires bearer. Also if I'm doing it from client If I logged in from client directly to the api it'll save the cookies but If how do I check before requests that if it's expired or any problems Thanks 😊 I made a wrapper using next-auth and calling login function from signIn of next-auth. This saves session in the server but when it's comes to client I would need bearer from server and I have to use until useSession available. -
Daphne Django deployment error 'Exited with status 1/FAILURE' on linux
I have been struggling with this error for hours, when I try to start my daphne.service, shows up this error after executing the command systemctl status daphne.service. I am folliwing this tutorial: https://github.com/mitchtabian/HOWTO-django-channels-daphne . I am using Gunicorn, Nginx and Redis that are working correctly. Error: × daphne.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne.service; disabled; preset: enabled) Active: failed (Result: exit-code) since Sun 2024-04-21 00:37:25 UTC; 31s ago Duration: 676ms Process: 2998 ExecStart=/home/franreinaudo/venv/bin/python /home/franreinaudo/venv/bin/daphne -b 0.0.0.0 -p 8001 core.asgi:application (code=exited, status=1/F> Main PID: 2998 (code=exited, status=1/FAILURE) CPU: 673ms Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Scheduled restart job, restart counter is at 5. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: Stopped daphne.service - WebSocket Daphne Service. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Start request repeated too quickly. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Failed with result 'exit-code'. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: Failed to start daphne.service - WebSocket Daphne Service. daphne.service [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/franreinaudo/test-db ExecStart=/home/franreinaudo/venv/bin/python /home/franreinaudo/venv/bin/daphne -b 0.0.0.0 -p 8001 core.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target settings.py """ Django settings for core project. Generated by 'django-admin startproject' using Django 5.0.1. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see …