Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Usage of OneToOneField in Django
I am very confused about the usage of the OnetoOneField. I thought it was for a case where a given record can only have 1 reference to another table. For example, a Child has 1 Parent. But it seems that Django makes the field that is defined as OneToOne a primary key of your table, meaning it has a Unique constraint. This doesn't make any sense. Any given Child has only 1 Parent. But there might be more than 1 child with the same parent. The the FK to the parent is not going to be unique in the entire Child table I wanted to use OneToOne instead of ForeignKey in order to enforce the one-to-one aspect, as opposed to ForeignKey, which is 1 to Many (any given Child can have more than 1 parent). Am I wrong in my understanding? Should I go back to using ForeignKey and just ensure that my code enforces 1-1? I found these other links which asked the same question, but not sure that I saw a definitive answer Why would someone set primary_key=True on an One to one reationship (OneToOneField)? OneToOneField() vs ForeignKey() in Django -
Empty response from GET method inside post_save
I made a post_save pdf creation method from a django webpage using pdfkit, when I call the from_url method to generate and save a pdf, it doesnt pass the values from the request, so the pdf generated shows the template but no data, when I run the same code outside django (pycharm) it works fine, do request work differently with signals?? @receiver(post_save,sender=CertUsoSuelo) def gener_pdf(sender,instance,*args,**kwargs): try: instance.arch_pdf pass except Pdf_cus.DoesNotExist: cus = instance url = f'http://localhost:8000/p/det_cus/{cus.n_id}/' options = { 'page-size': 'Legal', 'margin-top': '0.25in', 'margin-right': '0.15in', 'margin-bottom': '0.25in', 'margin-left': '0.15in', 'encoding': "UTF-8", } pdfkit.from_url(url, F'{cus.n_id}.pdf', options=options) This is the page called def det_cus_oficial(request,cus_id): cus = CertUsoSuelo.objects.get(n_id=cus_id) normat = cus.zona_ipt zon_alt = [] print('cus',cus) print('normat',normat) if cus.homolog_zon is True: zon_alt = PlanReg.objects.get(CODZONA=str(cus.homolog_zon_alt)) return render(request, 'e_publico/cus_ok.html',{'cus':cus,'normat':normat,'zon_alt':zon_alt}) when page called from pycharm or normal request from webpage when called from post_save -
generate swagger docs for allauth.headless
Im using django for an api, where I use django-allauth and dj-rest-auth for authorization and drf-spectacular for documentation. Recently allauth-headless came out and I want to switch to using headless instead of dj-rest-auth. I've done the basic configuration and I think I did everything correct since the routes work. However, in swagger no routes are generated for the new allauth-headless endpoints. Does anybody know what could be the issue? -
Non consistent post_save GET method
I made a post_save pdf creation method from a django webpage using pdfkit, when I call the from_url method to generate and save a pdf, it doesnt pass the values from the request, so the pdf generated shows the template but no data, when I run the same code outside django (pycharm) it works fine, wheres the error?? @receiver(post_save,sender=CertUsoSuelo) def gener_pdf(sender,instance,*args,**kwargs): try: instance.arch_pdf pass except Pdf_cus.DoesNotExist: cus = instance url = f'http://localhost:8000/p/det_cus/{cus.n_id}/' options = { 'page-size': 'Legal', 'margin-top': '0.25in', 'margin-right': '0.15in', 'margin-bottom': '0.25in', 'margin-left': '0.15in', 'encoding': "UTF-8", } pdfkit.from_url(url, F'{cus.n_id}.pdf', options=options) -
Django template compare templatetag result with variable?
I've got template tag, that returns selected (earlier) location name of the store: @register.simple_tag( takes_context=True) def getSelectedLocation(context): request = context['request'] locationId = request.session.get('locationId') if (locationId): location = Location.objects.get(id = locationId) else: location = Location.objects.first() return location.locationName and in my template I'd like to compare it with actual variables: {%for eq in obj.equipment.all %} {%if getSelectedLocation != 'eq.storageLocation.locationName' %} something {%endif%} {%endfor%} (in general, template tag works ok, ie/ if called like {% getSelectedLocation %} returns correct name). But comparison won't work. Is it possible to do it that way? I think I can't move that logic to a view, as it enumerates over obj object foreign key values... Any suggestions? -
Django auth_views Html template not identifying request.Scheme
Html email template for Django Accounts' auth_view doesn't recognize the protocol, http or https. It works on other manual, non auth_views html email templates. Manual Html email template - request.Scheme works. <p>{{ request.Scheme }}://{{ domain }}{% url 'user_activate' uidb64=uid token=token %}</p> Manual html email template activation link http://192.168.1.1:9000/activate/NDY/c9rpjv-8f514370dc5a858e9575958738e5b34q Auth_view Html email template - request.Scheme doesn't work. <p>{{ request.Scheme }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}</p> Auth_view link in the email ://192.168.1.1:9000/password_reset_link/NDY/c3lpkf-237q81cs574ad1875551161a43c8c8a9 -
Automatically updated created_by/updated_by with Django authenticated user
I have a BaseModel that looks like this: class BaseModel(models.Model): updated_by = models.ForeignKey(UserTable???) updated_at = models.DateTimeField(auto_now=True) created_by = models.TextField(default=0) created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True I want to automatically update the updated_by and created_by fields. But I'm not sure what to put as the target of the ForeignKey. I'm using Django's built in auth_user table, so I don't have a model for that. Also, I'm not clear how I would get the user, since I don't have access to the request object -
How to get the current domain name in Django template?
How to get the current domain name in Django template? Similar to {{domain}} for auth_views. I tried {{ domain }}, {{ site }}, {{ site_name }} according to below documentation. It didnt work. <p class="text-right">&copy; Copyright {% now 'Y' %} {{ site_name }}</p> It can be either IP address 192.168.1.1:8000 or mydomain.com https://docs.djangoproject.com/en/5.0/ref/contrib/sites/ In the syndication framework, the templates for title and description automatically have access to a variable {{ site }}, which is the Site object representing the current site. Also, the hook for providing item URLs will use the domain from the current Site object if you don’t specify a fully-qualified domain. In the authentication framework, django.contrib.auth.views.LoginView passes the current Site name to the template as {{ site_name }}. -
How to manually generate fixtures for Django Polymorphic Models?
I have some Django Polymorphic models: import uuid from django.db import models from polymorphic.models import PolymorphicModel class Fruit(PolymorphicModel): class Meta: abstract = True class Apple(Fruit): variety=models.CharField(max_length=30,primary_key=True) class Grape(Fruit): id=models.UUIDField(primary_key=True, default=uuid.uuid4) colour=models.CharField(max_length=30) Then I can create some fixtures: [ {"model": "test_polymorphic.apple", "pk": "bramley", "fields": {}}, {"model": "test_polymorphic.apple", "pk": "granny smith", "fields": {}}, {"model": "test_polymorphic.grape", "pk": "00000000-0000-4000-8000-000000000000", "fields": { "colour": "red"} }, {"model": "test_polymorphic.grape", "pk": "00000000-0000-4000-8000-000000000001", "fields": { "colour": "green"} } ] and use python -m django loaddata fixture_name to load it into the database which "appears" to be successful. Then if I use: from test_polymorphic import models models.Apple.objects.all() It raises the error: PolymorphicTypeUndefined: The model Apple#bramley does not have a `polymorphic_ctype_id` value defined. If you created models outside polymorphic, e.g. through an import or migration, make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass. Using loaddata bypasses the save() method of the model so the default content-types are not set on the models. I could find the appropriate content types using: from django.contrib.contenttypes.models import ContentType for model_name in ("apple", "grape"): print( model_name, ContentType.objects.get(app_label="test_polymorphic", model=model_name).id, ) Which outputs: apple: 3 grape: 2 and then change the fixture to: [ { "model": "test_polymorphic.apple", "pk": "bramley", "fields": { "polymorphic_ctype_id": … -
I get configure error when i try to launch my site in debug mode
Here's my 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', 'webstore.settings') # webstore is project name 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 PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() Here's the error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried to set environment manually, nothing changed -
How to fix django-filer 404 error on DigitalOcean?
I have a django-cms app running on DigitalOcean. Creating folders and uploading files with filer works perfectly. When downloading the uploaded files I get a 404 Error - for example on this url: https://my_app.ondigitalocean.app/en/media/filer_public/39/d9/39d9ff20-1aa8-48e5-9b8f-113fc71e534b/atest.pdf/ The file is present in the filesystem: Everything is working on the local development server. -
ImportError error for a project running on apache: DLL load failed while importing cv2
Importing opencv before deployment worked fine for my django project, but deploying to apache was an error. Later I wrote a project that only used opencv to read images, but still deployed to apache with errors. [Wed Jul 03 15:44:57.683431 2024] [mpm_winnt:notice] [pid 8204:tid 392] AH00455: Apache/2.4.59 (Win64) mod_wsgi/4.9.2 Python/3.8 configured -- resuming normal operations [Wed Jul 03 15:44:57.683431 2024] [mpm_winnt:notice] [pid 8204:tid 392] AH00456: Apache Lounge VS17 Server built: Apr 4 2024 15:03:17 [Wed Jul 03 15:44:57.683431 2024] [core:notice] [pid 8204:tid 392] AH00094: Command line: 'F:\\bushu\\code\\Apache24\\bin\\httpd.exe -d F:/bushu/code/Apache24 -f F:\\bushu\\code\\Apache24\\conf\\httpd-cv2_text.conf' [Wed Jul 03 15:44:57.693432 2024] [mpm_winnt:notice] [pid 8204:tid 392] AH00418: Parent: Created child process 3884 [Wed Jul 03 15:44:58.058334 2024] [mpm_winnt:notice] [pid 3884:tid 396] AH00354: Child: Starting 64 worker threads. [Wed Jul 03 15:45:53.993438 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] mod_wsgi (pid=3884): Exception occurred processing WSGI script 'F:/bushu/code/code/cv2_text/cv2_text/wsgi.py'. [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] Traceback (most recent call last):\r [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] File "F:\\bushu\\code\\Python38\\lib\\site-packages\\django\\core\\handlers\\exception.py", line 55, in inner\r [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] response = get_response(request)\r [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] File "F:\\bushu\\code\\Python38\\lib\\site-packages\\django\\core\\handlers\\base.py", … -
celery cannot connect to redis in docker:kombu.exceptions.OperationalError: Error -3 connecting to redis:6379. Lookup timed out
I'm building a Websocket service in Django, and I chose celery to push messages。But when I run celery using eventlet on the online server, the following error occurred: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) ^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) ^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/bin/celery.py", line 236, in main return celery(auto_envvar_prefix="CELERY") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/decorators.py", line 33, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( ^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/worker/worker.py", line 93, in __init__ self.app.loader.init_worker() File "/usr/local/lib/python3.12/site-packages/celery/loaders/base.py", line 110, in init_worker self.import_default_modules() File "/usr/local/lib/python3.12/site-packages/celery/loaders/base.py", line 104, in import_default_modules raise response File "/usr/local/lib/python3.12/site-packages/celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/fixups/django.py", line 97, in on_import_modules self.worker_fixup.validate_models() File "/usr/local/lib/python3.12/site-packages/celery/fixups/django.py", line 135, in validate_models self.django_setup() File "/usr/local/lib/python3.12/site-packages/celery/fixups/django.py", line 131, in django_setup django.setup() File "/usr/local/lib/python3.12/site-packages/django/__init__.py", line 24, in setup … -
How to logout with django rest framework?
I have a django rest framework. And I am using version 5.0.6 and djangorestframework==3.14.0 And I try to implement the logout function. What I already tried? I followed several recourses. For example this one: https://stackoverflow.com/questions/58283277/user-logout-by-session-in-django-rest-framework So my logout looks: from django.contrib.auth import logout class LogoutView(APIView): def get(self, request, format=None): logout(request) return Response(status=status.HTTP_200_OK) url: path('logout/',views.LogoutView.as_view(), name='logout'), and part of settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'corsheaders', 'rest_framework.authtoken', 'django_filters', "accounts", "core", 'drf_spectacular', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] So when I loged in and then I choose for logout then the user will be redirected to url: http://127.0.0.1:8000/api-auth/logout/?next=/api/ And I got this message: This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405 And I also tried with post. And I still don't understand which HTTP call you need for logout? Is it get or post? Because in the link I have found it is written with a get option. Question: how to build logout function in django rest framework? -
Not logging to /opt folder in rhel
I have a django application that runs in a docker container. I have a defaults.py file which defines the LOGGING configurations, i have included a file handler in the logging configuration to log to files. ‘file’: {‘class’: ‘logging.FileHandler’, ‘filename’: ‘/opt/tejcli/release/log/temp.log’, ‘formatter’: ‘simple’}, Above piece of code is the file handler that i have included. Unfortunately no logs are being written to the temp.log and not even a file is being created. I have manually created the tejcli/release/log folders. I wrote a python script and put it in home directory and tried writing logs to the same folder and it works. How do i solve this? -
Nested Serializer Doesn't work as expected in pytest
I have this serializer class. class CourseListSerializer(serializers.Serializer): course_slug = serializers.CharField() duration = serializers.FloatField() class CourseAssignSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=255) last_name = serializers.CharField(max_length=255) email = serializers.EmailField(max_length=255) username = serializers.CharField(max_length=255) courses = CourseListSerializer(many=True) class CourseAssignListSerializer(serializers.Serializer): users = CourseAssignSerializer(many=True) This is the viewset action class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "id" authentication_classes = ( ARestAuthentication, BRestAuthentication, ) permission_classes = (permissions.IsAuthenticated | HasAPIKeyWithPermission,) resource_label = "users.User" @action( methods=["put"], detail=False, serializer_class=CourseAssignListSerializer, url_path="assign-course", ) def assign_course(self, request: Request): serializer = self.get_serializer_class()( data=request.data, context={"request": request} ) serializer.is_valid(raise_exception=True) serializer.update(None, serializer.validated_data) return Response(status=status.HTTP_200_OK, data=serializer.data) Above serializers and viewset is working fine when I hit the endpoint using postman. But when I want to put it on the test it giving validation error. I am using the same data when test it on postman and the pytest This is my test function def test_UserViewSet_assign_course(user): request = APIRequestFactory().put( "/api/users/assign-course/", data={ "users":[ { "first_name": "John", "last_name": "doe", "email": "jd@example.com", "username": "jd", "courses": [ { "course_slug": "course_slug", "duration": 30 } ] } ] } force_authenticate(request=request, user=user) action = UserViewSet.as_view( actions={"put": "assign_course"}, serializer_class=CourseAssignListSerializer ) response: Response = action(request=request) print(response.data) assert response.status_code == 200 It giving me {'users': [ErrorDetail(string='This field is required.', code='required')]} But when I use empty data … -
Django: User Profile Update Form Only Showing One User's Data
I'm building an e-commerce website using Django, and I'm having trouble with updating user profiles. I want to display a list of users and provide a way to view and update each user's profile. However, I'm currently only able to see and update the profile of the logged-in user. Here is my current implementation: views.py: def user_list(request): users = CustomUser.objects.all() return render(request, 'useradmin/user_list.html', {'users': users}) @login_required def user_profile_update(request): try: profile = Profile.objects.get(user_name=request.user) except Profile.DoesNotExist: return render(request, 'useradmin/error.html', {'message': 'Profile does not exist.'}) if request.method == "POST": image = request.FILES.get("image") full_name = request.POST.get("full_name") phone = request.POST.get("phone") Address = request.POST.get("Address") diamond_user = request.POST.get("diamond_user") golden_user = request.POST.get("golden_user") if image: profile.image = image profile.full_name = full_name profile.phone = phone profile.Address = Address profile.diamond_user = diamond_user == 'on' # Checkbox values need special handling profile.golden_user = golden_user == 'on' profile.save() messages.success(request, "Profile updated successfully") return redirect("useradmin:user_profile_update") context = { "profile": profile } return render(request, 'useradmin/userprofile.html', context) urls.py: path('user_profile_update/', views.user_profile_update, name='user_profile_update'), path('user_list/', views.user_list, name='user_list'), user_list.html: {% extends 'useradmin/base.html' %} {% block content %} <h1>User List</h1> <ul> {% for user in users %} <li> {{ user.email }} ({{ user.first_name }} {{ user.last_name }}) <a href="{% url 'useradmin:user_profile_update' %}">View/Update</a> </li> {% empty %} <li>No users found.</li> {% endfor … -
Jitsi UI not being updated
I am using Jitsi Meet for video call in one of projects of mine. I cloned the project using link https://github.com/jitsi/jitsi-meet and connected with my react app and is working well.Now I want to change the UI of jitsi meet ,for this purpose I went to documentation ,I followed the steps of i changed into interface.config.js file and title.html file but they are not changed ,so then i build it using "make source-package " it gives me error: p: cannot stat 'build/close3.min.js.map': No such file or directory cp \ node_modules/@jitsi/rnnoise-wasm/dist/rnnoise.wasm \ libs cp -R \ node_modules/@jitsi/excalidraw/dist/excalidraw-assets \ libs/ cp \ react/features/stream-effects/virtual-background/vendor/tflite/.wasm \ libs cp \ react/features/stream-effects/virtual-background/vendor/models/.tflite \ libs cp \ node_modules/lib-jitsi-meet/dist/umd/lib-jitsi-meet.* \ libs cp \ node_modules/@matrix-org/olm/olm.wasm \ libs cp \ node_modules/@tensorflow/tfjs-backend-wasm/dist//*.wasm \ libs ./node_modules/.bin/sass css/main.scss css/all.bundle.css && \ ./node_modules/.bin/cleancss --skip-rebase css/all.bundle.css > css/all.css && \ rm css/all.bundle.css ([ ! -x deploy-local.sh ] || ./deploy-local.sh) cp \ node_modules/@vladmandic/human-models/models/blazeface-front.bin \ node_modules/@vladmandic/human-models/models/blazeface-front.json \ node_modules/@vladmandic/human-models/models/emotion.bin \ node_modules/@vladmandic/human-models/models/emotion.json \ libs mkdir -p source_package/jitsi-meet/css && \ Anyone help me in updating my UI? I wanted to change the UI of jitsi meet and it was unable to be done -
Should I place react files inside of venv directory when making django + react app?
So, I'm new to django and new to react but I thought I'd combine them to make a nice project with a frontend and backend separate. I plan to deploy the frontend on s3 and backend on ec2. Side question but please let me know if this is viable. I'm starting with making the backend template. However, it's recommended that I do my python development inside of a virtual environment, which I understand. Should my file structure be: AppName/ backend/ venv/ - set up django starting here - frontend/ - set up react - Or should I try to put everything inside of the venv. I tried to set it up based on a tutorial and ended up not understanding where anything is (https://www.geeksforgeeks.org/how-to-connect-django-with-reactjs/). Also, it was very unorganized. I'm now restarting and going based solely on documentation, which might be a better approach learning-wise. I think the separating structure is better because I could just upload the entire venv to ec2. Not sure how ec2 set up works but I'll get there eventually. Just wanted some insight to avoid having to restructure everything. Any and all information would be super helpful! -
django FormView modify fields before validation
Is there a proper way to modify the form fields before validating the data on a Class Based FormView. More specifically a CreateView. Is necessary to use Class Based views 'cause I'm throwing in a bunch of custom mixins: class Create(HtmxRequiredMixin, CreatedByMixin, HxFormValidationMixin, BaseMixin, CreateView): template_name = 'administration/form.html' model = Object form_class = Form success_url = reverse_lazy('object-list') hx_retarget = '#CREATE' base = 'object' views_list = ('create',) I used the CreatedByMixin in the DRF viewset for the api rest. it looks like: class CreatedByMixin: def create(self, request, *args, **kwargs): data = request.data.copy() if request.user.is_authenticated: data['created_by'] = request.user.id serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I want a similar mixin for my CreateView but I'm not sure what is the proper method to override. Also, the HxFormValidationMixin already override the form_valid and form_invalid methods. -
Why is my Django app unable to find my URL pattern?
My Django project is run in Docker and I use Celery to handle queuing. When a user submits an audio file the system starts an asynchronous task(that transcribes the audio), continuously checks its progress, and updates the UI once the transcription is complete, with a download button. However I've been getting an error after the transcription completes but before the download button appears. The error indicates that it can't find the view that provides the completed transcript to the user. Here's my code. views.py: def initiate_transcription(request, session_id): file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if request.method == 'GET': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) if request.method == 'POST': try: if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: print(str("VIEW: "+session_id)) task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) return JsonResponse({'status': 'success', 'task_id': task.id}) except Exception as e: return JsonResponse({'status': 'error', 'error': 'No file uploaded'}) return render(request, 'transcribe/transcribe-complete-en.html') def check_task_status(request, session_id, task_id): task_result = AsyncResult(task_id) if task_result.ready(): transcribed_doc = TranscribedDocument.objects.get(id=session_id) return JsonResponse({ 'status': 'completed', 'output_file_url': transcribed_doc.output_file.url }) else: return JsonResponse({'status': 'pending'}) JS: form.addEventListener('submit', function(event) { event.preventDefault(); const transcribeField = document.querySelector('.transcribe-output-lang-select') const errorDiv = document.querySelector('.error-transcribe-div'); transcribeField.style.opacity = '0'; setTimeout(function() { transcribeField.style.display = 'none'; … -
Can I define a field in a django model to return data from another model that meets certain conditions?
I have a model for recipes. I have a model for reviews of those recipes. The recipe's author (chef) can select a specific review as their favorite. I think I've set the constraint up correctly to only allow one favorite review per recipe. Let's assume one favorite review per recipe. I would like to reference the one favorite review using the recipe model. Is this possible? Example template snippet below. {% for recipe in recipes %} <div> <h2>{{ recipe.name }}</h2> <p>{{ recipe.favoriteReview.content }} <small>by {{ recipe.favoriteReview.author }}</small></p> <p>Email the chef: {{ recipe.chef.email }}</p> </div> {% endfor %} Here's an example of the models but I feel like I've approached this from the wrong direction and I've hit a wall. # Models as example class User(AbstractUser): pass class Recipe(models.model): name = models.CharField(max_length=64) instructions = models.TextField(max_length=1000) chef = models.ForeignKey("User", on_delete=models.SET_NULL, related_name="recipes") #favoriteReview = The review with chefsFavorite=True and recipe matches this recipe class Review(models.model): author = models.ForeignKey("User", on_delete=models.SET_NULL, related_name="reviews") rating = models.DecimalField(max_digits=2, decimal_places=2) content = models.TextField(max_length=1000) chefsFavorite = models.Boolean(default="True") recipe = models.ForeignKey("Recipe", on_delete=models.CASCADE, related_name="recipes") class Meta: constraints = [ models.UniqueConstraint(fields=['recipe'], condition=models.Q(chefsFavorite=True), name="chefs_one_favorite_recipe_review" ] -
How to validate Post arguments in Django
I've seen plenty of solutions on how to validate Form field parameters, but I am not using Django templates or implementing the front-end in Django at all. I'm looking purely for server-side backend validation. Let's say I have @api_view(['POST']) def my_func(request): And I want the data to be something like: { "username" : <user>, "password" : <pw>, "age" : <age> } I want to validate that username and password are strings, perhaps with a minimum length requirement. And that age is a number, again, perhaps with other restrictions, such as min/max. Is there a standard way to do this? -
Find periodic task's next execution time in Celery Beat
I am creating PeriodicTasks for opening user an access to the next lesson using this code: task = PeriodicTask.objects.create( interval=enrolment.course.interval, name=f"enrolment_id: {enrolment.id}", task="courses.tasks.next_program", args=json.dumps([enrolment.id]), ) enrolment.task = task enrolment.save() How to get datetime next task will be ran? -
Add 'business context' to all views Django
I've got an app handling a store, with some view of Items that are sold there and some list of Employees there etc. Now, there will be the second (physical) store, and my application is not ready for handling more than one :) So to my models will be added Location model, and foreign keys added to Item and Employee... But my question is how to rebuild views ... So my view that lists all Items, should have added some filter on the top to select location and than filter list based on that selection... and Employee view the same (and all other the same).... So - having that filter there on the top, I should set some global ('session'?) variable, and based on that filter each view? (or add it in url parameters?? or any other way?) Please advise me how to do it an elegant way.