Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translating month and day names in django templates
I would like to print day names and month names in the currently selected language, but django keeps showing them in english even if language selection is working fine. In my template: {{ LANGUAGE_CODE }} {% localize on %} {{ day|date:"l" }} {% endlocalize %} The result is: it Friday I was expecting: it Venerdì If I try to show the date with the default format, using this code: {{ day }} , the date format correctly changes depending on the currently selected language, but the day or month names are still not localized.. So for example if english is selected, I get April 25th 2025, while if italian is selected, I get 25th April 2025. Different date format, but April is always in English. How can i translate day\month names? This is my settings.py: USE_I18N = True USE_L10N = True USE_TZ = True -
model.predict hangs in celery/uwsgi
import numpy as np import tensorflow as tf import tensorflow_hub as hub from apps.common.utils.error_handling import suppress_callable_to_sentry from django.conf import settings from threading import Lock MODEL_PATH = settings.BASE_DIR / "apps/core/utils/nsfw_detector/nsfw.299x299.h5" model = tf.keras.models.load_model(MODEL_PATH, custom_objects={"KerasLayer": hub.KerasLayer}, compile=False) IMAGE_DIM = 299 TOTAL_THRESHOLD = 0.9 INDIVIDUAL_THRESHOLD = 0.7 predict_lock = Lock() @suppress_callable_to_sentry(Exception, return_value=False) def is_nsfw(image): if image.mode == "RGBA": image = image.convert("RGB") image = image.resize((IMAGE_DIM, IMAGE_DIM)) image = np.array(image) / 255.0 image = np.expand_dims(image, axis=0) with predict_lock: preds = model.predict(image)[0] categories = ["drawings", "hentai", "neutral", "porn", "sexy"] probabilities = {cat: float(pred) for cat, pred in zip(categories, preds)} individual_nsfw_prob = max(probabilities["porn"], probabilities["hentai"], probabilities["sexy"]) total_nsfw_prob = probabilities["porn"] + probabilities["hentai"] + probabilities["sexy"] return (individual_nsfw_prob > INDIVIDUAL_THRESHOLD) or (total_nsfw_prob > TOTAL_THRESHOLD) This works from python shell and django shell but stucks at predict part in uwsgi and in celery, anyone got any idea why that might be happening? I put a bunch of breakpoints and the problem is at the prediction itself, in shell it returns in ~100ms but it hangs in uwsgi and celery for 10+ minutes (didn't try for longer as I think it is obvious it won't return) Tried it with and without the lock, same result -
Choosing a storage schema for second-by-second telemetry data (PostgreSQL/Django/Grafana)
I am a software developer with limited experience in database design. I am working on an application that receives telemetry packets every second from equipment to an operations center. Each packet is identified by a fixed SID, which defines the data structure: SID 1 → temperature of equipment 1, 2, 3, 4 SID 2 → voltage of batteries 1, 2, 3 etc. Background: Solution 1 (generic EAV) is already implemented and running in production, but it generates a very large data volume. Rewriting the storage layer would be very costly in both development and maintenance. On the Django side, I can display the latest value of each parameter with nanosecond precision without issues. However, in Grafana, any attempt to build a historical dashboard (e.g., one month of temperature data) consumes massive resources (CPU/memory) to execute queries. Objectives: Keep real-time display of the latest values in Django Enable efficient plotting of time series over several months in Grafana without resource exhaustion 1. Solution 1 (generic EAV, in production) I use a single Django model to store each parameter in an Entity–Attribute–Value table: # models.py class ParameterHK(models.Model): id = models.BigAutoField(primary_key=True, db_index=True) date_hk_reception = models.DateTimeField(auto_now_add=True, db_index=True) sid = models.IntegerField(db_index=True) equipment = models.CharField(max_length=500) label_parameter … -
Forbidden (CSRF cookie not set.): /517775/users/approve-decline/4
@method_decorator(csrf_exempt, name='dispatch') class ApproveOrDeclineUserView(APIView): def patch(self, request, org_code, user_id): try: organization = Organization.objects.get(code=org_code) except Organization.DoesNotExist: return Response({'detail': 'Invalid organization code'}, status=status.HTTP_404_NOT_FOUND) try: user = ClientUser.objects.get(id=user_id, organization=organization) except ClientUser.DoesNotExist: return Response({'detail': 'User not found in this organization'}, status=status.HTTP_404_NOT_FOUND) decision = request.data.get('decision') if decision == 'accept': user.is_active = True user.status = 'Active' user.save() # Email credentials send_mail( subject='Your Account Has Been Approved', message=f"Hello {user.full_name},\n\n" f"Your account has been approved.\n\n" f"Login here: {settings.FRONTEND_URL}{organization.code}/login\n\n" f"Welcome aboard!\n\n" f"Best regards,\n" f"ISapce Team\n\n" f"If you have any questions, feel free to reach out to us via email at samsoncoded@gmail.com", from_email=settings.EMAIL_HOST_USER, recipient_list=[user.email], fail_silently=False, ) return Response({'message': 'User approved and email sent.'}, status=status.HTTP_200_OK) elif decision == 'decline': user.delete() return Response({'message': 'User account declined and deleted.'}, status=status.HTTP_200_OK) return Response({'detail': 'Invalid decision. Must be "accept" or "decline".'}, status=status.HTTP_400_BAD_REQUEST) I am stuck. Can someone please tell me where I am getting it all wrong. All other aspect of the application are working but the moment I try to access the endpoint I get an error 403. -
Is any Library in python for matching Users input (char)? [closed]
I want a library in python that match Users inputs with some words. I need it for jango I try to find some library, but rapid fuzz isn't good for it. I have to give my project too my teacher 1 month later please help me.o -
The page that works in Django design does not work in the admin panel. Other subpages work
I have served our page on Windows server, everything works smoothly, but unfortunately the contact page in the admin panel does not work. I have tried many things and done research, but I could not solve the problem. home/urls.py urls.py view/iletisim Error Page -
How to deal with recurrence dates in Django?
I'm currently developing a Gym website and using django-recurrence to handle recurring training sessions. However, I'm unsure how to work with recurrence dates in a Django QuerySet. Specifically, I want to sort trainings by the next upcoming date and filter trainings by a specific date, for example, to show sessions that occur on a selected day. What's the best way to achieve this using django-recurrence? Should I extract the next occurrence manually and store it in the model, or is there a more efficient approach for filtering and sorting recurring events? Any advice or examples would be greatly appreciated! class Training(TimestampModel): template = models.ForeignKey(TrainingTemplate, on_delete=models.CASCADE, related_name='trainings') start_time = models.TimeField() end_time = models.TimeField() location = models.ForeignKey(TrainingLocation, on_delete=models.PROTECT, related_name='trainings') recurrences = RecurrenceField() members = models.ManyToManyField(Member, through=MemberTraining, related_name='trainings', blank=True) objects = TrainingManager() I have a few ideas on how to handle this, but they all feel a bit over complicated. Add a next_training_date field to the Training model and use a Celery ETA task to update this field every time the training ends. For example, when an admin creates a new training, the next_training_date is calculated on save. Then, a scheduled Celery task (with ETA) is created to update this date again after … -
Date and Time setting in Django
My Django (5) instance adds am and pm to times, but here we are used to 24h clocks. So I wish to change this behavior. In my model I have this field: added_date = models.DateTimeField("date added"), it currently displays as: April 23, 2025, 10:01 a.m. I have tried many things now to change this, including these settings: # Internationalization # https://docs.djangoproject.com/en/5.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = False USE_TZ = True USE_L10N = False DATETIME_FORMAT = "c" I have also tried changing TIME_FORMAT and DATE_FORMAT and various formatting string like "DATE_FORMAT = "%Y-%m-%d" and other things specified here: https://docs.djangoproject.com/en/5.2/ref/settings/#datetime-format, but the only thing that changed anything so far was to do {{ dataset.added_date|time:"H:i" }} in the html. But I'd prefer to just set it in 1 place. How to do that? -
Is there any way to know if an email address exists before creating a user in Django?
I have a RegistrationSerializer in which I crate a user with is_verfied=False. And I wanted to prevent bad intended users to create fake accounts. Even if they can't login due to the email verification step, it would still be a headache if someone just posted a lot of fake users. class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password', 'cpf', 'is_active') extra_kwargs = { 'password': {'write_only': True} } def validate(self, data): return data def create(self, validated_data): user = User.objects.create_user(**validated_data) token = generate_email_verification_token.make_token(user) verification_url = f"{os.environ.get('FRONTEND_URL')}/verify-email?uid={user.id}&token={token}" subject = "..." plain_message = ( "...{verification_url}..." ) html_message = f""" ...{verification_url}... """ send_mail( subject, plain_message, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_message, fail_silently=False, ) return user And I tried to except send_email to delete the created user if there was any problems while trying to send the email, but nothing worked: try: send_mail( subject, plain_message, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_message, fail_silently=False, ) except BadHeaderError: # If mail's Subject is not properly formatted. print('Invalid header found.') User.objects.delete(id=user.id) raise ValidationError except SMTPException as e: # It will catch other errors related to SMTP. User.objects.delete(user=user) print('There was an error sending an email.'+ e) raise ValidationError except: # It will catch All other possible errors. User.objects.delete(user=user) print("Mail Sending Failed!") raise ValidationError So, … -
DRF: How can I validate data vs instance when many=True?
I am using a DRF serializer to update data in bulk. This is how I instantiate the serializer: # Order incoming data and DB instances data = sorted(data, key=lambda x: x["id"]) instances = WorksheetChecklistItem.objects.filter(id__in=(row["id"] for row in data)).order_by("id") # Serialize and save serializer = update.WorksheetChecklistItemSerializer(instance=instances, data=data, many=True) if not serializer.is_valid(): # ... more logic ... And this is the serializer: class WorksheetChecklistItemSerializer(serializers.ModelSerializer): class Meta: model = WorksheetChecklistItem fields = ["id", "value", "outcome"] def update(self, instance, validated_data): instance.outcome = validated_data.get("outcome", instance.outcome) instance.value = validated_data.get("value", instance.value) instance.done = instance.outcome is not None instance.save() return instance def validate(self, data): """Custom validation for the checklist item.""" instance = self.instance if not instance: raise serializers.ValidationError("Instance is required for validation") # Only update is allowed # Validate "must" condition if instance.must and not data.get("done"): raise serializers.ValidationError(f"Checklist item {instance.id} is required but not completed.") # Validate that value is a number if instance.check_type == WorksheetChecklistItem.CheckType.VALUE and not isinstance(data.get("value"), (int, float)): raise serializers.ValidationError(f"Checklist item {instance.id} requires a numeric value.") return data So I'm relying on the default ListSerializer class that is triggered when the serializer is instantiated with the many=True argument. My validation fails because the validate method does not have an "instance" argument like the update method … -
Django: querying two ManyToMany fields on the same model
Given the following models: class Color(models.Model): name = models.CharField() class Child(models.Model): fave_colors = models.ManyToManyField(Color) tshirt_colors = models.ManyToManyField(Color) How would I construct a query to find children who own t-shirts that are their favorite colors? i.e. lucky_kids = Child.objects.filter( fave_colors__exact=tshirt_colors ) # obvious but not valid query -
Using pytest and mongoengine, data is created in the main database instead of a test one
I've installed these packages: python -m pip install pytest pytest-django And created a fixture: # core/services/tests/fixtures/checkout.py import pytest from bson import ObjectId from datetime import datetime from core.models.src.checkout import Checkout @pytest.fixture(scope="session") def checkout(mongo_db): checkout = Checkout( user_id=59, amount=35_641, ) checkout.save() return checkout and imported it in the conftest.py in the same directory: # core/service/tests/conftest.py from core.service.tests.fixtures.checkout import * Here's how I connect to the test database: # conftest.py import pytest from mongoengine import connect, disconnect, connection @pytest.fixture(scope="session", autouse=True) def mongo_db(): connect( db="db", name="testdb", alias="test_db", host="mongodb://localhost:27017/", serverSelectionTimeoutMS=5000, ) connection._connections.clear() yield disconnect() And this is my actual test: import json import pytest from core.service.checkout import a_function def test_a_function(checkout): assert checkout.value is False response = a_function(id=checkout.id, value=True) assert response.status_code == 200 response_data = json.loads(response.content.decode("UTF-8")) assert response_data.get("success", None) is True checkout.reload() assert checkout.value is True But every time I run pytest, a new record is created in the main database. How can I fix this to use a test database? -
Stripe subscription intent error for 3 days
I have problem with Stripe Subscription integration into flutter (Back-end is Django) inside Views.py i have class CreateSubscriptionIntentView(APIView): permission_classes = [IsAuthenticated] def post(self, request): try: stripe.api_key = settings.STRIPE_SECRET_KEY price_id = request.data.get('priceId') if not price_id: return Response({'error': 'priceId is required'}, status=400) # Get or create user profile profile = request.user.profile # Create customer if missing if not profile.stripe_customer_id: customer = stripe.Customer.create( email=request.user.email, metadata={'django_user_id': request.user.id} ) profile.stripe_customer_id = customer.id profile.save() # Create subscription with retry logic subscription = None invoice = None payment_intent = None for _ in range(3): # Retry up to 3 times try: # 1. Create subscription subscription = stripe.Subscription.create( customer=profile.stripe_customer_id, items=[{'price': price_id}], payment_behavior='default_incomplete', payment_settings={ 'payment_method_types': ['card'], 'save_default_payment_method': 'on_subscription' } ) # 2. Retrieve invoice with expansion invoice = stripe.Invoice.retrieve( subscription.latest_invoice, expand=['payment_intent'] ) if invoice.payment_intent: payment_intent = invoice.payment_intent break except stripe.error.StripeError: time.sleep(1) # Wait 1 second before retry continue if not payment_intent: return Response({'error': 'Payment intent not available after creation'}, status=500) # Save subscription ID profile.stripe_subscription_id = subscription.id profile.save() return Response({ 'clientSecret': payment_intent.client_secret, 'subscriptionId': subscription.id }) except Exception as e: return Response({'error': str(e)}, status=500) Inside Flutter page called final_payment_screen.dart i have Future<void> _initSheet() async { setState(() { _loading = true; _error = null; }); try { // Pick your … -
Function to Password recovery email only works on localhost in django
I have the code below that is responsible for sending a password recovery email to the user who made the request. However, it only works on localhost if they access nginx using my machine's IP or access the VPS with the application deployment does not work. the link is generated normally regardless of the url, however the email is only generated outside of localhost if I remove the reset link I need the email to be sent regardless of the host, follow the code: def password_reset_request(request): if request.method == "POST": form = PasswordResetRequestForm(request.POST) if form.is_valid(): cpf = form.cleaned_data['cpf'] # Get user by CPF user = CustomUser.objects.get(cpf=cpf) # Adjust field as needed # Generate password reset token token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) # Create password reset link reset_link = request.build_absolute_uri( reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token}) ) # Prepare email theme = 'Reset Password' email_template = 'auth/recovery_email.html' email_context = { 'user': user, 'reset_link': reset_link, 'valid_hours': 24 # Token validity in hours } email_content = render_to_string(email_template, email_context) try: # Send email send_mail( theme, '', # Plain text version (empty as we're using HTML) settings.DEFAULT_FROM_EMAIL, [user.email], html_message=email_content, fail_silently=False, ) print("Email sent successfully!") except Exception as e: print(f"Email sending failed: {e}") print(f"Email sending failed: … -
How to re-enter fullscreen after first exit and auto-submit form on second exit (anti-cheating JavaScript logic)
I'm building an online exam system in Django and want to implement anti-cheating logic using JavaScript fullscreen detection. Goal: On first exit from fullscreen: ➤ Show a warning: "Warning: Exited fullscreen mode. (1/2)" ➤ Automatically re-enter fullscreen after a short delay. On second exit from fullscreen (or other cheat triggers): ➤ Immediately submit the exam form. No second warning. What I’ve done: I’m using JavaScript to detect: fullscreenchange visibilitychange (tab switch) blur (focus lost) Here’s the relevant JavaScript: let cheatCount = 0; const maxAllowedCheats = 2; let submitted = false; let lastCheatTime = 0; const CHEAT_COOLDOWN = 1500; let warnedFullscreenOnce = false; function handleCheatAttempt(reason, force = false) { const now = Date.now(); if (!force && now - lastCheatTime < CHEAT_COOLDOWN) return; lastCheatTime = now; cheatCount++; if (cheatCount < maxAllowedCheats) { alert(`Warning: ${reason}. (${cheatCount}/${maxAllowedCheats})`); // Try to re-enter fullscreen only on first "Exited fullscreen mode" if (reason === "Exited fullscreen mode" && !warnedFullscreenOnce) { warnedFullscreenOnce = true; setTimeout(() => goFullscreen(), 500); } } if (cheatCount >= maxAllowedCheats && !submitted) { submitted = true; alert("Cheating detected. Submitting your test."); document.getElementById("exam-form").submit(); } } function checkFullscreen() { const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; if (!isFullscreen) { if (!warnedFullscreenOnce) { handleCheatAttempt("Exited … -
Any way to improve my fitness services app?
I'm still a somewhat beginner when it comes to coding (I have been slowly learning it in my own time and think I've gotten pretty good) but would greatly appreciate any feedback on my form functionality specifically, as that's what I have been trying to get down recently. I'd love to know if there is anything I can do to improve my code at all from optimisation to professionalism. Thanks. forms.py class ConsultationForm(forms.ModelForm): class Meta: model = Consultation fields = ['address_line_1', 'address_line_2', 'postcode', 'description', 'date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), 'description': forms.Textarea(attrs={'rows': 4}) } class SessionForm(forms.ModelForm): consultation = forms.ModelChoiceField( queryset=Consultation.objects.all(), empty_label="Select a consultation", help_text="Please select a previous consultation", required=True ) class Meta: model = Session fields = ['consultation', 'workout', 'date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user: self.fields['consultation'].queryset = Consultation.objects.filter(user=user) class CheckInForm(forms.ModelForm): session = forms.ModelChoiceField( queryset=Session.objects.all(), empty_label="Select an session", help_text="Please select a previous session", required=True ) class Meta: model = CheckIn fields = ['session', 'date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user: self.fields['session'].queryset = Session.objects.filter(user=user) views.py @login_required def booking_form(request, service_type): SERVICE_MAP = { 'consultation': {'form': … -
Preserving Document Format in the Frontend using React JS
I am working on a project which is about document manipulation using AI. The frontend is build on React Js and the backend is built on Django. But the problem that i am facing is: When I upload the document and manipulate it in the frontend and then save it using any frontend library, the format is not preserved. The uploading document contains images and tables, but the downloaded document always downloads it as plain text. I changed my approach and created html blob for the file and saved it in docx extensions, but since its mainly masquerading, it corrupts the images that are in the document BUT preserves the format. IF anyone knows the solution to this, please do help. I tried creating its html blob, change the mime type and save it as docx. But it corrupted the images of the document. -
Android OpenAPI generator client can not connect to Django Rest API made with rest framework
I just generated a android client for an schema of a API built by myself and enabled internet connection permission with: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> I copied the code, changed the package name and URLS for api, so that in my client.api.PhotosApi class for example I have: public class PhotosApi { String basePath = "http://10.0.2.2:8000"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { getInvoker().addDefaultHeader(key, value); } And all the code is autgenerated by https://openapi-generator.tech/. This IP and port corresponds to the IP of my local computer because the code is running on an android emulator. Well, when I use the API to retrieve photos for example, I get: 2025-04-22 11:26:50.039 20890-20890 AndroidRuntime es.example.rallyfotografico E FATAL EXCEPTION: main Process: es.example.rallyfotografico, PID: 20890 java.lang.IllegalStateException: Could not execute method for android:onClick at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:472) at android.view.View.performClick(View.java:7448) at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) at android.view.View.performClickInternal(View.java:7425) at android.view.View.access$3600(View.java:810) at android.view.View$PerformClick.run(View.java:28305) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:467) at android.view.View.performClick(View.java:7448) at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) at android.view.View.performClickInternal(View.java:7425) at android.view.View.access$3600(View.java:810) at android.view.View$PerformClick.run(View.java:28305) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.RuntimeException: java.util.concurrent.TimeoutException at es.example.rallyfotografico.LaunchActivity.test(LaunchActivity.java:66) at … -
django celery: object has no attribute 'delay_on_commit'
django 4.2 with celery 5.5.1 launching a celery task from a django view sometimes causes "'generate_report' object has no attribute 'delay_on_commit'" # tasks.py from celery import shared_task @shared_task def generate_report(data): # Code to generate report ... # django view def testview(request): from tasks import generate_report generate_report.delay_on_commit("mytestdata") return render(request, "simple_page.html") This happens on some deployments, but not on all. And when it happens, a server (webapp) reboot solves the issue. Moving the "generate_report" import to the top of the file also did not help. Note: Code is deployed on pythonanywhere.com with several celery workers running in "always on" tasks. -
Django Broken Pipe Error during Form Submission
I am developing an online crime reporting system using django. I have a page which contains a form that helps register the incident. the form is as : {%extends 'BaseTemplate.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {%load static tailwind_tags%} {%tailwind_css%} </head> <body> {% block main_content %} <form action="" method="post" id="register_form" class="max-w-4xl mx-auto bg-white shadow-[0_2px_13px_-6px_rgba(0,0,0,0.4)] sm:p-8 p-6 rounded-md transform duration-500" enctype="multipart/form-data"> {% csrf_token %} <div class="grid sm:grid-cols-2 gap-6 transform duration-500"> <div> <input type="hidden" name="register_crime_form" id="register_crime_form" value="register_crime_form"> <label class="text-gray-900 text-sm mb-2 block">What Type of crime did you witness/face?</label> <select name="crime_type" type="text" required class=" focus:bg-transparent w-full text-sm text-gray-800 px-4 py-2.5 rounded border focus:ring-0 focus:border-black outline-none transition-all" placeholder="Enter name"> <option value="" disabled selected value>-- choose an option --</option> <option value="ANTI_SOCIAL">Antisocial Behaviour</option> <option value="BURGLARY">Burglary</option> <option value="CRIMINAL_DAMAGE">Criminal Damage</option> <option value="CYBER_CRIME">CyberCrime</option> <option value="FRAUD">Fraud</option> <option value="HATE_CRIME">Hate Crime</option> <option value="ROBBERY">Robbery</option> <option value="RURAL_CRIME">Rural Crime</option> <option value="SPIKING">Spiking</option> <option value="STACKING">Stacking</option> </select> </div> <div> <label class="text-gray-900 text-sm mb-2 block">Date of the Crime</label> <input name="crime_date" type="date" required class=" focus:bg-transparent w-full text-sm text-gray-800 px-4 py-2.5 rounded border focus:ring-0 focus:border-black outline-none transition-all" /> </div> <div> <label class="text-gray-900 text-sm mb-2 block">Time of the Crime</label> <input name="crime_time" type="time" required class=" focus:bg-transparent w-full text-sm text-gray-800 px-4 py-2.5 rounded border focus:ring-0 focus:border-black outline-none … -
I want to know if there is a method to show other users' info in Django [closed]
Im new in Django and i find a problem about the admin pages. i have a html page and i want to show all users' info like name and permission. Andi want to add a button that can delete this user or jump to this user's info page in django admin page. how can i do it? -
Django javascript functions running arbitrarily
I have 2 functions in my views.py and javascript. running at intervals of 1 and 10 sec respectively. They share a cumulative df. Although I'm using Lock(), the functions seem to give random outputs. -
Problem in logging out in Postman while sending POST Request through API
I am using POSTMAN to send API Requests.I have been logged in through API and got a token. When I try to log out using that particular token it display output as "not logged in" This is the screenshot of my token I got in Postman: and this is the output I get while sending POST request to log out: I am trying to logout with the same token I logged in with in Django application. Here is my code in Django: def logout_user(request): if request.user.is_authenticated: request.user.auth_token.delete() return Response({'message': 'Successfully logged out'}) else: return Response({'error': 'Not logged in'}, status=status.HTTP_401_UNAUTHORIZED -
Should I add the output.css file of tailwindcss into .gitingnore file?
I am working on a django project and trying tailwindcss for the first time with it. Although i integrated both of them successfully. But i have a doubt should i add the output.css file into the .gitignore file as this file is rebuilding whenenver i am doing some changed inside my project. So will it be okay if i add this 'output.css' file into the .gitignore file. Currently this output.css files resides inside the static directory. -
Django view: Can't import module from another directory
I have a django project structure like so: core_project/ App1/ Views.py Models.py .. App2/ Views.py Models.py .. Python_code/ Object_refresh/ __init.py__ refresh.py config.py Inside views.py I have a view called "run_refresh" that will run refesh.py from python_code. But I run into a problem trying to reference other .py files inside Python_code. In the view I use: from python_code import * But it isn't able to see main.py. If I type out "from python_code import main" it works but then it can't find env_config.py. This is what I have in my view.py: from core_project.python_code.object_refresh import * .. And this is the error: newfeature = asyncio.run(object_refresh.refresh(rows_to_refresh, schema, 'tbl_name')) print(newfeature) Error: newfeature = asyncio.run(object_refresh.refresh(rows_to_refresh, schema, 'tbl_name')) ^^^^^^^^^^^^^^^^^^^ AttributeError: module 'core_project.python_code.object_refresh' has no attribute 'refresh' Maybe i need to setup my init.py a certain way but i'm not sure. Any help is appreciated.