Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploaded image is not showing in django Admin using class based views?
I am using Class Based Views for uploading images but none of the images are getting uploaded i.e. the images are not shown in Django Admin Site. This is simple blog project where in only superuser can upload blogs/posts. Here are my major files of the project: models.py class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title=models.CharField(max_length=256) text=models.TextField() create_date=models.DateTimeField(default=timezone.now()) published_date=models.DateTimeField(blank=True,null=True) blog_pic=models.ImageField(upload_to='blog_pics/',blank=True)#the field for uploading image forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('author','title', 'text','blog_pic') views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url='/login/' redirect_field_name='basic_app/post_detail.html' form_class=PostForm model=Post settings.py MEDIA_DIR=os.path.join(BASE_DIR,'media') STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'static') MEDIA_ROOT=MEDIA_DIR MEDIA_URL='/media/' I also made the changes in the urls.py which is mentioned in docs but that didn't solved my problem. urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Please help me rectify the error due to which the image is not being uploaded. -
Null Value error inspite of passing value in Serializer
I have a model in my app like this: class Bid(models.Model): supplier = models.ForeignKey(User, on_delete=models.CASCADE) order = models.ForeignKey(Orders, on_delete=models.CASCADE) comments = models.CharField(max_length=255, blank=True, null=True) bid_amount = models.CharField(max_length=255, default=0) date = models.DateTimeField(auto_now_add=True) is_confirmed = models.BooleanField(default=False) I am trying to save data in this model but keep getting the error: django.db.utils.IntegrityError: null value in column "order_id" violates not-null constraint DETAIL: Failing row contains (28, null, 800, 2020-06-09 12:43:14.697672+00, f, null, 5). Views.py class BidCreateAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def post (self, request, pk, format=None): supplier = request.user.pk d = request.data.copy() print("pk", pk) d['order'] = pk d['supplier'] = supplier print("d is", d) serializer = BidSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer.py class BidSerializer(serializers.ModelSerializer): order = OrderSerializer(many=True, read_only=True, required=False) class Meta: model = Bid fields = "__all__" I have set required=False in order serializer then why does it throws the error ? -
Cannot edit data from a table in django
I keep on getting this error and I don't know why. Can anyone help me with it? NoReverseMatch at /item Reverse for 'edit_supplier' with arguments '('lll111',)' not found. 1 pattern(s) tried: ['supplier/edit_item/(?P\d+)/$'] models.py class item_status(models.Model): item_code=models.CharField(max_length=30,unique=True,primary_key=True,blank=False) item_name=models.CharField(max_length=50,blank=True) type= models.CharField(max_length=100,blank=True) price=models.IntegerField() choices =({'AVAILABLE','Item ready to be purchased'},{'SOLD','Item Sold'},{'RESTOCKING','Item restocking in few days'}) status=models.CharField(max_length=50,choices=choices,default="AVAILABLE") #Available,Sold, Restocking item_quantity_available=models.IntegerField() issues=models.CharField(max_length=100,default="No issues") views.py def edit_item(request, pk, model, cls): item = get_object_or_404(model, pk=pk) if request.method == "POST": form = cls(request.POST, instance=item) if form.is_valid(): form.save() return redirect('index') else: form = cls(instance=item) return render(request, 'inv/edit_item.html', {'form': form}) def edit_item_status(request, pk): return edit_item(request, pk, item_status, item_statusForm) forms.py class item_statusForm(forms.ModelForm): class Meta: model = item_status fields = ('item_code', 'item_name', 'type', 'price','status','item_quantity_available','issues',) urls.py url(r'^item/edit_item/(?P<pk>\d+)$', edit_item_status, name="edit_item_status"), index.html {% for item in items1%} <tr> <td>{{ item.item_code }}</td> <td>{{ item.item_name }}</td> <td>{{ item.type }}</td> <td>{{ item.price}}</td> <td>{{ item.status}}</td> <td>{{ item.item_quantity_available}}</td> <td>{{ item.issues}}</td> <td> <a href="{% url 'edit_supplier' item.item_code %}" class="btn btn-warning btn-sm" role="button" aria-pressed="true" > Edit</a> <a href="{% url 'delete_supplier' item.item_code %}" class="btn btn-danger btn-sm" role="button" aria-pressed="true" > x</a> </td> </tr> {% endfor %} This code however works fine for my other classes that use integer primary key. I don't know why and I am totally lost now. -
django-tables2 accessing computed data
I am creating set(t)s as accumulation of parts and I want to display their total price according similar to this post: models.py: class PartBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price", decimal_places=2, max_digits=8) class Sett(models.Model): name = models.CharField('Name', max_length=120) class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='setts', on_delete=models.SET_NULL, null=True) def get_position_price(self): return self.qty * self.part.price tables.py: class SetTable(django_tables2.Table): total_price = django_tables2.Column(accessor="total_price", verbose_name="total") class Meta: model = Sett sequence = ("name", "total_price") exclude = ("id",) views.py: class SetListView(SingleTableView): model = Sett context_object_name = "setts" table_class = SetTable def get_context_data(self, **kwargs): context = super(SetListView, self).get_context_data(**kwargs) for s in context["setts"]: pr = PartRelation.objects.filter(sett=s) s.total_price = 0 for p in pr: s.total_price += p.get_position_price() return context def total_price(self): pos = PartRelation.objects.filter(sett_id=self.kwargs["pk"]) total_price = 0 for p in pos: total_price += p.get_position_price() return total_price I tried accessing the data via get_context and also via a custom method total_price, but neither worked. Where did I take the wrong turn? -
Pip package install in both globally and in virtualenv
I have a problem with installing my pip packages. I have created a virtualenv and when I try to install packages through pip, it gets install both globally and inside my virtualenv. Does anyone have any solution why this is happening? I want to solution to be for windows. -
How to do unitetesting for unmanaged apps in django.? [closed]
I have an application where I am using 3 tables from legacy db and one resides within the application db. I have tried the solution https://dev.to/vergeev/testing-against-unmanaged-models-in-django ,https://blog.birdhouse.org/2015/03/25/django-unit-tests-against-unmanaged-databases/ ,https://dev.to/vergeev/testing-against-unmanaged-models-in-django. But nothing seems to work. I run my scripts as follows: python manage.py test --settings=myapp.test_settings myapp.tests.Testclass Can anyone help. -
Django; how to show the data of two models
am working on a project where one user adds price and then confirms the booking. My point is a user1 add a post and user2 add price on user1 post so when user1 accepts the price then user2 confirm the booking. Now the question is add price model user2 and booking model user2 are same but the posting user1 now I want to show data of user2 of two models. here is the model of add price. class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices', on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) status = models.BooleanField(default=False) approved = models.BooleanField(default=False) vehicle_type = models.CharField(max_length=50, default='') here is my model to confirm the booking of the same user. class Booking(models.Model): post = models.ForeignKey(Loader_post, related_name='b_post', on_delete=models.CASCADE, default='', null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') approved_price = models.BooleanField(default=False) b_price = models.CharField(max_length=50, default='') vehicle_type = models.CharField(max_length=50, default='') vehicle_model = models.CharField(max_length=50, default='') this is my view class Booking_view(ListView): context_object_name = 'prices' model = price template_name = "Booking_view.html" what kind of filter should I use for that? -
Django file does not exist error when trying to attach pdf in email based on conditions
I am trying to send a 2 pdf files as attachment,1 generated by xhtml2pdf and another which is already present in the app directory of my django project, based on a condition. I am able to send the generated file and 1 file but getting error " File does not exist" for the other condition, even when both the files are in the same location. I am a newbie here, what am i doing wrong? where and how do i need to store the files to be attached ? my views code for email- patienthist = get_object_or_404(PatientHist, pk=email_id) # stores values (Y,N) pdf = Render.render('eradicate/dietplan.html', context) msg = EmailMessage("Your Diet Plan", "Attached is your diet plan!", to=[email_id]) msg.content_subtype = "html" msg.attach('my_pdf.pdf', pdf, 'application/pdf') # attaching generated pdf if patienthist.foodhabit == 'N': msg.attach_file('eradicate/LCHF Eradicate Diabetes.pdf') # doest not get attached else: msg.attach_file('eradicate/LFV Eradicate Diabetes.pdf') # gets attached to email msg.send() error i am getting- FileNotFoundError at /eradicate/test@gmail.com/dietplan/ [Errno 2] No such file or directory: 'eradicate\\LCHF Eradicate Diabetes.pdf' Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python37\lib\pathlib.py in _opener, line 1058 note: its adding an extra backslash after the app name eradicate, why does this happen? my 2 files are stored in the django app directory, same level … -
DRF: APIView.finalize_response does not work when internal error happens
I have an APIView and I have overrode finalize_response method to log some information. It works fine but the problem is that, finalize_response won't be called when an internal error happens! While server responses with 500 status and some message! How can I catch internal error and log information about response?? class MyApiView(APIView): ... def finalize_response(self, request, response, *args, **kwargs): # doing some logging stuff! -
Changing names of Django form field in clean method
I am trying to change the names of my Django form fields in the clean method, depending on whether its value is True or False after the form is submitted. However, the method appears not to be using the new fields names calculated in the top part of the method, to clean the data in the second part, as I am getting a ValueError: 'UserServices' has no field named 'temporary_life_changes_end_date', but when I put a print statement in and print the cleaned data, 'temporary_life_changes_end_date' exists as a key. Why is this? def clean(self): cleaned_data = super().clean() # Change the field names to the category's internal code for category in enums.Category: if category.value in cleaned_data: if cleaned_data[category.value] == True: internal_code = models.RecordType.objects.get( industry_code=category.value ).internal_code cleaned_data[internal_code] = cleaned_data.pop(category.value) if category.value + "_end_date" in cleaned_data: cleaned_data[internal_code + "_end_date"] = cleaned_data.pop( category.value + "_end_date" ) else: cleaned_data.pop(category.value) if cleaned_data.get( "families_with_young_children_5_or_under", False ) and not cleaned_data.get("families_with_young_children_5_or_under_end_date", False): self.add_error( "families_with_young_children_5_or_under_end_date", "Please enter a date" ) if cleaned_data.get("temporary_life_changes", False) and not cleaned_data.get( "temporary_life_changes_end_date", False ): self.add_error("temporary_life_changes_end_date", "Please enter a date") -
How to upload multiple images using a single file upload button in django forms
I have been struggling to upload multiple images using single file upload button in django forms in my blog post. I will highly appreciate any assistance especially in creating the views.py that will enable the functionality. Here is part of my code. models.py from django.db import models from django.utils.text import slugify from django.conf import settings from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver def upload_location(instance, filename, **kwargs): file_path = 'posts/{author_id}/-{filename}'.format( author_id=str(instance.author.id), filename=filename ) return file_path class Post(models.Model): title = models.TextField(max_length=100, null=False, blank=False) detail = models.TextField(max_length=500, null=False, blank=False) date_published = models.DateTimeField(auto_now=True, verbose_name='date published') date_updated = models.DateTimeField(auto_now=True, verbose_name='date updated') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.detail class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_location) def __str__(self): return self.post.detail @receiver(post_delete, sender=Post) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_ad_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.author.username + '-' + instance.detail) pre_save.connect(pre_save_ad_post_receiver, sender=Post) forms.py from django import forms from posts.models import Post, PostImage class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['type', 'category', 'sub_category', 'detail', 'currency', 'price'] class ImageForm(forms.Form): images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = PostImage fields = ['images'] home.html <form class="post-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ posts_form }} {{ images_form … -
Django Fullcalendar Not rendering
I will get straight to the point. I'm using FullCalendar in mu application, and it's working fine, as aspected, but somehow, I have bugs when I try to render the calendar with ajax call, so the second time. When I call the landing page, the view, calendar gets rendered properly, but when I try to filter down the calendars using ajax implementation, the rendering is lost! I literally have no idea why is this happening, so any help will be great! The idea is simple, when I land on the page, I have all calendars rendered, and if I want to chose the particular calendar group, I just want to do a basic filtering depending on the users data. First, this is my function which handles the page : @login_required(login_url='registration/login') def add_event(request, pk): cal_group_param = request.GET.get('value_from_the_user', None) #Takes the users input from the frontend context = {} ... # Code which is nor relevant for this question ... events_all = Events.objects.all() if cal_group_param: calendars = Calendar.objects.all().filter( date_valid__gte=now.date(), calendar_master__group__cusopis=cal_group_param, ).order_by('date_valid') else: calendars = Calendar.objects.all().filter( date_valid__gte=now.date(), calendar_master__group__cusopis__icontains='default_group', ).order_by('date_valid') form = ZakaziForma() if request.method == 'POST': form = ZakaziForma(request.POST or None) if form.is_valid(): ... return redirect(success_page) context['cal_groups'] = cal_groups context['calendars'] = calendars context['form'] … -
how to Serve Pdf data from server to client. (Django)
I am working on a ebook reader app in which people can send pdf and get pdf content on more mobile read-friendly way. anyway to serve pdf data from server to client without disturbing images? for more info: i am using djnago rest framework. -
get_field_display() does not return string after saving it
Hereby my (simplified) situation. When I change a choicefield from one to the other, I want to record a message saying "Field changed from (previous) to (new)" In parenthesis I'd like the actual label of the field, so in case of the example below that should be "Field changed from Open to Completed". However, for some reason I am only able to generate "Field changed from Open to 2" I am baffled why this happens given that I use the exact same code. Any ideas? class Task(Record): class Status(models.IntegerChoices): OPEN = 1, "Open" COMPLETED = 2, "Completed" status = models.IntegerField(choices=Status.choices, db_index=True, default=1) Then in my views I try to do this: if request.POST["status"] == 2: description = "Status changed from " + info.get_status_display() + " → " # This works fine, returning "Status changed from Open → " info.status = request.POST.get("status_change") info.save() description = description + str(info.get_status_display()) # Yet for some reason this fails, and I end up with an integer (2)! even though I use the same syntax -
How to enable debugging in a particular app in Django
I want to enable Django debugging in a particular apps in the whole project because when the site is go to production if found something anything bug then I will fix by enabling the debug in the particular view in Django app without affecting the other modules Thank in advance. -
QuerySet for 3 Connected Model
I have a tree model for my ecommerce project. Want to show which product and how many waiting for packaging. I just want to show New Orders' product and quantities. For example: A product - 119 B product - 6 my model is: CHOICES = ( (1, _("New Orders")), (9, _("Canceled")), (10, _("Completed")), ) class Orders(models.Model): order_no = models.CharField(max_length=80) order_date = models.DateField(blank=True,null=True) order_status = models.IntegerField(choices=CHOICES, default=1) class Meta: verbose_name = "Order" verbose_name_plural = "Orders" ordering = ['order_date'] def __str__(self): return self.order_no class Products(models.Model): product_name = models.CharField(max_length=250,blank=True,null=True) barkod = models.CharField(max_length=60,blank=True,null=True) raf = models.CharField(max_length=15,blank=True,null=True) tax = models.DecimalField(blank=True,null=True, max_digits=5, decimal_places=0) class Meta: verbose_name = "Product" verbose_name_plural = "Products" ordering = ['pk'] def __str__(self): return self.product_name class OrderItems(models.Model): order = models.ForeignKey(Orders,on_delete=models.CASCADE,related_name='order') product = models.ForeignKey(Products,on_delete=models.PROTECT,related_name='product_order') quantity = models.CharField(max_length=6,blank=True,null=True) price = models.DecimalField(blank=True,null=True, max_digits=9, decimal_places=2) class Meta: verbose_name = "Item" verbose_name_plural = "Items" ordering = ['-pk'] def __str__(self): return self.order.order_no There is 3 model connected each other. I need the products in the New Orders and total quantity of them. I couldn't find the right way to do it. Is there a suggestion? -
django autocomplete light. Is there any tutorial for it with the post method?
Any help?! I'm trying to follow this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html And I have many problems with it. One of my question would be... In my form I'm using POST method because I am posting queries in database... But this above tutorial seemingly using GET method... Is there any tutorial to for autocomplete light with the POST method, could you adjust this method to implement POST or autocomplete is not made for POST method. In the last scenario, which method for autocomplete of the search form better to use? -
Django formset errors show up in print but not in templates
When I print out the errors in the form_valid method the errors are shown, but in the template, the errors are not shown. What am I missing here? views.py class ParentManage(LoginRequiredMixin, UpdateView): login_url = reverse_lazy('login') model = Parent form_class = ParentManageForm slug_url_kwarg = 'parent_slug' template_name_suffix = '-manage' def get_object(self): return Parent.objects.get(slug=self.kwargs['parent_slug']) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["children"] = ChildFormset(self.request.POST, instance=self.object) else: data["children"] = ChildFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() children = context["children"] self.object = form.save() if children.is_valid(): children.instance = self.object children.save() print(children.errors) print(children.non_form_errors) return super().form_valid(form) def get_success_url(self): parent = self.get_object() return reverse("parent-detail", kwargs={'parent_slug': parent.slug}) For the print statement when the POST request process, this is what I see in the shell: [{'__all__': ['Child with this Parent and Order already exists.']}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] <bound method BaseFormSet.non_form_errors of <django.forms.formsets.ChildFormFormSet object at 0x04F24040>> But it won't show up in the template. parent-manage.html: <div> <form method="post" action="{% url 'parent-manage' parent_slug=parent.slug %}"> {% csrf_token %} {{ form }} {{ children.management_form }} {% for dict in children.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor … -
What is the issue here?
python request get source code is different with actual source code. I am trying to web scrapping this web site "https://www.sundhed.dk/borger/guides/find-behandler/?Informationskategori=Psykolog" When I inspect it in the website it shows a different HTML code and when I use get.requests in pycharm and using soup when I print it, it is a different HTML code. Any idea why? ps : I am new to django -
How to execute django background tasks without command line?
I have checked out multiple other posts, but can't use the code I've seen circuling around (see below). I don't know where tasks is coming from on the last line: if not Task.objects.filter(verbose_name="update_orders").exists(): tasks.update_orders(repeat=300, verbose_name="update_orders") I want to be able to execute the function when it is called and only when it is called. So far when I run python manage.py runserver it runs the background tasks without having called them. Thank you. -
Django CSRF token missing or incorrect but CSFR has been added
Django give me the following error CSRF token missing or incorrect. but I don't find the issue. I have created my forms: class ModCollaboratoriForm(forms.ModelForm): class Meta: model = AltriCosti fields = "__all__" and my simple views.py: def collaboratori_commessa(request): collaboratori_commessa=AltriCosti.objects.all() if request.method == 'POST': form = ModCollaboratoriForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = ModCollaboratoriForm() context={ 'form':form, 'collaboratori_commessa': collaboratori_commessa, } return render(request, 'commesse/collaboratori_commessa.html', context) And in my collaboratori_commessa.htm the following form: <form id="contact-form" name="contact-form" method="post" > {% csrf_token %} <div class="card card-outline card-info shadow "> <div class="card-header "> <h4 class="mb-0"> <img src="{% static 'icon/plus-circle.svg' %}"> Informazioni generali </h4> </div> <div class="card-body"> {{ form.media }} <div class="row"> <div class="form-group col-2 0 mb-0" > {{form.codice_commessa|as_crispy_field}} </div> ..... </div> <div class="card-footer"> <div class="col-md-2"> <button class="btn btn-info form-control" type="submit" onclick="submitForm()">Registra</button> </div> </div> </form> Why django give me the CSRF Error? -
How can I add custom button beside of add row in django tabularinline?
I want to add custom button and action beside of "add another [inline object]...". But I can't find where can I override the template or what python package can I use. I'm going to add "import" button to reset the standard data. Please help me. Thanks a lot. -
How to find connection between two uers in django rest?
I have one Follower system and here I want to check those are following to me,we have a mutual connection or not. If they are following to me and I'm not following to them, I want to set in frontend follow back. Inside the views, I'm fetching the data and sending them to serializer but I don't, How I can check it? My models and views are in below: models.py class Follow(models.Model): follower = models.ForeignKey(User,on_delete = models.CASCADE,related_name = 'following') followee = models.ForeignKey(User,on_delete = models.CASCADE,related_name = 'followers') created_at = models.DateTimeField(auto_now_add = True, null = True) updated_at = models.DateTimeField(auto_now = True, null = True) class Meta: unique_together = ("follower", "followee") ordering = ('-created_at',) views.py: class FollowerAPIView(APIView,PaginationHandlerMixin): pagination_class = BasicPagination serializer_class = UserFollowerSerializer def get(self,request,*args,**kwargs): follower_qs = Follow.objects.filter(followee = request.user).select_related('follower') page = self.paginate_queryset(follower_qs) if page is not None: serializer = self.get_paginated_response(self.serializer_class(page, many=True).data) else: serializer = self.serializer_class(follower_qs, many=True) return Response(serializer.data,status=status.HTTP_200_OK) -
Django - redefine Form Select using pk URL
I need to set input (select) value using pk sended by URL. Using init in form, almost get the answer, but init method is executed twice and clean my value. Form: class CrearDelitoForm(forms.ModelForm): class Meta: model = Delito exclude = () def __init__(self, numero_pk = None, *args, **kwargs): super(CrearDelitoForm, self).__init__(*args, **kwargs) self.fields["imputado"].queryset = Imputado.objects.filter(numero_id = numero_pk) DelitoFormset = inlineformset_factory( Expediente, Delito, form=CrearDelitoForm, extra=1, can_delete=True, fields=('imputado', 'delito', 'categoria'), } ) Views: class CrearDelito(CreateView): model = Delito form_class = CrearDelitoForm template_name = 'crear_delito.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['formset'] = DelitoFormset() context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk']) return context def get_form_kwargs(self, **kwargs): kwargs['numero_pk'] = self.kwargs['pk'] return kwargs ** System check identified no issues (0 silenced). June 08, 2020 - 11:33:57 Django version 2.2.12, using settings 'red.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. , ]> ** I think problem is on context = super().get_context_data(**kwargs) but don't know why. -
Django, how to handle fetch request
I'm working on a Django project that uses a flatbed scanner. Since scanning takes a long time I must work around getting a timeout error. After searching and trying multiple things I ended up with threading an a fetch call. How do I alter the fetch call to do what I want? I currently get send to a blank page that shows the dictionary that was returned by free_scan_crop. Please note that I am new to JavaScript. I just copied this bit of JS. What I would like to happen: A modal shows up when the form is submitted When the scanner is done: send user to home page and show message scan.html <div class="modal fade" id="scanDocument" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Scanning</h5> </div> <div class="modal-body"> Please wait... </div> </div> </div> </div> <script> formElem.onsubmit = async (e) => { e.preventDefault(); let response = await fetch("{% url 'core:free_scan' %}", { method: 'GET', body: new FormData(formElem) }); let result = await response.json(); alert(result.message); }; </script> views.py def free_scan_crop(request): form = FreeScanForm(request.GET) if form.is_valid(): file_name = form.cleaned_data['file_name'] # Grab the rest of the fields from the form... x = threading.Thread( target=scan_crop, args=(request, file_name, top_left_x, …