Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rosetta :Nothing to translate! You haven't specified any languages in your settings file
I'm using django-rosetta 0.10.0 with Django, and I have django.po and django.mo files set up correctly. Everything works fine with Django's built-in translation system, and I can successfully use translations. However, when I open Rosetta, it cannot find any translations from my local apps or third-party apps (e.g., rosetta or debug-toolbar). Instead, I see the following message in the Rosetta interface: Nothing to translate! You haven't specified any languages in your settings file, or haven't yet generated a batch of translation catalogs. I’ve already set up my translations in the correct paths and ensured the locale files exist. Here's some additional information about my setup: Rosetta version: 0.10.0 My app structure follows the standard pattern, with locale directories inside each app (e.g., myapp/locale/fa/LC_MESSAGES/django.po). I have defined LANGUAGE_CODE = 'fa-ir' LANGUAGES = ( ('en','English'), ('fa','Persian') ) TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True, in settings.py. Do I need to explicitly define LOCALE_PATHS for each of my apps in settings.py, or should Rosetta automatically detect the locale directories inside the apps? If it’s necessary to specify LOCALE_PATHS, how should I configure it for multiple apps with translations? As I'm a beginner in Django, I would appreciate any … -
Django local server is not running
(myenv) PS E:\Pioneer.Solution\PythonFile\API1> python manage.py runserver Performing system checks... usage: manage.py [-h] [-c] manage.py: error: unrecognized arguments: runserver I'm try to run the local server. it was running earlier but suddenly the same thing stopped. Please help me out in this matter. manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'API1_sub.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHON environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
I can't upload an image to my database at all
I'm using django ninja back end the code works but when I try to send it through an application that I'm making using javascript or even with bash it doesn't work i've tryed `def upload_media(request, nome:str, imgurl: UploadedFile ): usuarios = Media.objects.all() Media.objects.create(nome = nome,imgurl=imgurl) return 1` and class mediaSchema(Schema): nome : str imgurl: UploadedFile `@api.post('tst/', response=mediaSchema) def upload_media2(request, infos : mediaSchema): media = infos.dict() infos = Media(**media) infos.save() return 1` -
Converting Nested Query string requests to a dictionary
I'm experiencing some difficulties converting a querystring data to a well formed dictionary in my view. Here's my view class VendorPayloadLayerView(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): print("Here's the request *****") print(request) payload = request.GET print("Here's the decoded queryDict data") print(payload) data = payload.dict() print("Here's the dictionary") print(data) Here is the request to the view: <rest_framework.request.Request: GET '/turnalerts/api/v2/vendor?%7B%22_vnd%22:%20%7B%22v1%22:%20%7B%22author%22:%20%7B%22id%22:%20%22d2e805b5-4a25-4102-a629-e6b67c798ad6%22,%20%22name%22:%20%22WhatsApp%20Business%20Cloud%20API%22,%20%22request_id%22:%20%22GBV3LTlUEUtfjuMHaDYi%22,%20%22type%22:%20%22SYSTEM%22%7D,%20%22card_uuid%22:%20null,%20%22chat%22:%20%7B%22assigned_to%22:%20%7B%22id%22:%20%2278c711b6-2673-cd8b-0fd9-9a6f03bbcdc5%22,%20%22name%22:%20%22Chima%20Chinda%22,%20%22type%22:%20%22OPERATOR%22%7D,%20%22contact_uuid%22:%20%225ba732cf-d424-4163-9d73-98680d4f53f9%22,%20%22inserted_at%22:%20%222022-05-10T10:15:38.808899Z%22,%20%22owner%22:%20%22%202349039756628%22,%20%22permalink%22:%20%22https://whatsapp-praekelt-cloud.turn.io/app/c/ebd12728-e787-4f29-b938-1059b67f4abd%22,%20%22state%22:%20%22OPEN%22,%20%22state_reason%22:%20%22Re-opened%20by%20inbound%20message.%22,%20%22unread_count%22:%2018,%20%22updated_at%22:%20%222024-12-28T22:17:48.825870Z%22,%20%22uuid%22:%20%22ebd12728-e787-4f29-b938-1059b67f4abd%22%7D,%20%22direction%22:%20%22outbound%22,%20%22faq_uuid%22:%20null,%20%22in_reply_to%22:%20null,%20%22inserted_at%22:%20%222024-12-28T22:17:48.817259Z%22,%20%22labels%22:%20[],%20%22last_status%22:%20null,%20%22last_status_timestamp%22:%20null,%20%22on_fallback_channel%22:%20false,%20%22rendered_content%22:%20null,%20%22uuid%22:%20%227d5fc64e-fd77-325f-8a50-6475e4496775%22%7D%7D,%20%22from%22:%20%2227726968450%22,%20%22id%22:%20%22wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA%27:%20%27%22,%20%22preview_url%22:%20false,%20%22recipient_type%22:%20%22individual%22,%20%22text%22:%20%7B%22body%22:%20%22The%20MomConnect%20ADA%20Symptom%20Checker%20is%20unfortunately%20no%20longer%20available.%20%5C%5Cn%5C%5CnPlease%20reply%20*ASK*%20if%20you%20have%20questions%20or%20need%20help.%22%7D,%20%22timestamp%22:%20%221735424268%22,%20%22to%22:%20%222349039756628%22,%20%22type%22:%20%22text%22%7D'> Here's the decoded queryDict with request.GET <QueryDict: {'{"_vnd": {"v1": {"author": {"id": "d2e805b5-4a25-4102-a629-e6b67c798ad6", "name": "WhatsApp Business Cloud API", "request_id": "GBV3LTlUEUtfjuMHaDYi", "type": "SYSTEM"}, "card_uuid": null, "chat": {"assigned_to": {"id": "78c711b6-2673-cd8b-0fd9-9a6f03bbcdc5", "name": "Chima Chinda", "type": "OPERATOR"}, "contact_uuid": "5ba732cf-d424-4163-9d73-98680d4f53f9", "inserted_at": "2022-05-10T10:15:38.808899Z", "owner": " 2349039756628", "permalink": "https://whatsapp-praekelt-cloud.turn.io/app/c/ebd12728-e787-4f29-b938-1059b67f4abd", "state": "OPEN", "state_reason": "Re-opened by inbound message.", "unread_count": 18, "updated_at": "2024-12-28T22:17:48.825870Z", "uuid": "ebd12728-e787-4f29-b938-1059b67f4abd"}, "direction": "outbound", "faq_uuid": null, "in_reply_to": null, "inserted_at": "2024-12-28T22:17:48.817259Z", "labels": [], "last_status": null, "last_status_timestamp": null, "on_fallback_channel": false, "rendered_content": null, "uuid": "7d5fc64e-fd77-325f-8a50-6475e4496775"}}, "from": "27726968450", "id": "wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA\': \'", "preview_url": false, "recipient_type": "individual", "text": {"body": "The MomConnect ADA Symptom Checker is unfortunately no longer available. \\\\n\\\\nPlease reply *ASK* if you have questions or need help."}, "timestamp": "1735424268", "to": "2349039756628", "type": "text"}': ['']}> Lastly, here's the dictionary as payload.dict() Here's the dictionary {'{"_vnd": {"v1": {"author": {"id": "d2e805b5-4a25-4102-a629-e6b67c798ad6", "name": "WhatsApp Business Cloud API", "request_id": "GBV3LTlUEUtfjuMHaDYi", "type": "SYSTEM"}, "card_uuid": null, "chat": {"assigned_to": {"id": … -
I have a scheduling task and would like to ask everyone for some suggestions
I have a long verbatim transcript, possibly exceeding 50,000 words. I’ve written a program to split each person’s dialogue into BeforeTranscriptSegment. However, I have several issues, which I’ve listed below. Please provide me with some suggestions. Thank you. By default, I use Gemini for translation because its input token count and output token count meet my expectations. The Gemini plan I’m using has a RateLimit, so I want the API request for translation to - trigger only once every 4 seconds. If there is no transcript to translate at the moment, I’d also like the 4-second worker not to trigger. If there are untranslated segments or if an API call returns an error, I want to implement a retry mechanism. Could you suggest a good way to design this task? Thank you. -
There is some basics I do not understand here regarding custom user models
I wanted to delete a user. After a bit of struggeling I ended up like this: views.py the_user = get_user_model() @login_required def del_user(request): email = request.user.email the_user.objects.filter(email=email).delete() messages.warning(request, "bruker slettet.") return redirect("index") But I really do not understand. In the line email = request.user.email. Why is it not email = request.the_user.email There is some basics I do not understand here regarding custom user models. Is this because the user is refering to the AbstractBaseUser? Please excuse me for asking this. -
How to Send List of IDs via multipart/form-data in Django REST Framework
I am working on a Django REST Framework API where I need to send a list of IDs in a multipart/form-data request to create a many-to-many relationship in the database. While everything works perfectly when using JSON as the request format, I face issues when switching to multipart/form-data because the list of IDs doesn't serialize correctly. Here's my serializer: class AddOrUpdateContractSerializer(serializers.ModelSerializer): deputy_agent = serializers.ListField( child=serializers.IntegerField(), required=False, allow_empty=False ) product_type = serializers.ListField( child=serializers.IntegerField(), required=False, allow_empty=False ) referral_type = serializers.ListField( child=serializers.IntegerField(), required=False, allow_empty=False ) customer_id = serializers.IntegerField(required=False) class Meta: model = Contract exclude = ["id", "product", "is_deleted", "state", "customer"] Here's my view class AddContract(APIView): @extend_schema(request=AddOrUpdateContractSerializer, tags=["contract"]) def post(self, request): serialized_data = AddOrUpdateContractSerializer(data=request.data) if serialized_data.is_valid(raise_exception=True): service = ContractService( serialized_data=serialized_data.validated_data, user=request.user ) service.create_contract() return Response( status=status.HTTP_200_OK, data={"detail": "contract created successfully"}, ) And the service for creating the contract: def create_contract(self): items = ["customer_id", "deputy_agent", "product_type", "referral_type"] customer = CustomerSelector.get_customer_by_id( self.serialized_data.get("customer_id", None) ) deputy_agent = self.serialized_data.get("deputy_agent", None) product_type = self.serialized_data.get("product_type", None) referral_type = self.serialized_data.get("referral_type", None) self.remove_unnecessary_items(items) contract = Contract(customer=customer, **self.serialized_data) contract.full_clean() contract.save() if deputy_agent: deputy_agents = DeputyAgent.objects.filter(id__in=deputy_agent) contract.deputy_agent.add(*deputy_agents) if product_type: product_types = ComboBoxsOptions.objects.filter(id__in=product_type) contract.product_type.add(*product_types) if referral_type: referral_types = ComboBoxsOptions.objects.filter(id__in=referral_type) contract.referral_type.add(*referral_types) PROBLEM When sending the data as multipart/form-data, lists like deputy_agent, product_type, and referral_type are received … -
Multipe one-to-many relation between two models
I am stuck on a question that I really need help in so I was creating a route finder and I have created a model of the vehicle with 2 relations start_location and final_location. I want them to be foreign keys as I don't want to have multiple options when selecting start and final location and foreign key defines one-to-many relation that means one location can have multiple vehicle but one vehicle can't be related to multiple location. So my question is will Django Give me error if I create multiple foreign key fields and connect to location that I think (I may be wrong) will create many-to-many relation Thank you for your insight class Destination(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(State, on_delete=models.CASCADE,related_name="destination") country = models.ForeignKey(Country, on_delete=models.CASCADE,related_name="destination") class vehicle(models.Model): start_time = models.CharField(max_length=10) reaching_time = models.CharField(max_length=10) startdestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="startdestinations") subdestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="subdestinations") finaldestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="finaldestinations") fare = models.IntegerField() confirmed = models.BooleanField() distance = models.IntegerField() -
Django is not updating on MacOS
Wanted to start working with Django on MacOS although I am not able to manage to install the last version of Django. Python version is 3.8.8 Installing Django with ´pip install Django´results: Requirement already satisfied: django in ./opt/anaconda3/lib/python3.8/site-packages (4.2.16) Requirement already satisfied: sqlparse>=0.3.1 in ./opt/anaconda3/lib/python3.8/site-packages (from django) (0.5.1) Requirement already satisfied: backports.zoneinfo in ./opt/anaconda3/lib/python3.8/site-packages (from django) (0.2.1) Requirement already satisfied: asgiref<4,>=3.6.0 in ./opt/anaconda3/lib/python3.8/site-packages (from django) (3.8.1) Requirement already satisfied: typing-extensions>=4 in ./opt/anaconda3/lib/python3.8/site-packages (from asgiref<4,>=3.6.0->django) (4.12.2) Trying to update it with ´pip install -U Django´ Requirement already satisfied: Django in ./opt/anaconda3/lib/python3.8/site-packages (4.2.16) Collecting Django Downloading Django-4.2.17-py3-none-any.whl (8.0 MB) 8.0 MB 5.4 MB/s Requirement already satisfied: asgiref<4,>=3.6.0 in ./opt/anaconda3/lib/python3.8/site-packages (from Django) (3.8.1) Requirement already satisfied: sqlparse>=0.3.1 in ./opt/anaconda3/lib/python3.8/site-packages (from Django) (0.5.1) Requirement already satisfied: backports.zoneinfo in ./opt/anaconda3/lib/python3.8/site-packages (from Django) (0.2.1) Requirement already satisfied: typing-extensions>=4 in ./opt/anaconda3/lib/python3.8/site-packages (from asgiref<4,>=3.6.0->Django) (4.12.2) Installing collected packages: Django Attempting uninstall: Django Found existing installation: Django 4.2.16 Uninstalling Django-4.2.16: Successfully uninstalled Django-4.2.16 Successfully installed Django-4.2.17 Trying to force the version with ´python -m pip install Django==5.1.4´ results: ERROR: Could not find a version that satisfies the requirement Django==5.1.4 ERROR: No matching distribution found for Django==5.1.4 -
You don’t have permission to view or edit anything. Django Admin. Web-site for school
I am working on a school website where there is a superadmin who can create other users, but the regular administrators (with the is_staff permission) should not have access to the User model. However, they should have access to other models. Currently, when I log in as a regular administrator (is_staff), I receive the error "You don’t have permission to view or edit anything." On the other hand, everything works fine when I log in as the superadmin (is_staff and is_superuser). Could you help me figure out how to configure the permissions properly, so that the regular administrators don't have access to the User model, but can still work with other models? managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def _create_user(self, username, position, password, is_staff, is_superuser, **extra_fields): if not username: raise ValueError("Вы не ввели username!") if not password: raise ValueError("Вы не ввели пароль!") user = self.model( username=username, position=position, is_active=True, is_staff=is_staff, is_superuser=is_superuser, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, position="Администратор", password=None, **extra_fields): return self._create_user(username, position, password, is_staff=False, is_superuser=False, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): return self._create_user( username, position="Главный администратор", password=password, is_staff=True, is_superuser=True, **extra_fields ) models.py: from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, ) from django.db import models from .managers import … -
How to attach a VPC to a Lambda through fromFunctionAttributes in CDK?
I manage infrastructure through CDK, except for stuff created by zappa for a Django application. Now, I need to connect such Lambda to the RDS cluster: following this guide I need to attach the Lambda to RDS's VPC, assign all subnets and use a SG different than RDS VPC. However, if can retrieve Zappa's Lambda only through Function.fromFunctionAttributes() which doesn't allow then to specify the vpc as we would create the Lambda inside CDK. How do I solve this? -
Why is Django Machina query altered with nonexistent table name
I have a django-machina forum where I can't delete posts because of an error where the delete process apparently looks for a table "forum_conversation_forumpost" This is not a table name in the package. There is a table "forum_conversation_post." I have another test forum installed and I am not getting this error when I delete a post. While I have overridden some sections of the standard machina install in the site with a problem, I still get the error when I revert back to the standard install. I can't figure out where the query is being overridden or why. Error: ProgrammingError at /forum/moderation/queue/31/disapprove/ (1146, "Table 'site.forum_conversation_forumpost' doesn't exist") Request Method: POST Request URL: http://localhost:8000/forum/moderation/queue/31/disapprove/ Django Version: 3.2.23 Exception Type: ProgrammingError Exception Value: (1146, "Table 'site.forum_conversation_forumpost' doesn't exist") Exception Location: /Users/user1/.local/share/virtualenvs/labororg-RtI6P7d4/lib/python3.9/site-packages/MySQLdb/connections.py, line 265, in query Python Executable: /Users/user1/.local/share/virtualenvs/labororg-RtI6P7d4/bin/python Python Version: 3.9.6 Python Path: ['/Users/user1/Documents/labororg', '/Users/user1/.pyenv/versions/3.9.6/lib/python39.zip', '/Users/user1/.pyenv/versions/3.9.6/lib/python3.9', '/Users/user1/.pyenv/versions/3.9.6/lib/python3.9/lib-dynload', '/Users/user1/.local/share/virtualenvs/labororg-RtI6P7d4/lib/python3.9/site-packages'] Server time: Sat, 04 Jan 2025 18:45:46 +0000 Traceback: Environment: Request Method: POST Request URL: http://localhost:8000/forum/moderation/queue/31/disapprove/ Django Version: 3.2.23 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'haystack', 'mptt', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'compressor', 'crispy_forms', 'crispy_bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'captcha', 'machina', 'machina.apps.forum_conversation.forum_attachments', 'machina.apps.forum_conversation.forum_polls', 'machina.apps.forum_feeds', 'machina.apps.forum_moderation', 'machina.apps.forum_search', 'machina.apps.forum_tracking', 'machina.apps.forum_member', 'machina.apps.forum_permission', 'apps.forum', 'apps.forum_conversation', … -
Having issues getting django-simple-captcha to work on my Contact Us page
I'm having trouble getting the captcha to work on my Contact Us page in my website. I've followed the instructions shown in the docs but keep getting errors. Can anyone help? Here's my forms.py: # main/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # For the Captcha from captcha.fields import CaptchaField # For the Contact Us page from django.core.validators import EmailValidator class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.save() return user class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) # phone = forms.CharField(max_length=15) # subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) captcha = CaptchaField() Here is my urls.py: # main/urls.py from django.contrib import admin from django.urls import path, include from main.views import dashboard, register, about, blog app_name = 'main' urlpatterns = [ path('blog/', include('blog.urls')), path('admin/', admin.site.urls), path('projects/', include('projects.urls')), path('captcha/', include('captcha.urls')), ] Here is my views.py: # main/views.py from django.contrib.auth import login as auth_login from django.shortcuts import redirect, render from django.urls import reverse from main.forms import CustomUserCreationForm from captcha.fields import CaptchaField from django.core.mail import EmailMessage from main.forms import ContactForm from django.conf import settings from django.http import HttpResponse # Create … -
How can I use FilteredSelectMultiple widget in a django custom form?
I'm trying to use Django's FilteredSelectMultiple widget in a custom form. This widget is used in the Django admin for fields like Permissions (e.g., http://127.0.0.1:8000/admin/auth/group/add/), where there are two boxes: one for available options and another for selected options. However, when I try to use it, it only renders as a regular multi-select box. That’s my current code: View: class SupervisorUpdateView(modal.BaseModalUpdateView): permission_required = 'management.change_supervisor' template_name = 'management/supervisors/update_supervisor.html' model = models.Supervisor form_class = forms.SupervisorForm success_message = 'Supervisor updated' Form: from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple class SupervisorForm(BSModalModelForm): class Meta: model = models.Supervisor fields = '__all__' labels = {'supervisor': 'Supervisor', 'technicians': 'Technicians'} widgets = { 'supervisor': forms.HiddenInput(), 'technicians': FilteredSelectMultiple('Technicians', is_stacked=False), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['technicians'].queryset = get_agparts_users() Template: {% extends 'core/_modal_form.html' %} {% block header %}Update Supervisor{% endblock header %} {% block button %} <button class="btn btn-primary submit-btn">Update</button> {% endblock button %} Despite this, the widget only renders as a basic multi-select dropdown without the dual-box UI. What am I missing? How can I properly use FilteredSelectMultiple outside of the Django admin? -
CERT_PATH points to the wrong directory even though I set it correctly in my Django project
I'm working on a Django project and trying to configure SSL with the certificate. I have set the CERT_PATH variable like this in my code: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent CERT_PATH = os.path.join(BASE_DIR, "certs", "DigiCertGlobalRootG2.crt.pem") However, when the code runs, it is looking for the certificate in the wrong directory: in core/certs/ instead of certs/. aParent ├── certs │ └── DigiCertGlobalRootCA.crt.pem └── core └── livenews └── services.py -
SimpleJWT: Re-apply Blacklist Token Migration: "Table 'token_blacklist_blacklistedtoken' doesn't exist"
I have, rather sillily, run "python manage.py migrate" when I added Django SimpleJWT's token blacklist functionality to my program. This means whenever I try to generate tokens or use any functionality, I run into the error... (1146, "Table 'token_blacklist_outstandingtoken' doesn't exist") I have tried unapplying and redoing the migrations for "token_blacklist", but I get the same error... python manage.py migrate token_blacklist zero Operations to perform: Unapply all migrations: token_blacklist Running migrations: Rendering model states... DONE Unapplying token_blacklist.0012_alter_outstandingtoken_user... OK Unapplying token_blacklist.0011_linearizes_history... OK Unapplying token_blacklist.0010_fix_migrate_to_bigautofield... OK Unapplying token_blacklist.0008_migrate_to_bigautofield...Traceback (most recent call last): return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fiona\AppData\Roaming\Python\Python312\site-packages\django\db\backends\mysql\base.py", line 76, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\MySQLdb\cursors.py", line 179, in execute res = self._query(mogrified_query) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\MySQLdb\cursors.py", line 330, in _query db.query(q) File "C:\Python312\Lib\site-packages\MySQLdb\connections.py", line 265, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1146, "Table 'token_blacklist_blacklistedtoken' doesn't exist") ... I have tried uninstalling and re-installing the package, djangorestframework-simplejwt, but that also hasn't worked. How do I resolve this? Thank you for any help -
Hi, How to make sure that only tags translated in a given language are displayed on the page translated in that language?
class Insight(Page): .... tags = ClusterTaggableManager(through='insight.InsightTag', blank = True) @register_snippet class InsightTag( TranslatableMixin, TaggedItemBase ): # panels = [FieldPanel("name")] free_tagging = False content_object = ParentalKey( to='insight.Insight', related_name='tagged_items', on_delete=models.CASCADE ) def get_preview_template(self, request, mode_name): return "base.html" def get_preview_context(self, request, mode_name): return {"insighttag": self.body} class Meta(TranslatableMixin.Meta): verbose_name = "insight Tag" verbose_name_plural = "insight Tags" -
Images not displaying in Django webapp deployed on Vercel
I've deploy my app successfully locally, but when deployed on vercel I can't get the images to display. vercel.json: { "builds":[{ "src":"XPense/wsgi.py", "use":"@vercel/python", "config":{ "maxLambdaSize":"15mb", "runtime":"python3.10" } }], "routes":[ { "src":"/(.*)", "dest":"XPense/wsgi.py" } ] } settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' problem child: <div id="profile-picture-selection" class="grid grid-cols-3 gap-4"> {% for image in profile_pictures %} <input type="radio" name="profile_picture" id="{{image}}" value="{{image}}" style="display: none;"> <img src="/media/profile_pictures/{{image}}" alt="{{image}}" class="profile-image-preview rounded-lg cursor-pointer transition transform hover:scale-110" onclick="selectImage('{{image}}', this)"> {% endfor %} </div> The images are located XPense/media/profile_pictures/ with XPense being root. I've tried relocating the images to a public folder and using <img src="/{{image}}"... but noting worked so far, I've tried hard coding an image url and that doesn't work either so yeah... Help please! The website is deployed and you can check it out, if you go to register a new user text I've tried relocating the images to a public folder and using <img src="/{{image}}"... but noting worked so far, I've tried hard coding an image url and that doesn't work either so yeah... Help please! -
django multi-level template extending
I have 3 templates in my code. first one is the base.html, second one is toolbar.html and the third is toolbar_content.html. so I wanted to include the toolbar inside base and use the third inside content blocks by extending base.html. here is an example: my base.html: <div class="d-flex flex-column flex-column-fluid"> {% include 'components/toolbar.html' %} </div my toolbar: <div class="d-flex align-items-center gap-2 gap-lg-3"> {% block toolbar_content %}{% endblock %} </div> and my toolbar content: {% extends 'base.html' %} {% block toolbar_content %} <a href="#" class="btn btn-sm fw-bold btn-primary" data-bs-toggle="modal" data-bs-target="#concept_create">Create New Concept</a> {% endblock %} I both tried to test this example and also I tried to extend the toolbar page instead of base in my toolbar content template but its not working. toolbar is successfully included in base but the content is not showing. could you help me work this out? -
Unable to get form data in database and getting type object 'UserRegister' has no attribute 'USERNAME_FIELD' error
Form.py from django import forms from .models import UserRegister from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError form.py from django import forms from .models import UserRegister from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): username = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'input-group'})) email = forms.EmailField(max_length=70, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'input-group'})) password1 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'input-group', 'id': 'password'})) password2 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'input-group', 'id': 'password'})) class Meta: model = UserRegister fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data.get('email') if UserRegister.objects.filter(email=email).exists(): raise ValidationError('This email address is already in use.') return email def clean_username(self): username = self.cleaned_data.get('username') if UserRegister.objects.filter(username=username).exists(): raise ValidationError('This username is already in use.') return username def clean(self): cleaned_data = super().clean() password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Passwords do not match.") return cleaned_data model.py from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth.hashers import make_password class UserRegister(models.Model): username= models.CharField(max_length=50,unique=True) email = models.EmailField(unique=True,max_length=70) password = models.CharField(max_length=128) class Meta: verbose_name = "User Register" verbose_name_plural = "User Register" def save(self,*args,**kwargs): self.password = make_password(self.password) super(UserRegister,self).save(*args,**kwargs) def __str__(self): return self.username views.py Create your views here. from django.shortcuts import render from django.http import HttpResponseRedirect ,Http404 … -
django.db.utils.OperationalError: no such column: home_student.schoolYear
models.py ''' class Person(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) othernames = models.CharField(max_length=40) dateOfBirth = models.DateField() gender = models.CharField(max_length=20) birthGender = models.CharField(max_length=20) email = models.EmailField(max_length=100) class Student(Person): studentId = models.IntegerField() admissionDate = models.DateField() enrolmentStatus = models.BooleanField() studentExamCode = models.IntegerField() schoolYear = models.IntegerField() ''' forms.py ''' class studentF(ModelForm): class Meta: model = Student fields = ['firstname', 'lastname', 'othernames', 'dateOfBirth', 'gender', 'birthGender', 'email', 'studentId', 'admissionDate', 'enrolmentStatus', 'studentExamCode', 'schoolYear'] ''' I am getting the error in the title, how do I fix it? -
How to reference an inner class or attribute before it is fully defined?
I have a scenario where a class contains an inner class, and I want to reference that inner class (or its attributes) within the outer class. Here’s a concrete example using Django: from django.db import models from django.utils.translation import gettext_lazy as _ class DummyModel(models.Model): class StatusChoices(models.TextChoices): ACTIVE = "active", _("Active") INACTIVE = "inactive", _("Inactive") status = models.CharField( max_length=15, choices=StatusChoices.choices, verbose_name=_("Status"), help_text=_("Current status of the model."), default=StatusChoices.ACTIVE, null=False, blank=False, ) class Meta: verbose_name = _("Dummy Model") verbose_name_plural = _("Dummy Models") constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_status_valid", check=models.Q(status__in=[choice.value for choice in DummyModel.StatusChoices]), ) ] In this case, the constraints list in the Meta class tries to reference DummyModel.StatusChoices. However, at the time this reference is evaluated, DummyModel is not fully defined, leading to an error (neither StatusChoices is accessible in that line). I would like to solve this without significantly altering the structure of the code—StatusChoices must remain defined inside DummyModel. How can I resolve this issue while keeping the inner class and its attributes accessible as intended? -
show chekbox in django marked when instantiating a form
I have the following code: view.py def actualizar_rutina(request, id_rutina): if not request.user.es_entrenador: messages.error(request, 'Usted no tiene permisos para acceder a esta pagina') return redirect('mostrar_rutina') if request.method == 'GET': rutina = get_object_or_404(Rutina, id=id_rutina) rutinaform = RutinaForm(instance=rutina) contexto = { "rutinaform": rutinaform, } return render(request, 'core/crear_rutina.html', contexto) else: return HttpResponse('no se pudo actualizar') form.py class RutinaForm(forms.ModelForm): class Meta: model = Rutina exclude = ('dias_descanso',) dias_entrenamiento = forms.MultipleChoiceField( choices=DIAS_SEMANA, widget=forms.CheckboxSelectMultiple(), required=False ) What happens is that when I instantiate the form that shows the html, the boxes (chekbox) are not checked, they remain blank and what I want is for only those boxes to be checked that are supposed to be instantiated with the instance that the user send Keep in mind that the training day it saves is something like this: training_days=['MON','TUE'] etc and WEEK_DAYS = [('MON', 'Monday'),('TUE', 'Tuesday'), ('WED', 'Wednesday'),('THU', 'Thursday'),('FRI', 'Friday'),('SAT', 'Saturday'),('SUN', 'Sunday'),] How could I achieve that?? thank you What I want is for only those boxes to be checked that are supposed to be instantiated with the instance that the user sends. -
Do I need public S3 bucket for Zappa to work?
I followed this and this tutorials on hosting assets on the bucket generated by Zappa. Following this question I also applied the bucket policy and used ACLs enabled. However, if bucket public access is blocked (default S3 behaviour), then I am not able to access them (for example, I am not able to get CSS for the /dev/admin page). As soon as I make the bucket public, I can retrieve them. Question: is this expected by design? If so, I am concerned about the security implications of having a public S3 bucket. -
Facebook Login - Feature Unavailable
I am trying to implement Facebook login for my application. It was working well in development mode, but when I try to switch to live mode I see this message: Feature Unavailable Facebook Login is currently unavailable for this app, since we are updating additional details for this app. Please try again later. here is the exact error I get I do not have any required actions in developer console. I have searched for an answer, I have already set advanced access to email and public profile, and I got advanced access to other permissions as well. Business verification is complete and I have verified my Business as a tech provider as well. Here is the code that handles the Facebook login (I am using Django framework): def facebook_login(request): facebook_auth_url = "https://www.facebook.com/v21.0/dialog/oauth" if "test" in request.get_full_path(): redirect_uri = request.build_absolute_uri('/test/home/facebook_login/facebook_callback/') redirect_uri = "http://localhost:8000/home/facebook_login/facebook_callback/" else: redirect_uri = request.build_absolute_uri('/home/facebook_login/facebook_callback/') scopes = "pages_show_list,business_management,read_insights,ads_read,pages_read_engagement,ads_management" state = generate_state() request.session['oauth_state'] = state params = { 'client_id': settings.META_APP_ID, 'redirect_uri': redirect_uri, 'scope': scopes, 'response_type': 'code', 'state': state, } auth_url = f"{facebook_auth_url}?{urlencode(params)}" return JsonResponse({'authorization_url': auth_url}) def facebook_callback(request): error = request.GET.get('error') if error == 'access_denied': prefix = 'test/' if os.getenv('PROD') == 'blue' else '' cancel_redirect_url = ( "http://localhost/" + prefix + …