Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
geeing vertical scroll bar after adding ckeditor django
before adding ckeditor my webpage was working fine but when I add ckeditor to my textarea field I get an vertical scroll bar. my problem is I want to remove that scroll bar which I have got after adding ckeditor template code is <div class="container"> <form method="POST"> <div class="form-group"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-weight: 700;">Create Notes</legend> </fieldset> {{form.media}} {{form|crispy}} <div class="form-group"> <button href="" class="btn btn-primary" type="submit"> Create </button> </div> </div> </form> model.py title=models.CharField(max_length=200) description = RichTextField(blank=True,null=True) my second problem is I want to remove image ,table and anchor optio from editor please help me to figure it out thanks in advance -
Problems with Django Avatars
I have a problem in my django app and when I edit a user my avatar photo is deleted and returns to the default one, I think the problem is in the views because it works correctly if I load the values from the django admin, If you could help me, I would appreciate it very much. This is the code: Views: @login_required def editar_user(request): mensaje = "" if request.method == "POST": extension_logued_user, _ = Avatar.objects.get_or_create(user=request.user) FormularioUser = NuestraEdicionUser(request.POST, request.FILES) if FormularioUser.is_valid(): logued_user = request.user #intancia del Usuario logued_user.email = FormularioUser.cleaned_data['email'] logued_user.first_name = FormularioUser.cleaned_data['first_name'] logued_user.last_name = FormularioUser.cleaned_data['last_name'] extension_logued_user.imagen = FormularioUser.cleaned_data['imagen'] extension_logued_user.link = FormularioUser.cleaned_data['link'] extension_logued_user.more_info = FormularioUser.cleaned_data['more_info'] if FormularioUser.cleaned_data['password1'] != '' and `FormularioUser.cleaned_data['password1'] == FormularioUser.cleaned_data['password2']:` logued_user.set_password(FormularioUser.cleaned_data.get("password1")) else: mensaje = "" if extension_logued_user.imagen is None: pass logued_user.save() extension_logued_user.save() return render(request, "index/index.html", {"mensaje":mensaje}) else: extension_logued_user, _ = Avatar.objects.get_or_create(user=request.user) return render(request, "EditUser.html", {"FormularioUser":FormularioUser,"mensaje":mensaje}) extension_logued_user, _ = Avatar.objects.get_or_create(user=request.user) FormularioUser = NuestraEdicionUser( initial={ 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'email': request.user.email, 'imagen': extension_logued_user.imagen, 'link': extension_logued_user.link, 'more_info': extension_logued_user.more_info, } ) return render(request, "EditUser.html", {"FormularioUser": FormularioUser, "mensaje":mensaje}) Template: {% extends 'index/index.html' %} {% load static %} {% block Encabezado %} <h1>Tu cuenta</h1> {% endblock Encabezado %} {% block PruebaTemplate %} {% if msj %} {{msj}} {% endif %} {% if … -
DRF call a cached view in another view
I have some classviews that I cache for a very long amount of time and I want to use the cached version of the result to speed up my API, but each time I call the cached view like so : data = ItemRaw.as_view()(self.request._request).data it will not return me the cached view but will re-request and rebuild the data then give it to me Is there a way to properly call a chached classview to get the cached data from the said view ? Thanks. -
I want to print if the discount value is blank then do not print anything if the discount value is something then show the value
I want to print if the discount value is blank then do not print anything if the discount value is something then show the value. how I will do this in if-else conditions. ** here is my HTML code ** {% for page_details in service %} <div class="row py-5 service_item"> <div class="col-md-12 d-flex justify-content-between"> <p class="border px-3 p-1 rounded text-center bg-light text-secondary font-weight-light">{{ page_details.service_name }}</p> {% if page_details.discount_optional > 1 %} <p class="border px-3 p-1 rounded text-center text-success border-success">{{ page_details.discount_optional }} % OFF</p> {% else %} <p class="border px-3 p-1 rounded text-center text-success border-success"></p> {% endif %} </div> <div class="col-md-8"><h5 class="card-title"></h5></div> <div class="col-md-4 text-right"> <strike class="text-secondary"></strike> &nbsp;<strong>₹ {{ page_details.price }}</strong><br/> <span class="text-secondary">Inc. of all taxes</span> </div> <div class="col-12"><p class="text-success">{{ page_details.Cancellation}}</p></div> <div class="col-12"> <span class="text-secondary"> Weekday_Off : </span><span class="text-dark"> {{page_details.Business_Details.weekday_off }}</span> <span class="text-secondary"> | Open Timings: </span><span class="text-dark">{{ page_details.Business_Details.open_time }}</span> <span class="text-secondary"> | Closed Timings: </span><span class="text-danger">{{page_details.Business_Details.close_time}}</span> </div> </div> {% endfor %} my model.py file class Services(models.Model): Business_Details = models.ForeignKey(Business_Details, on_delete=models.CASCADE, blank=True,null=True) service_name = models.CharField(max_length=100, blank=True, null=True) category = models.ForeignKey(category, on_delete=models.CASCADE, blank=True,null=True) subcategory = models.ForeignKey(subcategory, on_delete=models.CASCADE, blank=True,null=True) price = models.IntegerField( blank=True, null=True) duration = models.CharField(max_length=50, blank=True, null=True) image = models.ImageField() # description = HTMLField() discount_optional = models.CharField( max_length=10,blank=True, null=True) def __str__(self): … -
Get DataError: value too long for type character varying for every string
I use Django+Postgres for my project. I tried to implement user registration, but when I try to send a form with username and password, I get database error psycopg2.errors.StringDataRightTruncation: value too long for type character varying(32) That error appears with every string as a password, even its length less than 32. I tried to print form values, so they are the same that I typed. What can be the reason for value too long error? models.py class Person(AbstractUser): username = models.fields.CharField(max_length=50,unique=True) password = models.fields.CharField(max_length=32) forms.py class RegisterForm(ModelForm): username = forms.CharField(max_length=100) password = forms.CharField(widget=PasswordInput()) class Meta: model = Person fields = ["username", "password"] views.py def register(request): context={} if request.method == 'POST': form = RegisterForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] print('username: '+username) print('password: '+password) if len(Person.objects.filter(username=username))==0: Person.objects.create_user(username=username, password=password) else: context['form_errors']=['Person with this username already exists'] else: form = RegisterForm() error -
How to get logged in users credentials in Django?
I am trying to do some API calls from Django views. Is there any way I can get the logged in user credentials directly in the view so that I can use those creds in API authentication without asking the user to input same creds again. -
how do I show the real time value of cart without reloading the page
how do I show the real time value of cart when someone adds something to the cart without reloading the page, my function already handles the logic except it needs to reload, I'm trying to replace location.reload() in my javascript function with ajax that would just show the {{cartItems}} real time value on nav without reloading the page when someone hits the "add-to-cart" button, right now everything has to reload to work. I would really appreciate it if someone can help, thx! views.py def shop(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {"products": products, "cartItems": cartItems} #the nav is able to access home context def home(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} def ajax_update(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} return render(request, 'store/shop.html', context) urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 … -
Get the Image from the Private S3 bucket and convert the image to blob using django to give it to React Js
I having a logo field as Imagefield and i connected the filepath to s3 bucket. Once i upload a image in logo it will be uploaded in s3, if i delete or modify it working. But when i want to get the image to show that image in the frontend(reactjs) iam generating a url method where the aws credentials are shown in the url itself. But i need to change the image as blob(binary) and give that data to the frontend for the GET call. I dont know how can be it done, refered many sites but still not clear. Please help me solve this issue. Models.py class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def remove_on_image_update(self): try: # is the object in the database yet? obj = Organisation.objects.get(org_id=self.org_id) except Organisation.DoesNotExist: # object is not in db, nothing to worry about return # is the save due to an update of the actual image file? if obj.org_logo and self.org_logo and obj.org_logo != self.org_logo: # delete the old … -
Product matching query does not exist
when I try to add an item to a vendor it calls the POST method when this *view is called it shows an error that Product matching query does not exist. if you want any other files to tell I hope someone will fix this issue. class AddBaseproductToStore(AdminOnlyMixin, generic.TemplateView): template_name = 'aldobi-admin/add-product-to-store.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['prod_id'] = self.kwargs['pk'] context['vendor'] = self.kwargs['vendor'] return context def get(self, request, *args, **kwargs): product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_cat = BaseCategory.objects.all() return render(request, self.template_name, {"product": product, "base_cat": base_cat, 'vendor': vendor_id}) this the continuation of above code def post(self, request, *args, **kwargs): base_product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_category = BaseCategory.objects.get(id=request.POST.get('category')) try: p = Product.objects.get(base_product=base_product, category=Category.objects.get(vendor_id=vendor_id, base_category=base_category)) except AttributeError: product = Product() product.category = Category.objects.get(vendor_id=vendor_id, base_category=base_category) product.base_product = base_product product.name = request.POST.get('name') product.ar_name = request.POST.get('ar_name') product.sort_order = request.POST.get('sort-order') product.dryclean = request.POST.get('dryclean', '') == 'on' product.normal_dryclean_price = request.POST.get('dryclean_price') product.normal_dryclean_buffer_time = request.POST.get('dryclean_buffer') product.wash_and_pressing = request.POST.get('wash-press', '') == 'on' product.normal_wash_and_pressing_price = request.POST.get('wash-press-price') product.normal_wash_and_pressing_buffer_time = request.POST.get('wash-press-buffer') product.pressing = request.POST.get('press', '') == 'on' product.normal_pressing_price = request.POST.get('press-price') product.normal_pressing_buffer_time = request.POST.get('press-buffer') product.express_dryclean = request.POST.get('exp-dryclean', '') == 'on' product.express_dryclean_price = request.POST.get('exp-dryclean-price') product.express_dryclean_buffer_time = request.POST.get('exp-dryclean-buffer') product.express_wash_and_pressing = request.POST.get('exp-wash-press', '') == 'on' … -
Django-rest-framework api permission AllowAny authentication failed
I have someViews like below: class SomeView(generics.ListAPIView): serializer_class = SomeSerializer permission_classes = [AllowAny] settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), ... } And When I request without any Authorization header it works fine. But When I add Bearer Authorization header it response "detail": "Given token not valid for any token type", "code": "token_not_valid", I gave permission_classes=[AllowAny]. Why? I thought there is no difference between sending or not sending tokens. Because I set permission_class=[AllowAny]. In ASP.NET there is no like this problems. In ASP.NET If I set AllowAny permission this endpoint open for everyone regardless of whether you send a Token or not. -
AttributeError: 'ModelName' object has no attribute 'get' if response.get("X-Frame-Options") is not None:
I'm trying to get a list of Scripts I'm not sure why this error is django throwing however, Can anybody identify if there's something is wrong. Model class Script(models.Model): name = models.CharField(max_length=100) script = models.TextField() def __str__(self): return self.name Serializer class ScriptSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(read_only=True) script = serializers.CharField(read_only=True) view; @api_view(['GET']) def scripts(request): scripts = Script.objects.all() serializer = ScriptSerializer(scripts, many=True) return Response(serializer.data) but when I call this view, I get this error Internal Server Error: /api/v1/seo/scripts Traceback (most recent call last): File "E:\folder\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\folder\venv\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "E:\folder\venv\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'Script' object has no attribute 'get' I have also seen answers related to that issue in Stackoverflow but not able to reproduce the solution. And also this approach is not new to me, I have been using this type of functions all over the project. But I'm surprised now why it's happening. Edit: Imports from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import ScriptSerializer from .models import Script -
(DRF) How to make axios post request on nested object with reverse lookup for foreignkey as primary key
I have made Sample model as a ForeignKey to other two child model, and sample_ID as a primary key using lookup_field. models.py class Sample(models.Model): sample_ID = models.CharField(max_length=10) class Label(models.Model): AI_sample = models.ForeignKey(Sample, null=True, on_delete=models.CASCADE, related_name='AI_sample') AI_position = models.CharField(max_length=50) AI_defect = models.CharField(max_length=50) AI_tool = models.CharField(max_length=50) class Manual(models.Model): manual_sample = models.ForeignKey(Sample, null=True, on_delete=models.CASCADE, related_name='manual_sample') manual_position = models.CharField(max_length=50) manual_defect = models.CharField(max_length=50) manual_tool = models.CharField(max_length=50) Now my API endpoint looks like this: { "id": 3, "sample_ID": "a000001", "AI_sample": [ { "id": 3, "AI_position": "Position 1", "AI_defect": "Defect 1", "AI_tool": "Tool 1" } ], "manual_sample": [ { "id": 8, "manual_position": "Position 3", "manual_defect": "Scratch", "manual_tool": "Tool 2" } ] } Currently I am using reverse lookup of foreignKey to get the child data from sample_ID. Now I can easily make GET request by destructing the data like this: axios.get(url) .then(resp => { let data = []; const manual_sample = resp.data.manual_sample; manual_sample.forEach(el => { data.push({ id: el.id, manual_position: el.manual_position, manual_defect: el.manual_defect, manual_tool: el.manual_tool }); }); }) However, I am not able to make POST request out of a child data, because the I cannot set the primary key of sample_ID in a nested object. I am sending the manual_sample data request like this: { "id": 9, … -
Want to send extra data from BasePermission to Queryset in ModelVIewSet DRF
Here is My Seller Model which has User as OneToOneField #models.py . . class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") company = models.CharField(max_length=255) pincode = models.IntegerField() city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.TextField() profileActive = models.BooleanField(default=False) . . Purchase Model #models.py class PurchaseOrder(models.Model): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE) message = models.TextField(blank=True, null=True) expectedDelivery = models.DateField(blank=True, null=True) isCancel = models.BooleanField(default=False)) updated_at = models.DateTimeField(auto_now=True) #Custom permission_classes class SellerCompanyActive(BasePermission): message = 'Only Seller with activated company account is allowed' def has_permission(self, request, view): user = AuthUser.objects.get(id=request.user.id) if user.is_seller: try: company = CompanyProfile.objects.get(user=user) if company.profileActive: return True else: self.message = "Company profile is not active" except CompanyProfile.DoesNotExist: self.message = "Company not found first create company" return False In ModelViewSet #views.py class SellerPurchaseOrder(viewsets.ModelViewSet): queryset = PurchaseOrder.objects.all() serializer_class = PurchaseOrderSerializer authorization_classes = [TokenAuthentication] permission_classes = [IsAuthenticated, SellerCompanyActive] def get_queryset(self): user = self.request.user company = CompanyProfile.objects.get(user=user) return self.queryset.filter(company=company) Now here I always had to use this user = self.request.user company = CompanyProfile.objects.get(user=user) As their are lot of other views also, Is their any other way to send data from my custom permission_classes i.e from SellerCompanyActive to direct SellerPurchaseOrder->get_queryset -
How to modify url in a django get request
I have a web page which displays some data (with get parameters to filter in the view) and I use a pagination. To go through the data i use a link to change the page in the paginator : <li class="paginator-data"><a href="{{ request.get_full_path }}?page={{ page_obj.next_page_number }}">Next</a></li> Here is the problem : url looks like that after browsing a few pages : http://127.0.0.1:8000/?page=2&page=3&page=4&page=5&page=6 The view is working well (It displays me the last page) but I got this ugly link. I tried something like that : request.GET.get = querydict (with querydict a QueryDict object with only one page data) But It didn't work. I also thought of parsing data in the template but maybe there is a better way. -
How to add data in Django?
This is the Memo text where User can submit their Memo form. I need to add(update) new message this record via Update button in DJANGO. by the way I used PK and FK db table. How can I modify it? Tks. Error Message : IntegrityError at /addshowmemo/72/ (1048, "Column 'software_id' cannot be null") Request Method: POST Request URL:/127.0.0.1/addshowmemo/72/ Django Version: 3.1.5 Exception Type: IntegrityError Exception Value: (1048, "Column 'software_id' cannot be null") Exception Location: d:\project\python\it\venv\lib\site-packages\django\db\backends\mysql\base.py, line 78, in execute Python Executable: d:\project\python\it\venv\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\project\python\it', 'c:\Users\tou52\.vscode\extensions\ms-python.python-2022.4.1\pythonFiles\lib\python\debugpy\_vendored\pydevd', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310', 'd:\project\python\it\venv', 'd:\project\python\it\venv\lib\site-packages'] Models: class Memo(models.Model): notes = models.TextField() software = models.ForeignKey(Software, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return self.notes class Software(models.Model): STATUS_CHOICES = [ (0, 'Planning'), (1, 'Development'), (2, 'Using'), (3, 'Obsolete') ] name = models.CharField(max_length=100, verbose_name="SysName") url = models.CharField(max_length=100, verbose_name="SysAdd") status = models.PositiveIntegerField(default=0, choices=STATUS_CHOICES, verbose_name="Status") company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Company") team = models.ForeignKey(Team, on_delete=models.DO_NOTHING, verbose_name="Team") def __str__(self): return self.name Templates: <form method="POST" name="myform" action="." > {% csrf_token %} <table class="table table-striped"> <tr> <td align=right>Memo:</td> <td> <input type=text size=50 name="Cmemo" value='{{Nmemo.notes}}'> </td> </tr> <tr> <td> </td> <td> <input type=submit value="Confirm" class="btn btn-primary">||<a href='/showall/' class="btn btn-warning">Home</a> </td> <td></td> </tr> views: def add_showmemo(request,id=None,logmemo=None): memos = Memo.objects.all() if request.method=="POST": Cmemo … -
Nested quotes in html page
I have a button in my html code to reset password that have nested quotes <button type="" class="btn btn-primary" onclick="window.location.href='{% url 'password_reset' %}'">Forgot Password</button> The button work on site and doesn't seem to have any problem so far. But my VS Code give me the following problem ';' expected. Should I be concerned about this problem? -
showing error while writing heroku login in command line in Django framework in windows
**Made a project in Django framework, but when I tried to deploy on the internet using heroku login,This is the picture of the error. It's showing me this. Though I installed gunicorn and Django-heroku, It still shows me an Error. Please help me with this If anyone knows what is wrong happening behind the hood.I am using python 3.9.12 ** -
How to disable logging messages in Django shell?
I'm using pycharm to run my Django project and I did set some logging settings in my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, }, "formatters": { "verbose": { "format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}", "style": "{", }, }, "handlers": { "console": { "class": "logging.StreamHandler", "stream": "ext://sys.stdout", "formatter": "verbose", }, "mail_admins": { "level": "ERROR", "class": "django.utils.log.AdminEmailHandler", "filters": ["require_debug_false"], }, }, "loggers": { "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, }, "root": { "handlers": ["console"], "level": "DEBUG", }, } The problem is when I'm in the Django shell. In the Django shell when I press the tab button to auto-complete my code imports or calling methods,some logging messages just appear. PS D:\Django Projects\Company-Task\APITask> python .\manage.py shell DEBUG 2022-04-27 12:53:34,021 proactor_events 8988 5720 Using proactor: IocpProactor Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 8.2.0 -- An enhanced Interactive Python. Type '?' for help. DEBUG 2022-04-27 12:53:34,145 proactor_events 8988 5720 Using proactor: IocpProactor In 1: from task_auth.DEBUG 2022-04-27 12:53:49,375 diff 8988 5720 diff parser start DEBUG 2022-04-27 12:53:49,376 diff 8988 5720 line_lengths old: 1; new: 1 DEBUG 2022-04-27 … -
how do I show the real time value of cart without reloading the page
how do I show the real time value of cart when someone adds something to the cart without reloading the page, my function already handles the logic except it needs to reload, I'm trying to replace location.reload() in my javascript function with something that would just show the {{cartItems}} real time value on nav without reloading the page when someone hits the "add-to-cart" button, right now everything has to reload to work. I would really appreciate it if someone can help, thx! views.py def shop(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {"products": products, "cartItems": cartItems} #the nav is able to access home context def home(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } … -
Send messages from Django to Ajax while processing the request
I'm making an AJAX call to a Django POST view. It's reading X files locally, and then sending back to the front-end (thanks to ajax), so the user can download them. Everything is working fine on this part, but i'd like to have some sort of "intermediate response", which would tell Ajax that the server has read one file. That way, i could create a loading bar on the front end while the server is processing the request. Is there any way to do it, using only Ajax and Django ? Here is my code, quite simplified, so you can understand better what I'd like it to do: Django: def downloadFiles_API(request): if request.is_ajax and request.method == "POST": requested_files = json.loads(request.body)['files'] for file in requested_files: # Handle file reading (this part works) # Here i'd like to tell the front end "File X has been loaded..." # Zip-ing all files, and send it as response return FileResponse(myZipFile) AJAX: $.ajax({ url: "/api/downloadFiles/", type: 'POST', contentType: "application/json; charset=utf-8", data: JSON.stringify({ "files" : filesThatTheUserWants, }), xhrFields:{ responseType: 'blob' }, success: function (response){ // Download the file in response (this works) }, // And what i'd like to add (it's NOT in my code): onProgress: … -
How to display value on fields based on queryset?
i have a case like this : Models class Car(models.Model): description = models.CharField(max_length=200) is_available = models.BooleanField(default=False) class Rental(models.Model): car = models.ManyToManyField(Car) My question is, how to display Car on Rental models with is_available = True. On django admin ? Thank you -
OperationalError at /admin/Master/profile/ no such table: Master_profile
When I click on Users in admin site, it is showing errors. I am not getting points here. Please help me out what to do here. Errors: OperationalError at /admin/Master/profile/ no such table: Master_profile Request Method: GET Request URL: http://localhost:8000/admin/Master/profile/ Django Version: 4.0.4 Exception Type: OperationalError Exception Value: no such table: Master_profile Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Python Executable: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['E:\\Project\\S3_project', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Manoj\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Wed, 27 Apr 2022 06:36:44 +0000 models.py: class Profile(User): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') address = models.TextField(max_length=200,null=False) contact_number = models.PositiveIntegerField(null=False) ut=(('Admin','Admin'),('Operator','Operator'),('Ticket generator User','Ticket generator User'),('Inspector','Inspector'),('User 80','User 80'),('Final Inspection','Final Inspection'),('Maintenance','Maintenance'),('Ticket Admin','Ticket Admin'),) user_type = models.CharField(max_length=200, null=False, choices=ut) def __str__(self): return f'{self.user.username} profile' admin.py: admin.site.register(Profile) -
Does psycopg2-binary support pypy?
I wanted to create a django application using the pypy jit compiler, but db engines have a problem i.e. I can't connect to the postgres database -
How to Update this form data in Django?
This is the complain file where User can submit their complain form. I need to update this record via Update button in DJANGO. complain.html file: <form method='POST' enctype="multipart/form-data"> {% csrf_token %} Email: &nbsp; <input type="email" name="email" required/> <br /><br /> What is the complain: &nbsp; <input type="text" name="complain" required/><br /><br /> Who's against the complain (Enter Userame): &nbsp; <input type="text" name="against" required/><br/><br/> Position of the person you are complaining against: &nbsp; <input type="text" name="position" required/><br/> <br/> <div class="mb-3"> <label class="form-label">Evidence</label> <input class="form-control-file" type="file" name="image" required /> </div> </div> <div class="mt-1" style="text-align: center"> <button class="btn btn-danger type="submit"> Submit </button> <button class="btn btn-danger type="submit"> Update </button> </form> I need to update this record via Update button in DJANGO views.py : def complain(request): if request.method=='POST': email = request.POST['email'] complain = request.POST['complain'] against = request.POST['against'] position = request.POST['position'] image = request.FILES.get('image') user = User.objects.filter(username = against) if user.first() is not None: if request.user == user.first(): messages.error(request, 'You are complaining against Yourself :o ') return redirect('complain') pass if User.objects.filter(username = against).exists(): complain = Complain(email = email, complain=complain, against = against, position = position, image=image) complain.save() messages.success(request, 'Complain Submit Successful') return redirect('complain') else: messages.error(request, 'You are complaining against Non-User (-,-)') return redirect('complain') else: return render(request,'complain.html') This … -
Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name
I keep having this error when I try to add a post. It says, "Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name." I know this is not a matter of adding "path('summernote/', include('django_summernote.urls')" because I've already done that. models.py from django.db import models from django.contrib.auth.models import User from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget CATEGORY = ( ("Beginner", "Beginner"), ("Intermediate", "Intermediate"), ("Advanced", "Advanced"), ) class Post(models.Model): title = models.CharField(max_length=300, unique=True) slug = models.SlugField(max_length=300, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_posts') content = models.TextField() # content = models.CharField(widget=SummernoteWidget()) category = models.CharField(max_length=25, choices=CATEGORY, default="Beginner") created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['-created_at'] def __str__(self): return self.title urls.py from . import views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static app_name = 'course_app' urlpatterns = [ path('course/', views.PostList.as_view(), name='course'), path('course/<slug:slug>/', views.PostDetail.as_view(), name='course_posts'), path('summernote/', include('django_summernote.urls')), path('editor/', include('django_summernote.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render from django.views import generic from .models import Post class PostList(generic.ListView): """ Return all posts that are with status 1 (published) and order from the latest one. """ queryset = Post.objects.order_by('-created_at') template_name = 'course.html' class PostDetail(generic.DetailView): model = Post template_name = 'course_post.html' def courses(request): return render(request, 'course.html', …