Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enum field in MySQL
In MySQL there are several types of data, char, varchar int, boolean as you already know. But it also has the Enum type that in SQL we create the table as follows: CREATE TABLE person( id int..... name varchar(50), and Married Enum(Yes,No) ) My goal is, when I'm creating the models in Django (Python) to be able to create the tables in MySQL I can automatically create this type of field as well. I tried like this: from django.db import models from enum import enum class options(Enum): Yes = "Yes" No = "No" class Customer(models.Model) : name = models.CharField(max_length=200) docto = models.CharField(max_length=14) age = models.IntegerField(default=0) username = models.CharField(max_length=20) password = models.CharField(max_length=20) block = models.CharField( max_length=3, choices=[(tag, tag.value) for tag in options], default= 'No' ) def __str__(self): return self.name Create the field in MySQL creates but creates as VARCHAR(3) and not as enum. Can Django do this? How would it be? I wouldn't like to have to create the tables directly in the database, -
Django Forms Radio Button
I had made a form using django forms and call it to a template but while I select a radio button it won't pick what's the solution ''' html section ''' <div class="form-row p-t-20"> <label class="label label--block">Gender</label> {% for radio in form.Gender %} <div class="p-t-15"> <label class="radio-container"> {{radio}} <input type="radio" name="gender"> <span class="checkmark"></span> </label> </div> ''' forms section ''' Gender = forms.ChoiceField(choices=GenderChoice,widget=forms.RadioSelect(attrs={'class':'form-check form-check-inline'})) -
Django is not creating any fields with users created manually
i've created a eccomerce website. this has a registration page where users creates their user account & then can order anything. if i create a user from admin panel, then everything works perfectly. but if i create a user from front end of my registration page using React js, then that user can't order anything, meaning when i post a data using fetch django doesn't store or create any data for that user. why? what's the issue here? i'm using Rest Api in backend & posting data through fetch to send data. but the fetch fails but not if i use a user which was created from admin panel(./admin). am i doing anything wrong in creating the user data manually at my views??? #my_views from django.shortcuts import redirect from django.contrib.auth.hashers import make_password from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from App.models import * from api.forms import RegisterForm from .serializers import * from django.contrib.auth.models import User class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET','POST']) def getRoutes(request): routes = [ '/api/token', '/api/refresh', ] return Response(routes) … -
Errors not showing in Django signup template form
Hi i need help with my code, errors not showing up in my HTML form and i dont know how to debug it or how to understand why the div isnt showing, i tried changing its CSS i tried changing classname i tried everything i just cant get it to show when i put bad inputs. views.py from django.shortcuts import render, redirect from .forms import SignUpForm from django.contrib.auth import login def frontpage(request): return render(request,'core/frontpage.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('frontpage') else: form = SignUpForm() return render(request, 'core/signup.html', {'form': form}) signup.html {% extends 'core/base.html' %} {% block title %} Sign Up | {% endblock %} {% block content %} <div class="main"> <h1>Sign Up</h1> </div> <div class="form-container"> <form method="post" action="." class="sign-up-form"> {% csrf_token %} <p>Fill Form :</p> <div class="form-items"> <label for="username">Username</label> <input type="text" class="label" id="username" name="username" placeholder="Username" > <label for="password">Password</label> <input type="password" class="label" id="password" name="password1" placeholder="Password"> <label for="confirm-password">Confirm Password</label> <input type="password" class="label" id="confirm-password" name="password2" placeholder="Confirm Password"> {% if form.error %} {% for field in form %} {% for error in field.errors %} <div class="error-msg"> <p>{{ error|escape }}</p> </div> {% endfor %} {% endfor %} {% endif %} <div class="form-control-buttons"> <button … -
ImportError: Module 'django.contrib' does not contain a 'Advisor' class. ------- why am I getting this error
Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\config.py", line 225, in create raise ImportError(msg) ImportError: Module 'django.contrib' does not contain a 'Advisor' class. -
How to use django-oauth-toolkit to protect a package's API
I'm developing a web API using "django-scim2" package. As a development requirement, bearer token authentication is required when accessing the django-scim2 API via http. The django-scim2 documentation (https://django-scim2.readthedocs.io/en/latest/) says "This app does not implement authorization and authentication. Such tasks are left for other apps such as Django OAuth Toolkit to implement." And as I check the django-oauth-toolkit docs, I can see how to protect it when you create a function or class, https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/function_based.html https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/class_based.html but django-scim2 is loaded from config/urls.py as it is (like below), so I have nothing to do and I don't know how to implement it. [config/urls.py] urlpatterns = [ path('admin/', admin.site.urls), path('scim/v2/', include('django_scim.urls', namespace='scim')), ... I would be grateful if you could give me some good advice. -
How to implement this function?
I have model Contact class Contact(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=255) appearance = models.PositiveIntegerField(default=0) def get_appear(self): self.appearance += 1 where appearance is how match I'm browsing this endpoint my views.py is : class ContactView(generics.RetrieveAPIView): queryset = Contact.objects.all() serializer_class = ContactIdSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() instance.get_appear() serializer = self.get_serializer(instance) return Response(serializer.data) serializers.py: class ContactIdSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = ['id', 'name', 'phone', 'address', 'appearance'] Problem is when I go to my id : http://127.0.0.1:8000/api/v1/contacts/3/ every time appearance should increase by 1 , but this value always equals 1 and value of appearance in db always equals 0 -
Django/react Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
I am building a website using django as purely a server and React. I am getting the error Access to XMLHttpRequest at 'http://localhost:8000/dividends/current_yield/hd' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. so far i've tried Redirect is not allowed for a preflight request and "No 'Access-Control-Allow-Origin' header is present on the requested resource" in django I added corsheaders to my installed apps in django, and still no luck my app.js looks like import React from 'react'; import SearchBar from './SearchBar'; import axios from 'axios'; class App extends React.Component { onSearchSubmit(term) { axios.get('http://localhost:8000/dividends/current_yield/hd', { // params: {query: term}, headers: { // Authorization: 'Client-ID *YOUR KEY HERE*' // "Access-Control-Allow-Origin": "*", } }).then(response => { console.log(response.data.results); }); } render() { return ( <div className="ui container" style={{marginTop: '10px'}}> <SearchBar onSubmit={this.onSearchSubmit} /> </div> ) } } export default App; my views looks like def current_dividend_yield_view(request, ticker): yahoo_stock_obj = yfinance.Ticker(ticker.upper()) price = get_current_price(yahoo_stock_obj) dividends = get_all_dividends(yahoo_stock_obj) current_yield = get_current_dividend_yield(price, dividends) current_yield_object = {'current_yield': current_yield} data = json.dumps(current_yield_object) return HttpResponse(data, content_type='application/json') my settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dividends_info.apps.DividendsInfoConfig', 'corsheaders', ] MIDDLEWARE = [ … -
How to import parent template except for its overriden content in django templates?
I'm trying to extend two nested blocks from a parent template in a child template. It goes like this : parent.html {% block parentBlock %} <span> Foo </span> {% block rowBlock %} <button ...> Button here </button> <button ...> Another button here </button> {% endblock rowBlock %} <div> Some other content </div> {% endblock parentBlock %} child.html {% extends 'parent.html' %} {% block parentBlock %} {{ block.super }} # --> See note n°1 below {% block rowBlock %} {{ block.super }} <button ...> A third button that extends the 2 others </button> {% endblock rowBlock %} <div> Content that extends parentBlock from parent.html </div> {% endblock parentBlock %} Note n° 1: Problem is that the child's block.super on parentBlock marked as Note 1 will do a super that includes the new rowBlock and appends the new one one more. Result is like this : <span> Foo </span> <button ...> Button here </button> <button ...> Another button here </button> <button ...> A third button that extends the 2 others </button> <button ...> Button here </button> <button ...> Another button here </button> <button ...> A third button that extends the 2 others </button> <div> Some other content </div> <div> Content that extends … -
Production deployable, scalable and managed solution from Heroku
I explored most of the options available in Heroku and none of them has a feasible and managed plan for Django based eCommerce web application. We basically don't want to manage the infrastructure and configurations, but would like to focus on coding and deploy it on a managed solution that is feasible to us. Currently we have the following software stack on a development server and we would like to find a Heroku managed solution, yet scalable and production deployable. Linux OS Postgres Python 3.10 Django latest ( with and without REST APIs) Vue.js Gunicorn Nginx Let's Encrypt or any SSL Redis Celery Github Jenkins CI/CD (the code is automatically deployed on the development server by running a Jenkins job) Integrated API: Stripe, Twilio, Google and etc. Best regards -
Django template forloop values in jquery
I am using Django for a question and answer project. I have a template with multiple answers and, for each answer, I have a "Comment" button to toggle a textarea where I can add a comment to the answer itself. My problem is, I can just toggle the first "comment" button, because jquery gets the first item as unique id. I post some code to be more clear: template {% for answer in answers %} <div class="col-1"> <div style="text-align: center"> <a title="Dai un voto positivo" href="" class="btn btn-lg"><i class="fas fa-arrow-circle-up"></i></a> <br> <span>{{ answer.count_all_the_votes }}</span> <br> <a title="Dai un voto negativo" href="" class="btn btn-lg"><i class="fas fa-arrow-circle-down"></i></a> <br> {% if request.user == question.post_owner %} <a title="Accetta questa risposta come corretta" href="" class="btn btn-lg"><i class="fas fa-check"></i></a> {% endif %} </div> </div> <div class="col-11"> {{ answer.body|safe }} <br> <div class="mt-3"> {% if request.user == answer.answer_owner %} <a href="">Modifica</a> {% endif %} &nbsp;&nbsp;&nbsp; <a href="">Segnala</a> </div> <hr> {% for comment in answer_comments %} {% if comment.answer.id == answer.id %} <small>{{ comment.comment }} - <a href="">{{ comment.commented_by }}</a> {{ comment.created_at }}</small> <hr> {% endif %} {% endfor %} <button class="btn btn-link" id="ans_show_button{{answer.id}}">Commenta</button> <input type="hidden" name="" value="{{answer.id}}"> <div class="col-6"> <form action="{% url 'questions:add_answer_comment' pk=answer.id %}" method="post"> {% … -
What is the difference between timezone.now and db.models.functions.Now?
Can anyone explain the difference between 'django.db.models.functions.Now' and 'django.utils.timezone.now'? For example, am I correct that functions.Now() returns the system time without timezone stamp, and timezone.now() would return UTC timestamp? When I use print(timezone.now()) I get the expected timestamp however when I print(functions.Now()) I get a blank string. Why is this? In what circumstances is it appropriate to use one method over the other? -
circular import error in django rest framework
I have two custom modules in the root project folder: root/setting.py root/utils/custom_exception.py root/custom_authentication.py I am importing from rest_framework import exception_handler, from rest_framework.exceptions import APIException in the custom_exception.py module. When I import CustomExceptionClass from custom_exception.py in custom_authentication.py, I get a cyclical import error: ImportError: cannot import name 'exception_handler' from partially initialized module 'rest_framework.views' (most likely due to a circular import) However when I import the same exception class inside the authenticate method , the error is gone. Does anyone know why I am not able to import globally? -
Django large file uploads to s3 on heroku
For the love of god can we get a solution for uploading large files to Amazon s3 bucket on heroku? I have been through everything on the net and no working solutions or clear documentation. Meanwhile YouTube uploading hour long HD videos!!!! Please only people with experience or success in uploading large 20 minute videos to there app answer. Don’t want people with no experience references other broken answers. By the way my website is www.theraplounge.co/ and we can’t get large file uploaded for nonthing. (Boto3, these s3-direct widgets) you name it. -
Returning a Crispy Form as response to ajax request
i am trying to fill a form with data via ajax request. The is my attempt so far: view.py: def ajaxGetData(request): pnr=int(request.GET.get('pnr',None)) instance=User.objects.get(pnr=pnr) form=User_Form(instance=instance,prefix="Userdata") return HttpResponse(form.as_p()) Ajax Code: $.ajax({ url: '{%url 'ajaxGetData'%}', type: "get", data: { 'pnr': pnr, }, success: function (data) { if (data) { $('#Userdata-Content').html(data); } } }); It does work, but the form is not rendered with crispy-forms. Is there some code like return HttpResponse(form.as_crispy()) That would return a crispy form? PS: I am quite new to Django and developing websites in general. I want to do a website where you can select a user from a list at the side of the page and then edit a whole bunch of data about him. From what i read doing a one-page-solution was the way to go for that. Would be quite thankful if someone can give me a hint if this is the right way to go about it. Greetings! -
Django Rest Framework - One serailizer for API and drf-spectacular
I have a serializer for DRF, and drf-spectacular. My serializer works that i expect but in GUI don't present currectly. So i need to have tho diffrents serializer one for schema and second for endpoint. But i wanna use one, how to fix this ? My serializer: class GetConversionCasesSerializer(serializers.Serializer): conversionId = serializers.SerializerMethodField() cases = serializers.SerializerMethodField() def get_cases(self, obj): serializer = ResultDataSerializer(ResultData.objects.filter(conversion=obj), many=True) data = serializer.data return data def get_conversionId(self, obj): return obj.id Schema serializer: class GetConversionCasesSerializerSchema(serializers.Serializer): conversionId = serializers.IntegerField() cases = serializers.ListSerializer(child=ResultDataSerializer()) Api endpoint: @extend_schema(request=None, responses=GetConversionCasesSerializerSchema()) def get(self, *args, **kwargs): if self.request.version == "v1": conversion_id = self.kwargs.get('conversion_id') instance = Conversion.objects.get(id=conversion_id) serializer = GetConversionCasesSerializer(instance) serializer.data['c1'] = 'test' return Response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) When i use to show schema normal selialiser i have: in schema serializer: How to fix first serializer and have one for schema and get method ? -
Как хранить и отображать параметры сайта (то есть какие-то числа, не связанные с работой django, для моих скриптов) через админку?
Можете подсказать где хранить такую информацию (в базе данных через модели django или как-то по-другому) и как сделать переход к ним в админке. Буду очень благодарен. -
Django: How to stop django session from expiring in django?
I have written a logic where a referer would get some point when the person they refered buy a package. Now the problem with this is that when i refer someone and they sign up and also buys a package immediately i the referer gets some point when after sometime maybe a day, if they buys another package i do not get any point again. In this case i feel like a session is timing out or something, but i cannot really tell what the problem here it. this is the code that gives me (or any user that refered someone) some point when the person they refered buy some package views.py profile_id = request.session.get('ref_profile') if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) print("Profile Id Is" + str(profile_id)) recommended_by_profile.indirect_ref_earning += 250 recommended_by_profile.save() else: print("Profile ID is None and no point where given") THis s my registerRef view that signs-up a user and detects the person who refered them def registerRef(request, *args, **kwargs): profile_id = request.session.get('ref_profile') print('profile_id', profile_id) code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile … -
geodjango spatial lookup failure Only numeric values of degree units are allowed on geographic DWithin queries
So I'm building Django app which has some stores saved with coordinates in db, all I need to do, when I get user coordinates, I want to search in db for the nearest store, IDk what to do after receiving coordinates eveything raises error tried this hard coded query lookup Shop.objects.filter(location__dwithin = (GEOSGeometry(Point(-95.23592948913574, 38.97127105172941)), D(km=5))) but still getting errors like Only numeric values of degree units are allowed on geographic DWithin queries. the srid if it matters is 4326, idk even know what this is -
TimeoutError [winError10060]
This is my function for sending email, but i am getting time out error. I tried to solve my problem by disabling the proxy settings and also enabling the imap from gmail. None is helping. Plus I think less secure app option is also disabled. Correct me if I am wrong settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIl_HOST = 587 EMAIL_HOST_USER = 'my email' EMAIL_HOST_PASSWORD = '#####' EMAIL_USE_TLS = True view.py def register(request): if request.method =='POST': form = RegistraionForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split('@')[0] user = Account.objects.create_user(first_name=first_name,last_name=last_name,email=email,username=username, password=password) user.phone_number = phone_number user.save() #user activation current_site = get_current_site(request) mail_subject = 'Please activate your account' message = render_to_string('accounts/account_verification_email.html',{ 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() messages.success(request, "Registration successful") return redirect('register') else: form = RegistraionForm() context={ 'form':form, } return render(request, 'accounts/register.html',context) -
How can i update quantity in the django cart?
model.py class OrderItem(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.IntegerField() date_added = models.DateTimeField(auto_now_add=True) if request.method == "POST": customer = request.user.customer order ,created = Order.objects.get_or_create(customer=customer,complete=False) id = request.POST.get('id') product = Product.objects.get(id=id) if OrderItem.objects.filter(product=product): orderitem = OrderItem.objects.filter(product=product) orderitem.quantity+=1 order.save() else: orderitem = OrderItem.objects.create(product=product,order=order,quantity=1) products = Product.objects.all() return render(request, "HTML/index.html",{'products':products}) Error QuerySet' object has no attribute 'quantity' I'm trying to a cart if an item exists in this cart, the system should update its quantity, if not then a new item should be created in the cart, how can i do that? -
Repeated syntax errors while guy in tutorial is getting none
I am new to coding, and am following a tutorial on how to make a forum website. I am instructed to enter two lines of code into the VScode terminal, which are: $ git clone https://github.com/SelmiAbderrahim/AutoDjango.git $ python AutoDjango/AutoDjango.py --venv The first one works fine and clones everything into my workspace, but for the second line I keep getting syntax errors. The first one was for line 43, which was: <h1 class="text-5xl">Django + Tailwind = ❤️</h1> So I took out the heart assuming it was that, but then I just got one for line 44 which was: </section> If anybody knows how to fix this, it would be much appreciated as I have spent days on this project and don't want it to end because of this problem. Here is the tutorial video with the timestamp: Tutorial -
How do I pass django variables to javascript in a for statement?
How do I pass django variables to javascript in a for statement I want to pass c.tv.tv_id in a for statement in javascript. I want to pass it to javascript in each for statement, but I don't know how to do it. {% extends 'base.html' %} {%load static%} <link rel="stylesheet" href="{% static 'css\common_movie_tv.css' %}"> {% block content %} <table> <tr> <tr> <th>name</th> <th>created_at</th> <th>comment</th> <th>evaluation</th> </tr> {% for c in object_list %} <tr> <th id = "trendings"></th> <td>{{ c.user.nickname }}</td> <td>{{c.tv.tv_id}}</td> <td>{{ c.created_at }} </td> <td>{{ c.comment }}</td> <td><h2 class = "rate" style="--rating:{{c.stars}}">{{c.stars}}</h2></td> </tr> {% endfor %} </table> <script> const tv_id = {{c.tv.tv_id}} fetch(`https://api.themoviedb.org/3/tv/${tv_id}?api_key=${TMDB_API_KEY}&language=en-US`, { method: "GET", headers: { "Content-Type": "application/json" } ) .then(res => res.json()) .then(data => { var mainDiv = document.createElement("div"); mainDiv.setAttribute("class", "card"); mainDiv.setAttribute("style", "width: 18rem;"); var img = document.createElement("img"); img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.poster_path); img.setAttribute("class", "card-img-top"); img.setAttribute("alt", "..."); var body = document.createElement("div"); body.setAttribute("class", "card-body"); var title = document.createElement("h5"); title.setAttribute("class", "card-title"); if (data.name) { title.innerHTML = data.name; } else { title.innerHTML = data.title; } //var text = document.createElement("p"); //text.setAttribute("class", "card-text"); //text.innerHTML = data.results[i].overview; var link = document.createElement("a"); link.setAttribute("href", "/" + "tv" + "/" + data.id + "/"); link.setAttribute("class", "btn btn-primary"); link.innerHTML = "View Details"; body.appendChild(title); //body.appendChild(text); body.appendChild(link); mainDiv.appendChild(img); mainDiv.appendChild(body); … -
Django app deployment on heroku compiled slug size is too large
So i am deploying my django application which consists on a reural network model used for fungus classification. The total files on the repo wheight like 100MB but i keep getting this error: 129 static files copied to '/tmp/build_dcf9fdff/hongOS_project/staticfiles'. remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: ! Compiled slug size: 1.1G is too large (max is 500M). remote: ! See: http://devcenter.heroku.com/articles/slug-size remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: e8bac23bbcb75c7d2773ba8eecf5613182f0a4ac remote: ! remote: ! We have detected that you have triggered a build from source code with version e8bac23bbcb75c7d2773ba8eecf5613182f0a4ac remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to hongos-heroku. remote: To https://git.heroku.com/hongos-heroku.git ! [remote rejected] develop-heroku -> main (pre-receive hook declined) error: fallo el … -
icontains unable to search certain words from a field that uses richtext field - Django
I made a search function in my project where a user can enter a query and a number of fields will be searched before sending a response with the data filtered. As usual I am using icontains in the views for making the queries in my model. I copied certain words directly from a field that uses ckeditor to the searchbar to see if it works. What I have noticed is it is unable to match certain that are in bold form. In the image for example if I search the words arbitration agreement no data is returned but as you can see the words exists in the field. This is happeing with all the bold words. Please help me to solve the problem as I am unable to understand as to why this is happeing. Below is the view that deals with the search functionality. Using ckeditor for the field. views.py def search_citation(request): q = request.data.get('q') print(f'{q}') if q is None: q = "" if len(q) > 78 or len(q) < 1: return Response({"message":'not appropriate'}, status=status.HTTP_200_OK) try: judge_name = Civil.objects.filter(judge_name__icontains = q) case_no = Civil.objects.filter(case_no__icontains = q) party_name = Civil.objects.filter(party_name__icontains = q) advocate_petitioner = Civil.objects.filter(advocate_petitioner__icontains = q) advocate_respondent = …