Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to solve error (1241, 'Operand should contain 1 column(s)') when using Django with MySQL
I'm Using MySQL database with my Django application, but when i try to save the model it returns this error : (1241, 'Operand should contain 1 column(s)') Here is my code : Model class Proposal(models.Model): """ Model for Proposals """ status_choices = ( ("pending", _("Pending")), ("accepted", _("Accepted")), ("declined", _("Declined")), ) related_request = models.ForeignKey(Request, on_delete=models.CASCADE, verbose_name=_('Request'), help_text=_('Request')) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name=_('User'), help_text=_('User')) price = models.IntegerField(verbose_name=_('Price'), help_text=_('Price')) notes = models.TextField(verbose_name=_('Notes'), help_text=_('Notes'), null=True, blank=True) estimated_time = models.CharField(max_length=100, verbose_name=_('Estimated time'), help_text=_('Estimated time')) date_created = models.DateTimeField(verbose_name=_('Date created'), help_text=_('Date created'), auto_now_add=True) date_modified = models.DateTimeField(verbose_name=_('Date modified'), help_text=_('Date modified'), auto_now=True) status = models.CharField(max_length=100, verbose_name=_('Proposal status'), help_text=_('Proposal status'), choices=status_choices, default="pending") checked_by_admin = models.BooleanField(verbose_name=_("Checked by admins"), default=False, help_text=_( "Check this only if you are an admin and toke actions with this request")) file = models.FileField(upload_to="proposals_files", help_text='File attached with the proposal', verbose_name='Attached file', null=True, ) client_notes = models.TextField(verbose_name=_('Client Notes'), help_text=_('Client Notes'), null=True, blank=True) def __str__(self): return self.related_request.type + ' ' + self.related_request.finishing_type class Meta: verbose_name = _('Proposal') verbose_name_plural = _('Proposals') it returns the error in both stations : 1- when I try to save, edit, or create from the Admin interface. 2- when I try to save or edit using Django rest framework view. DRF View @api_view(["POST"]) @permission_classes([IsAuthenticated]) def react_to_proposal(request): … -
I am using crispy form to render the form. In my form there is one multiple checkbox field.I want to show some options as selected.How to do that
I am using django-crispy-forms. One of the form field is multiple choice checkbox. In this checkbox i wanted to show some options as checked. How to do that. -
Django query (contains, startswith, etc..) always case-insensitive
Whenever I use Django's query functions like name__contains or name__startswith it is always case-insensitive, as if they were name__icontains or name__istartswith. How could I force case-sensitivity? I'm using Django 4.1.1 and Python 3.10 -
Why an ajax query is called twice
I try to update database using ajax query I get row table id on click to send to view for updating data but as my ajax is called twice (why?), second call reverse first call <table> <tbody> {% for dcf in datacorrections %} <tr> <td data-toggle="tooltip" data-placement="top" title="">{{ dcf.ide }}</td> <td data-toggle="tooltip" data-placement="top" title="" id="{{ dcf.ide }}">{{ dcf.deativated }}</td> </tr> {% endfor %} </tbody> </table> $('body').on('click','td', function() { var _id = $(this).attr('id'); $.ajax({ type: 'POST', url: "{% url 'monitoring:deactivate_dcf' %}", data: { "id" : _id }, dataType: 'html', success: function (response) { obj = JSON.parse(response); }, }); }); @login_required @csrf_exempt def deactivate_dcf(request): if request.is_ajax() and request.method == "POST": datacorrection_id = request.POST.get("id") if DataCorrection.objects.filter(ide = datacorrection_id).exists(): if DataCorrection.objects.get(ide = datacorrection_id).deativated == False: DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=True) else: DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=False) return JsonResponse({"response": "success",}, status=200) else: return JsonResponse({"response": "failed","exist":"datacorrection not exist"}, status=404) return JsonResponse({"response":"not_ajax"}, status=200) -
How to get how many seconds are left before session expiration django
In Django I can set the expiration time for the session request.session.set_expiry(300) and after 5 minutes the session ends. When a user makes a request for a view, I want to be able to check how many seconds are left in the current session before it expires. The following method request.session.get_expiry_date() is returning 300 instead of the seconds left. Is there anyway to get the seconds left in a session before it expires? -
View dropdown by condition Django Model Forms
I have a model of categories with a title class Category(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) title = models.CharField(max_length = 20) I have another model with many to many field of categories class Product(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) Category = models.ManyToManyField(Category) title = models.CharField(max_length = 20) Both my models got a user foreign key. I created a product form using django modelforms. class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' The issue I face is that I get the category of another user also. how to show only categories of that particular user? so that one user won't see another user's category -
My API works fine when tested with Postman or ThunderClient but when i integrated swagger it's not showing any parameters
Image 1 showing no parameters in swagger UI Image 2 showing registration endpoint upon registration Image 3 showing login endpoint upon login Below are my code snippets in views.py from rest_framework.response import Response from rest_framework import status from rest_framework.generics import GenericAPIView from rest_framework.views import APIView from account.serializers import ( SendPasswordResetEmailSerializer, UserChangePasswordSerializer, UserLoginSerializer, UserPasswordResetSerializer, UserProfileSerializer, UserRegistrationSerializer, ) from django.contrib.auth import authenticate from account.renderers import UserRenderer from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import IsAuthenticated from drf_yasg.utils import swagger_auto_schema Generate Token Manually def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { "refresh": str(refresh), "access": str(refresh.access_token), } class UserRegistrationView(GenericAPIView): renderer_classes = [UserRenderer] def post(self, request, format=None): serializer = UserRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token = get_tokens_for_user(user) return Response( {"token": token, "msg": "Registration Successful"}, status=status.HTTP_201_CREATED, ) UserLoginView class UserLoginView(APIView): renderer_classes = [UserRenderer] def post(self, request, format=None): serializer = UserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data.get("email") password = serializer.data.get("password") user = authenticate(email=email, password=password) UserLoginView cont'd if user is not None: token = get_tokens_for_user(user) return Response( {"token": token, "msg": "Login Success"}, status=status.HTTP_200_OK ) else: return Response( {"errors": {"non_field_errors": ["Email or Password is not Valid"]}}, status=status.HTTP_404_NOT_FOUND, ) UserProfileView class UserProfileView(APIView): renderer_classes = [UserRenderer] permission_classes = [IsAuthenticated] def get(self, request, format=None): serializer = UserProfileSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) #UserChangePasswordView class UserChangePasswordView(APIView): renderer_classes = [UserRenderer] … -
Django Razorpay: Not able to get the post data from the razorpay form
Django razorpar: Error getting the POST data. After making the razorpay payment in test session. I'm Find an error getting the POST data from the url. I am not able to figure out what the problem is My views @csrf_exempt def callback(request): if request.method == "POST": try: payment_id = request.POST.get('razorpay_payment_id', '') razorpay_order_id = request.POST.get('razorpay_order_id', '') signature = request.POST.get('razorpay_signature', '') course_id = request.POST.get("course_id", '') amount = request.POST.get('amount', '') ... except: messages.error(request, 'Error getting the post data') return redirect('home-page') else: messages.error(request, 'other than post request is made') return redirect('home-page') My payment page <form method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { key: "{{razorpay_key}}", amount: "{{amount}}", currency: "INR", name: "Buy", description: "Test Transaction", image: "https://imgur.com/NOWiBu9", order_id: "{{provider_order_id}}", callback_url: "{{callback_url}}", redirect: true, prefill: { "name": "aa", "email": "aa@gmail.com", "contact": "9898989898" }, notes: { "course_id": "{{course_id}}", "address": "Razorpay Corporate Office", "amount": "{{amount}}" }, theme: { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.open(); </script> <input type="hidden" custom="Hidden Element" name="hidden"> </form> The payments are working fine. The only error is i am not able to get the data. It would be helpful if anyone know whats wrong. -
no data is retrieved after query
I am trying to fetch specific records from the database table based on user input but getting no data in the objj. Can anybody specify the error. objects.all() is also returing no data. views.py from django.views.generic import TemplateView, ListView, DetailView from ssr.models import dinucleotides from ssr.forms import InputForm # Create your views here. def homepage(request): return render(request,'index.html') def searchpage(request): if(request.method == 'POST'): fm=InputForm(request.POST) if fm.is_valid(): print('form validated') Motiff = fm.cleaned_data['Motiff'] obj1=dinucleotides.objects.filter( SSRtype=Motiff) objj={'obj1':obj1 } return render(request,'result.html', objj) else: fm=InputForm() return render(request,'search.html',{'form':fm})``` models.py ``` from django.db import models # Create your models here. class dinucleotides(models.Model): ID = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. Chromosome = models.CharField(db_column='Chromosome', max_length=100, blank=True, null=True) # Field name made lowercase. SSRtype = models.CharField(db_column='SSRtype', max_length=100, blank=True, null=True) # Field name made lowercase. Sequence = models.CharField(db_column='SSRsequence', max_length=10000, blank=True, null=True) # Field name made lowercase. Size = models.IntegerField(db_column='Size', blank=True, null=True) # Field name made lowercase. Start = models.IntegerField(db_column='Start', blank=True, null=True) # Field name made lowercase. End = models.IntegerField(db_column='End', blank=True, null=True) # Field name made lowercase. def __str__(self): return self.dinucleotides``` -
Djoser Password reset confirmation
I have checked many resources,till now I couldn not understand how to setup password reset confirm.How do I do that?I can send email in /u/admin/register/reset_password/ endpoint but when it directs I don't know the process.It said no password reset confirm url,I set it in djoser settings but I got below error.I would like to know whole password reset process in djoser from start. after i click post below error shows up. -
Runserver not working while use_tz = true in Python - Django
I can't runserver or use any commands in terminal after I connect my model with MySQL When I try to change USE_TZ = False in settings.py It's work for me, But I still can't use DateTimeField or DateField in models.py . And I saw other people in Youtube can use models without configure USE_TZ = False and why I can't do that? $ python manage.py makemigrations Traceback (most recent call last): File "C:\Users\UserName\Desktop\MyWeb\MyWeb\manage.py", line 22, in <module> main() File "C:\Users\UserName\Desktop\MyWeb\MyWeb\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\commands\makemigrations.py", line 119, in handle loader.check_consistent_history(connection) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\migrations\loader.py", line 313, in check_consistent_history applied = recorder.applied_migrations() File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\migrations\recorder.py", line 82, in applied_migrations return { File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\query.py", line 320, in __iter__ self._fetch_all() File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\query.py", line 87, in __iter__ for row in compiler.results_iter(results): File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\sql\compiler.py", line 1299, in apply_converters value = converter(value, expression, connection) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\backends\mysql\operations.py", line 330, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\utils\timezone.py", … -
502 Bad Gateway in GAE with Django, & Log say "libBLT.2.5.so.8.6 No such file or directory"
Django 4.0.4 Python 3.8.9 I deployed Django App to GAE. But I got "502 Bad Gateway" error. And I checked server logs. That is below. Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/opt/python3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/workspace/SakeMarksV1/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "/opt/python3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, … -
Bootstrap 4 modal not working when button clicked from a dropdown
I know this question was asked many times but I think I've tried everything... I have a bootstrap dropdown and the dropdown item should open a modal. But it is not showing. Nothing happens when the button is clicked.. The modal works as expected when I click it with a normal button instead of a dropdown button. <div class="dropdown" style="float:right;"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> ••• </button> <div class="dropdown-menu"> <button type="button" class="dropdown-item delete-btn{{ comment.id }}" data-toggle="modal" data-target="#commentdeleteModal-{{ comment.id }}"> Delete </button> </div> </div> <div class="modal" id="commentdeleteModal-{{ comment.id }}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Are you sure you want to delete the comment? <br> This can’t be undone.</p> </div> <div class="modal-footer"> <form action="{% url 'comment-delete' comment.id %}" method="POST" class="comdelete-form" id="{{ comment.id }}"> {% csrf_token %} <div class="form-group"> <button class="btn btn-danger" type="submit">Delete</button> <button type="button" class="btn btn-secondary closebtn" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </div> -
How to fetch the all the data(records) which is searched (like : we are getting a slug from frontend),with Latest updated date
class A: some fields class B: user = models.ForeignKey(User, **CASCADE, related_name='sessions') DEVICES = ( ('android', 'android'), ('ios', 'ios') ) We are creating a dashboard for front end and there is a search field, user supposed to type the device_type and we used to fetch the records who uses only the IOS or Android. In this Case the records is stored in the fields like, Created_at, updated_at, device_type, user_id... we need to apply two filters now here: searched_key : ios or android latest_device_type : only latest updated_record I have done like : User.objects.filter(Q(id=user_details['id']) & Q(sessions__device_type=self.search_key) & Q(reduce(or_, self.query_filter))).order_by('sessions__user_id', '-sessions__created_at').distinct('sessions__user_id'). values('id', 'sessions__device_type', 'first_name') But am not getting exact output : even i tried [0] putting this after order_by and latest() and first() method will fetch only one record so any 1 has the best solution for this. Note : if anybody try to explain with Prefetch please explain with clarity. -
Django's APPEND_SLASH setting does not work with static, why?
Django's 4.1.1 APPEND_SLASH setting automatically appends a slash / until I add static roots, i.e. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT). For example, this works with http://127.0.0.1:8000/admin and http://127.0.0.1:8000/admin/ urlpatterns = [ path('', home), path('admin/', admin.site.urls), ] However, adding my static roots and the setting no longer takes effect: urlpatterns = [ path('', home), path('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Why? Is this a bug? How is urlpatterns += static etc impacting Django's setting? -
Is it possible to render a template excepting the app bundle (using django - webpack)
I'm using django with webpack. I'm trying to render a second html template that doesn't include the app bundle. I don't need the app bundle : enter image description here I don't use render bundle app in my dashboard template - just dashboard enter image description here thats my webpack plugin config enter image description here webpack config for for entry point and outputs enter image description here -
DRF serializer is taking nested JSON payload as single JSON object
Please go through the description, I tried to describe everything i've encountered while trying to solve this issue. I have two models, User and Profile. I'm trying to update them through one serializer. I've combined two models into one serilzer like below: class DoctorProfileFields(serializers.ModelSerializer): """this will be used as value of profile key in DoctorProfileSerializer""" class Meta: model = DoctorProfile fields = ('doctor_type', 'title', 'date_of_birth', 'registration_number', 'gender', 'city', 'country', ) class DoctorProfileSerializer(serializers.ModelSerializer): """retrieve, update and delete profile""" profile = DoctorProfileFields(source='*') class Meta: model = User fields = ('name', 'avatar', 'profile', ) @transaction.atomic def update(self, instance, validated_data): ModelClass = self.Meta.model profile = validated_data.pop('profile', {}) ModelClass.objects.filter(id=instance.id).update(**validated_data) if profile: DoctorProfile.objects.filter(owner=instance).update(**profile) new_instance = ModelClass.objects.get(id = instance.id) return new_instance When I send request with GET method, the DoctorProfileSerializer returns nested data(Combining two models User and DoctorProfile) in the desired fashion. But when I try to update both models through this serializer, it returns error saying User has no field named 'doctor_type'. Let's have a look at the JSON i'm trying to send: { "name": "Dr. Strange updated twice", "profile" : { "doctor_type": "PSYCHIATRIST" } } Let's have a look at how the serializer is receiving the JSON: { "name": "Maruf updated trice", "doctor_type": "PSYCHIATRIST" } … -
How to make pdf editor using python with django?
I am working on a project in which clients requirement is The user can edite the pdf while using browser and user can remove the text which they want. Reference: [Like This ][1] [1]: https://www.sejda.com/pdf-editor I used lots of python libraries but not all are good. -
Access dictionary property with dollar sign `$` in it's name using django template syntax
I'm ttrying to access a property with a $ in its name in a django template. Unfortunately I have neither control over additional filters nor over the variable name itself. The object is structured as follows: { "title": "Some title", "metadata": { "$price": 9.99, "$inventory_policy": 1 } } I am trying to access {{ item.metatadata.$price }}, but the template builder crashes with an unspecified error. I already tried the methods from python templates, but they crash as well: {{ item.metatadata.$$price }} {{ item.metatadata.${price} }} -
Django Query: How to filter record that have more than one foreign key
This is my models class WorkReport(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='work_reports') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tasks') effort = models.DecimalField() class ProjectMember(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='projects') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='members') role = models.CharField() In my views.py, I use ProjectMember as queryset and I can filter out the project that doesn't have any report, but can't find a way to filter out record where some member who haven't submit yet. This is what I currently get. Is there any way I can get only the first three? Project, Member, Role, Effort prj01, mem01, dev, 2 prj01, mem02, dev, 1 prj02, mem01, tst, 3 prj02, mem02, dev, null -
Save values into another database table with one-to-one relationship in Django during form update
This is my models.py with 2 tables having a one-to-one table relationship. UserComputedInfo model has a one-to-one relationship with CustomUser model. from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model class CustomUser(AbstractUser): email = models.EmailField(unique=True) post_code = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.username class UserComputedInfo(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) copy_input = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.copy_input Here is the relevant section of my views.py. from django.shortcuts import redirect from django.contrib import messages def profile(request, username): if request.method == "POST": user = request.user form = UserUpdateForm(request.POST, request.FILES, instance=user) if form.is_valid(): user_form = form.save() # How to save post_code to copy_input in UserComputedInfo model messages.success(request, f'{user_form.username}, Your profile has been updated!') return redirect("profile", user_form.username) return redirect("homepage") After a user submits a form, profile function will be run and post_code in CustomUser model will be updated. What I want to do is copy the content of post_code to copy_input in UserComputedInfo model as well. How do I do that inside my views.py? I am running Django v4 and Windows 10. -
Delete element with ajax in django
I am currently having some issue in deleting element with ajax in a Django Application. I have some pictures, each of them displayed in a bootstrap card. Basically, my code is kind of working, but I couldn't figure out why, for example, when I display the pictures in the card, in the first one of the list the Delete button doesn't work and, when I have multiple pictures, the delete button works but delete the first picture on the list and not the right one. I may have some mistake in fetching the IDs, but so far I couldn't find where the issue is. I post some code views.py def delete_uploaded_picture(request, pk): picture = Picture.objects.get(id=pk) if request.headers.get('x-requested-with') == 'XMLHttpRequest': picture.delete() return JsonResponse({}) js const deleteForms = document.getElementsByClassName('delete_form') deleteForms.forEach(deleteForm => deleteForm.addEventListener('click', (e)=>{ e.preventDefault(); let pk = deleteForm.getAttribute('data-pk') const cardDiv = document.getElementById('card_div'+pk) const clickedBtn = document.getElementById('clicked_btn'+pk) $.ajax({ type: 'POST', url: $("#my-url-div").data('url'), data: { 'csrfmiddlewaretoken': csrftoken, 'pk': pk, }, success: function(response){ $('#card_div'+pk).hide(); handleAlerts('success', 'Immagine Rimossa') }, error: function(error){ handleAlerts('danger', 'Ops qualcosa è andato storto!') } }) })) html <div class="form-group mt-2"> <div class="row"> {% if question.picture_set.all %} {% for pic in question.picture_set.all %} <div class="col-lg-4 col-md-6" id="card_div{{pic.id}}"> <form action="" method="post" class="delete_form" data-pk="{{pic.id}}"> <div … -
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' in Django 4 + highcharts
I'm trying to configure the display of graphs in django using highcharts and I encounter this error: AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' code: views.py import random from django.shortcuts import render from highcharts.views import HighChartsBarView class BarView(HighChartsBarView): title = 'Example Bar Chart' subtitle = 'my subtitle' categories = ['Orange', 'Bananas', 'Apples'] chart_type = '' chart = {'zoomType': 'xy'} tooltip = {'shared': 'true'} legend = {'layout': 'horizontal', 'align': 'left', 'floating': 'true', 'verticalAlign': 'top', 'y': -10, 'borderColor': '#e3e3e3'} @property def series(self): result = [] for name in ('Joe', 'Jack', 'William', 'Averell'): data = [] for x in range(len(self.categories)): data.append(random.randint(0, 10)) result.append({'name': name, "data": data}) return result index.html {% % load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/highcharts/highcharts.js' %}"></script> <script type="text/javascript"> $(function () { $.getJSON("{% url 'bar' %}", function(data) { $('#container').highcharts(data); }); }); </script> </head> <body> <div id="container" style="height: 300px"></div> </body> </html> I have no idea how to fix it enter image description here -
Can I take live data from an external gps and plot it in an offline map using Django?
I want to see the live location and the changes when i change my location in my django local server by ploting it into an offline map. Is it possible? Can someone please share the resources too. -
Django admin inline auto creates multiple fields on admin panel
I have a TicketMessage model that contains a foreign key to Ticket. I wanted to have my TicketMessage message field appear on my Ticket admin panel as an inline. I did succeeded in doing so however as shown in the image below for some reason by default it creates three message fields instead of one. Would like to know how to make it so it shows only one message by default and the reason why this happens in the first place. TicketMessage model from django.db import models from django.utils.translation import gettext as _ from painless.models import TimeStampMixin class TicketMessage(TimeStampMixin): class Meta: verbose_name = _("Ticket Message"), verbose_name_plural = ("Ticket Messages") ticket = models.ForeignKey( "Ticket", default=False, on_delete=models.PROTECT, related_name="ticket_message", help_text="Lorem ipsum" ) message = models.TextField( _("message"), max_length=500, help_text="Lorem ipsum", ) def __str__(self): return f"Ticket subject: {self.ticket}" def __repr__(self): return f"Ticket subject: {self.ticket}" Ticket admin from django.contrib import admin from django.utils.translation import gettext_lazy as _ from desk.models import ( Ticket, TicketMessage ) class TicketMessageInline(admin.TabularInline): model = TicketMessage @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): list_display = ( 'subject', 'status_choices', 'priority_choices', 'is_read', 'is_important', 'is_archive', ) list_filter = ( 'is_read', 'is_important', 'is_archive', 'status_choices', ) inlines = ( TicketMessageInline, ) filter_horizontal = ( "tags", ) fieldsets = ( (_("Primary Informations"), { …