Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named ' django'
Hello there I am following a tutorial on YouTube I use postman to post request of a user to an api just following his tutorial. I found an error: Internal Server Error: / Traceback (most recent call last): File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "E:\UsamaComputer\env\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html [17/May/2021 12:38:41] "GET / HTTP/1.1" 500 80940 Internal Server Error: /favicon.ico Traceback (most recent call last): File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "E:\UsamaComputer\env\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html [17/May/2021 12:38:41] "GET /favicon.ico HTTP/1.1" 500 80843 Bad Request: /auth/users/ [17/May/2021 12:38:45] "POST /auth/users/ HTTP/1.1" 400 58 Internal Server Error: /auth/users/ Traceback (most recent call last): File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner … -
MySQL + Django / ERROR 1045 and CommandError
I configured MySQL as follows: CREATE DATABASE IF NOT EXISTS foodb; CREATE USER IF NOT EXISTS 'foo'@'localhost'; ALTER USER 'foo'@'localhost' IDENTIFIED BY 'qux'; GRANT ALL ON foodb.* to 'foo'@'localhost'; SHOW GRANTS FOR 'foo'@'localhost'; FLUSH PRIVILEGES; SELECT user, host, authentication_string FROM mysql.user ORDER BY user, host; When I run python manage.py dbshell I get the following error: ERROR 1045 (28000): Access denied for user 'foo'@'localhost' (using password: YES) CommandError: "mysql --user=foo --host=localhost foodb" returned non-zero exit status 1. Also, this query SHOW GRANTS for 'foo'@'localhost'; returns +--------------------------------------------------------------+ | Grants for foo@localhost | +--------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'foo'@'localhost' | | GRANT ALL PRIVILEGES ON `foodb`.* TO 'foo'@'localhost' | +--------------------------------------------------------------+ 2 rows in set (0.00 sec) Finally, switching user to root and the root account password works just fine. So I think the issue must be with the user permissions on MySQL itself. What additional permissions does 'foo'@'localhost' need for this to work? -
Is it possible to use `__date` for a `timestamp` field in `filterset_fields` list of `DjangoFilterBackend`
I am using ListAPIView to list the records from my database table which is represented as ExpiredOrders(models.Model) in models.py. The Django model has several columns along with created_at and modified_at as timestamp. I want to filter the records on the created_at against the query parameters created_at. I am trying to use the DjangoFilterBackend to achieve the same. filter_backends = [DjangoFilterBackend] filterset_fields = ['craeted_at__date'] However, it return me an error - 'Meta.fields' must not contain non-model field names: created_at__date As created_date is a timestamp and in query parameter I will only get the date as YYYY-MM-DD, I am using __date to make the record of database table comparable with the query parameter. The other way to achieve this is - def get_queryset(self): try: queryset = ExpiredOrders.objects.filter(created_at__date=self.query_params['created_at']) except: queryset = ExpiredOrders.objects.all() return queryset I want to know if it is possible to get it done by just defining the filed name in the list filterset_fields. Also, please explain me what does this __ means here. Best to my knowledge it is a convention to represent class variable or methods which must not be used with the objects of other class or subclasses. Perhaps, this concept is known as name mangling in Python. … -
`HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer
This is what my serializers.py file is looking like: from rest_framework import serializers from .models import * class EinsatzSerializer(serializers.ModelSerializer): class Meta: model = Einsatz fields = ('pk', 'url', ...) # ... = all my other fields But when I create an "Einsatz", I get this error: Exception Value: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. Exception Location: .../venv/lib/python3.9/site-packages/rest_framework/relations.py, line 378, in to_representation I don't understand why I am getting this Error, when I am not even using HyperlinkedIdentityField. And where would I even put context={'request': request}? I also have a views.py and urls.py to show if needed. Thank you in advance! -
How to remove nesting from Django REST Framework serializer?
I have two models defined in my models.py file: class Album(models.Model): album = models.CharField(max_length=100) band = models.CharField(max_length=100) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song = models.CharField(max_length=100) For these, I have defined the serializers in my serializers.py file as: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = "__all__" class SongSerializer(serializers.ModelSerializer): album = AlbumSerializer() class Meta: model = Song fields = "__all__" When I make a request, the data I get is in this format: [ { "id": 1, "album": { "id": 1, "album": "Hybrid Theory", "band": "Linkin Park" }, "song": "Numb" }, { "id": 2, "album": { "id": 1, "album": "Hybrid Theory", "band": "Linkin Park" }, "song": "In the End" } ] How do I remove the nesting from the album name, from the songs Serializer? I would want data something like this: [ { "id": 1, "album_id": 1, "album": "Hybrid Theory", "band": "Linkin Park" "song": "Numb" }, { "id": 2, "album_id": 1, "album": "Hybrid Theory", "band": "Linkin Park" "song": "In the End" } ] -
Django Project could not resolve pylance
How to resolve this error. New to Django kindly help. I have tried installing pylint but it doesn't work -
Outputting a table to a template
I recently began to study Django and cannot understand how to correctly implement the template (table) I have a model: She has ties to Company and bank. class BankAccount(models.Model): company = models.ForeignKey('Company.Company', null=True, on_delete=models.CASCADE, verbose_name='Фирма', related_name='company') bank = models.ForeignKey('Bank', null=True, on_delete=models.CASCADE, verbose_name='Банк', related_name='bank') login_bank = models.CharField(max_length=255, verbose_name='Логин', null=False) password_bank = models.CharField(max_length=255, verbose_name='Пароль', null=False) date_created = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) balance = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) In the template I want to display a table where all firms / banks will be displayed at the intersection of these columns and rows, a value from this model will appear. I've been looking for an answer for 5 days and | | Company1 | Company2 | Company3 | Company4 | |-------|-------------------------|-------------------------|------------------------|-------------------------| | Bank1 | Balance(Company1/Bank1) | Balance(Company2/Bank1) | Balance(Company/Bank1) | Balance(Company4/Bank1) | | Bank2 | Balance(Company1/Bank2) | .... | .... | .... | | Bank3 | Balance(Company1/Bank3) | .... | .... | .... | -
ValueError: Unable to configure handler 'console'
I'm django new user, why i use the official settings.py from Django to start my project, it still throw exception? -
LookUp in django HTML's input tag
I am building a BlogApp and I am stuck on a Error. I am trying to lookup in HTML template, Because, I have two models for upload multiple images AND I am trying to access my second model field named file in HTML with input tag. Why i want to access model field in input tag ? I am trying to make my custom choose file button, AND which cannot be donw using {{ form }}, I have to access field name with <input> tag. I want to access model field in input tag because , When i try to upload file using <input type="file" name="file" > then it is not uploading or saving. AND when i try to access or save file using {{ form }} then it is working correctly. So i think this is because of i have two models , so i have to access model field name in input tag using LookUp. models.py class G(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) class GImage(models.Model): gimage = models.ForeignKey(G,related_name='imagess',on_delete=models.CASCADE) file = models.ImageField(upload_to='images') forms.py class GForm(forms.ModelForm): class Meta: model = GImage fields = ['file',] template.html When i try this then it is working correctly. <form method="post" action="" enctype="multipart/form-data"> {% … -
Django form data not saving into SQLite database
I am making a Django project and I want to submit a link name and a link into my form and make it appear on links.html but when I press submit, it prints onto the console that a post method had happened but when I check the database the data has not saved into it. In case this was a problem with my models I made one through the shell but it seemed to have been fine. Here is my forms.py: from django import forms class LinkForm(forms.Form): link_text = forms.CharField(label="Link text", max_length=150) link = forms.URLField(max_length=100000) models.py: from django.db import models # Create your models here. class Topic(models.Model): topic_text = models.CharField(max_length=40) def __str__(self): return self.topic_text class Link(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) link_text = models.CharField(max_length=150) link = models.URLField(max_length=100000) def __str__(self): return self.link_text links.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Links</title> </head> <body> {% if links %} {% for link in links %} <a href="{{link.link}}">{{link.link_text}}</a> <br /> {% endfor %} {% else %} <h1>This topic has no links</h1> {% endif %} <a href="/topics/{{ topic.id }}/newLink">Add a new link</a> </body> </html> newLink.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" … -
how assign permission different model to one object?
i have this model i need to assign permission Relation model to object TableRelation model because i want have one model permission class Relation(models.Model): title = models.CharField(max_length=100) layer = models.ForeignKey(Layer, blank=True, null=True, on_delete=models.CASCADE) related_from_table = models.CharField(max_length=150, default='', blank=True) related_from_connection = models.ForeignKey(DataBaseProfile, null=True, on_delete=models.CASCADE) related_source_field = models.CharField(max_length=150) def __str__(self): return self.title class Meta: permissions = ( ('view_relate', 'Can view relate'), ('delete_relate', 'Can delete relate'), ('add_relate', 'Can add relate'), ('edit_relate', 'Can edit relate'), ) class TableRelation(Relation): connection = models.ForeignKey(DataBaseProfile, blank=False, on_delete=models.PROTECT) related_table = models.CharField(max_length=150) related_destination_field = models.CharField(max_length=150) related_table_fields = JSONField() related_table_fields_view = JSONField(default=dict) form = models.OneToOneField(Form, null=True, on_delete=models.CASCADE) class Meta: default_permissions = () class APIRelation(Relation): class Meta: default_permissions = () api_profile = models.ForeignKey( APIProfile, on_delete=models.CASCADE) connection = models.ForeignKey(DataBaseProfile, blank=True, null=True, on_delete=models.PROTECT) I want to use parent-class permissions and not create separate permissions on the chile models. for example: from guardian.shortcuts import assign_perm assign_perm('relates.view_relation', user, table_relate_obj) assign_perm('relates.add_relation', user, table_relate_obj) assign_perm('relates.change_relation', user, table_relate_obj) assign_perm('relates.delete_relation', user, table_relate_obj) that do not work this example thanks -
Django QuerySet annotation with Case appears to be falsely positive
I am trying to annotate a QuerySet on a case-by-case basis but I get all results positive (1) when they should be all but one negative (0). The filter looks like so related_params[distro.id] = table.objects.filter( ProductId__in=[map["ProductId"] for map in related_maps_by_distro.values("ProductId")]).annotate( has_agr_param=Count( models.Case( models.When(DistributionParameterId__Code__in=[agr_parameter.Code for agr_parameter in agr_parameters], then=1), default=0, output_field=models.IntegerField(), ) ) ).order_by("DistributionParameterId__Name") where everything works just fine except for the annotate part. Values of [agr_parameter.Code for agr_parameter in agr_parameters] are ['ZARIZENI', '443', '10071', 'PC4.12', 'PC4.121', 'PC4.6', 'PC3.101', 'AIO 2.1'] while all possible DistributionParameterId__Codes are ['10176', '10175', '10171', '10177', '563', '10172', '10179', '829', '10174', '10173', '10170', '10178'] so there is only one match - 10071 - and therefore all but one should be annotated with 0. What am I missing? Any help would be appreciated. -
How do I copy to the clipboard in Django
I am new to django and currently I am working on a project where I need to create a functionality where the website users can copy the url to a post by a clicking on a button so that they can be able to share with other people. I am thinking of pyperclip module but I don't how to implement it in a web app and/or django templates. I have no other idea on how to go about this -
Using django-tables2 to show all admin tables in admin.py instead of default render
I am trying to use https://github.com/jieter/django-tables2 to replace the default Django admin table that you see when you login into the admin part. All the examples that I have found are based on creating a different view for the Model where you want to use, for example https://github.com/jieter/django-tables2/blob/master/example/templates/base.html but in this case, I want to use https://github.com/jieter/django-tables2/blob/master/example/app/admin.py. I do not how to tell Django to render these two fields ("name", "continent") using Django-tables2, instead of rendering with the default table. Can someone give me a hint? Thanks in advance! -
djangorestframework-simplejwt can't verify token
I have used django-rest-knox for user authentication. Now I want to add email-verification. I did it using djangorestframework-simplejwt. Note: I am creating an API. Here is my register view. class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() img = ProfileImage(owner=user) img.save() profile = Profiler(user=user, img=img) profile.save() token = RefreshToken.for_user(user).access_token abs_url = f'http://localhost:8000/auth/verify-email/?token={str(token)}' email_body = f'Salom {user.username}, ArticleUz dan ro\'yxatdan o\'tishni yakunlash uchun quyidagi link orqali emailingizni tasdqilang \n {abs_url}' data = {'subject': 'Emailingizni tasdiqlang', 'body': email_body, 'to': user.email} Util.send_email(data) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1], "profile": { "img": ProfileImageSerializer(img, context=self.get_serializer_context()).data['img'], "verified": ProfilerSerializer(profile, context=self.get_serializer_context()).data['verified'], } }) And my Verify-Email view is here class VerifyEmail(generics.GenericAPIView): def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) profiler = Profiler.objects.get(user=user) profiler.verified = True profiler.save() return Response({'message': 'Email verified'}, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError: return Response({'error': 'Token expired'}, status=status.HTTP_400_BAD_REQUEST) except jwt.exceptions.DecodeError: return Response({'error': 'Invalid token'}, status=status.HTTP_400_BAD_REQUEST) But whenever I clicked the link that's sent to email, It says Invalid Token. I can't understand. Can you help me, please? -
Django model foreign key field is not available in migrations during tests
I have this model. class TransportOrder(SomeMixin, models.Model): order = models.ForeignKey( to="orders.Order", on_delete=models.PROTECT, related_name="transport_orders", help_text=_("Order which was used for creating"), null=True, blank=True, ) # Other fields have been removed for simplicity I have forward function in a migration. def forward(apps, schema_editor): TransportOrder = apps.get_model("transportorders", "TransportOrder") # There is no `order` field printed result. print(dir(TransportOrder)) However, this only happens while running my tests. Otherwise there is no problem. What can cause this issue? -
Django generate bootstrap tabs with for loop
I have a page in my web app with multiple tables, and rather than have them on separate pages or one long list, I want to use tabs and I need to be able to generate these tabs based on how many objects there are. I'm pretty certain it's just a problem with the template, but I'll include all the other files just in case. Here are the models relevant to the problem. class Exercises(models.Model): exercise = models.CharField(max_length=45) evolution = models.CharField(max_length=8) start_date = models.DateTimeField(blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) logo = models.TextField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=['exercise', 'evolution'], name='exercise_evolution_UNIQUE') ] def __str__(self): return f"Exercise: {self.exercise}\t Evolution: {self.evolution}" class Units(models.Model): uic = models.CharField(max_length=10) unit_name = models.CharField(unique=True, max_length=45) mcc = models.CharField(max_length=5, blank=True, null=True) ruc = models.CharField(max_length=10, blank=True, null=True) personnel = models.IntegerField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=['uic', 'mcc', 'ruc'], name='uic_mcc_ruc_UNIQUE') ] def __str__(self): return f"{self.unit_name}" def get_uic(self): return f'{self.uic}' class ExercisePersonnel(models.Model): exercise = models.ForeignKey('Exercises', models.CASCADE) unit = models.ForeignKey('Units', models.CASCADE) location = models.ForeignKey('Locations', models.RESTRICT) quantity = models.IntegerField() def __str__(self): return f'{self.unit}' class UnitEdl(models.Model): unit = models.ForeignKey('Units', models.CASCADE) equipment = models.ForeignKey('Equipment', models.CASCADE) quantity = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['unit', 'equipment'], name='unit_equipment_UNIQUE') I have functions that use … -
How to access a jwt token from a django rest framework to angular frontend
I have created a DRF api authenticated with jwt,the token is stored in a cookie.I can successfully access all the viewsets using the token with postman.It only becomes a problem when l want to pass the token to angular frontend for the same operations.I am using django rest framework backend and Angular 9 frontend.Also note that l am storing the token in a cookie. My views.py class LoginView(APIView): def post(self,request): #getting the inputs from frontend/postman email =request.data['email'] password =request.data['password'] user=User.objects.filter(email=email).first() #Authentication if user is None: raise AuthenticationFailed('User not found!') if user.password!=password : raise AuthenticationFailed("incorrect password") payload = { 'id':user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=10), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() #storing the token in a cookie response.set_cookie(key='jwt',value=token ,httponly=True) response.data = { 'jwt':token } return response class UserView(APIView): def get(self,request): token=request.COOKIES.get('jwt') if not token: raise AuthenticationFailed("unauthorised") try: payload =jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed("session expired") user=User.objects.get(id=payload['id']) serializer=UserSerializer(user) return Response(serializer.data) class Update(APIView): def get_object(self,request): try: token=request.COOKIES.get('jwt') if not token: raise AuthenticationFailed("unauthorised") try: payload =jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed("session expired") user=User.objects.get(id=payload['id']) return user except User.DoesNotExist: return Response("wakadhakwa",status=status.HTTP_204_NO_CONTENT) def get(self,request): obj=self.get_object(request) serializer=UserSerializer(obj) return Response(serializer.data) def put(self,request): obj=self.get_object(request) serializer=UserSerializer(obj,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response("corrupted data",status=status.HTTP_204_NO_CONTENT) def … -
Nginx "upstream" directive is not allowed here
I'm trying to set up a Django website with uwsgi and nginx. I created configuration file mysite.conf: # the upstream component nginx needs to connect to upstream django { server unix:///home/path/to/mysite/mysite.sock; } # configuration of the server server { listen 80; server_name mydomain.com www.mydomain.com; charset utf-8; # max upload size client_max_body_size 350M; # Django media and static files location /media { alias /home/path/to/mysite/media; } location /static { alias /home/path/to/mysite/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/path/to/mysite/uwsgi_params; } } And it gives this error: nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/sites-enabled/mysite.conf:2 I don't why it happens. I followed this tutorial: https://tonyteaches.tech/django-nginx-uwsgi-tutorial/ -
How to display 2 message in my django website
I am creating a website that can display the hours worked of an employee and also show a graph of the employees past working hours. The graph on the y-axis could not show time value so I made an input that can convert integer to time. I want it to be displayed at the bottom while still showing the graph and hours worked. Here is a picture of my website displaying the hours worked, the graph and the convert input. . Here is after I convert integer to time. . Here is my code: def report(response): empName = employeeName.objects.all correct = True global cInUpdated global allDateUpdated global label if response.method == "POST": if 'byHour' in response.POST: n = response.POST.get("enterName") if employeeName.objects.filter(employee=n).exists(): emp = employeeName.objects.get(employee=n) time = emp.total_Hours_Worked messages.info(response, time + ' hours') f = Name.objects.filter(name=emp) allDate = [] cIn = [] today = datetime.today() datem = today.month for date in f: allDate.append(date.date) totalTime = (datetime.combine(date.date, date.timeOut)- datetime.combine(date.date, date.timeIn)).seconds/3600 cIn.append(totalTime) hours = int(totalTime) minutes = (totalTime*60) % 60 seconds = (totalTime*3600) % 60 time = "%d:%02d:%02d" % (hours, minutes, seconds) cInUpdated = [] allDateUpdated = [] label = "Hours worked this month" for item in range(len(allDate)): if allDate[item].month == datem: cInUpdated.append(cIn[item]) … -
Dynamically create <script src from string in database using django
In my Django project, I am dynamically rendering cards populated with data from a database. This works as expected. In each card, I need to render a vue-audio-mixer control, but each instance of the mixer must have it's own configuration script. Firstly, I tried this: <script src="{{ movements.script_source }}" but this is wrong. Then, I tried the following code but it does not work either. Any help would be appreciated, thanks. <script> var url = "{{ movement.script_source }}"; var script = document.createElement("script"); script.src = url document.body.appendChild(script); </script> -
state value not change reactjs when axios get
When I used this code as an API in Python(Django) to return three characters from the username but unfortunately the value of the state does not change. Django code: class usertype(APIView): def get(self,request,format=None): try: user=User.objects.get(username=request.user) except: raise ValueError('error') if not user.is_superuser: data={ 'usertype':user.username[:3], } return Response(data) else: return redirect('login') Reactjs code: state={ usertype:'', } gettype() { api.get('/').then(res=>{ this.setState({usertype:res.data.usertype}); }); } showDash() { switch(this.state.usertype){ case "std": ///code break; case "thr": ///code break; default: ///code break; } } All imports are correct and there are no problems with the library installation. how can i fix this problem! -
How to display celery progress bar on UI in a way that it should display even after switching pages
I have created celery-progress bar in my django project like click on a button and the progress bar starts on UI and it works.After progress starts when i go to back page or next page & come back to progress-bar page, It doesn't display the bar anymore however the celery task is still running in the background. I want to show the progress baron UI even after switching pages until the task is done. Please suggest me to achieve it.Here is my code: views.py def approval_req_func(request): task = go_to_sleep.delay(3) data = {'status': 'Success', 'message': 'Approved successfully', 'task_id':task.task_id} return HttpResponse(json.dumps(data), content_type="application/json") tasks.py @app.task(bind=True) def go_to_sleep(self,duration): progress_recorder = ProgressRecorder(self) s = Contact.objects.all() for i,j in enumerate(s): time.sleep(duration) print(j) progress_recorder.set_progress(i+1, len(s),f'On Iteration {i}') return 'Done' Html & Scripts <button>Click to start Progress</button> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <script> $(document).ready(function(){ $("button").click(function(event) { event.preventDefault() const valuesInArray = $(this).serializeArray() const body = {} valuesInArray.forEach(e => { body[e.name] = e.value }); $.ajax({ method: "GET", url: "{% url 'contact:approval_req_func' %}", data: body }).done(function (response) { $(function () { var progressUrl = "{% url 'celery_progress:task_status' 'task-id-stub' %}"; var progressUrll = progressUrl.replace('task-id-stub', response['task_id']); CeleryProgressBar.initProgressBar(progressUrll); }); }) .fail(function (response) { … -
Can we store files on the django framework?
I was wondering on how to store some files in the django framework, and how to access them for editing and updating them? I wanted to upload a few excel files and a few python scripts which automate the excel files. Everything is working fine locally for me, but just wanted to know on how to do it for webpage which can be accessed by anyone? Thanks -
Image is not uploading in Input Tag
I am building a BlogApp and I am new in django and HTML. I am trying to make a custom upload button using <input type="file" > BUT when i use {{ form }} then it is working BUT when i use <input type="file" name="file" > then it doesn't upload the Image. models.py class G(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) class GImage(models.Model): gimage = models.ForeignKey(G,related_name='imagess',on_delete=models.CASCADE) file = models.ImageField(upload_to='images') **My image instance name is file. views.py def new(request): GForm = modelformset_factory(GImage,fields=('file',),labels={'file':'Image'},extra=1,min_num=1) if request.method == 'POST': formset = GForm(request.POST,request.FILES,queryset=GImage.objects.none()) if formset.is_valid(): post_form = formset.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: if form: image = form['file'] photo = GImage(g=post_form,file=image) photo.save() return redirect('mains:all_stories') else: formset = GForm(queryset=GImage.objects.none()) context = {'formset':formset} return render(request, 'new.html',context) forms.py class GForm(forms.ModelForm): class Meta: model = GImage fields = ['file',] template.html When i try this :- <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <button type="submit" name='submit' class="btn btn-secondary btn-lg post"> Post </button> </form> BUT When i try with input tag then it doesn't work. <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <input type="file" …