Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send multiple objects on serializers.Serializer (got non_field_errors)
I'm trying to send multiple data through a create viewset method to a serializer. However when doing that I get an error as follows: enter image description here Im using many attribute into the serializer, but I sill get the same error. I'm posting data like this: [ { "weekday":"day", "start_time":"time", "end_time":"time" }, { "weekday":"day", "start_time":"time", "end_time":"time" } ] This is the viewset and serializer code: viewset.py class SpecialistAvailabilityView(viewsets.ModelViewSet): model = SpecialistAvailability permission_classes = [IsAuthenticated, IsSpecialist] def get_serializer_class(self): saving_actions = ["create", "update", "partial_update"] if self.action in saving_actions: return WeekDayTimeSerializer return SpecialistAvailabilitySerializer def get_queryset(self): queryset = SpecialistAvailability.objects.filter( specialist__user=self.request.user ).order_by('-start_time__week_day') return queryset def translate_availability(self, data): pass def create(self, request, *args, **kwargs): serializer = WeekDayTimeSerializer(data=request.data, many=isinstance(request.data, list)) print(serializer.initial_data) print(serializer.is_valid()) if serializer.is_valid(): self.translate_availability(serializer.validated_data) return super().create(request, *args, **kwargs) serializer.py import pytz from datetime import datetime from rest_framework import serializers from apps.specialist.models.specialist_availability import SpecialistAvailability from apps.specialist.utils import WEEKDAYS class WeekDayTimeSerializer(serializers.Serializer): weekday = serializers.ChoiceField(choices=WEEKDAYS, required=True) start_time = serializers.TimeField() end_time = serializers.TimeField() # TODO ADD TIME AND WEEKDAY CHECKING # START TIME MUST BE LESS THAN END TIME # JUST ONE DAY MUST BE SENDED IF MANY def validate(self, attrs): self.validate_start_time(attrs['start_time']) self.validate_start_time(attrs['end_time']) self.validate_end_time return super().validate(attrs) def validate_start_time(self, start_time): try: datetime.strptime(start_time, "%H:%M") except: raise serializers.ValidationError("Wrong time format") return start_time … -
Django payment intigration
i want to add a donation page in my DJango project but i have not seen any proper intigration of payment gateway in any articles and videos so plzz help me and give the proper code and explanation. in stripe apy key is not supported in india in razorpay when click on payment error occur amount exceed -
django rest framework: Getting "This field may not be null." with FloatField even with blank=True
Here dummy code to show my problem: In my django models.py I have something like: class MyModel(Model): test_field = SlugField(blank=True, null=False) # some other not-null not-blank fields here def save(self, *args, **kwargs): self.test_field = .... # Setting with a value calculated form the other not-null not-blank fields Here my serializer: from rest_framework import serializers class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [ ...., 'test_field', ] In my views.py something like: def post_endpoint(request): data = JSONParser().parse(request) serializer = MyModelSerializer(data=data) if serializer.is_valid(): .... serializer.save() return JsonResponse(serializer.data, status=201) This is working as expected: I can send an object to my post_endpoint without my test_field and I get my result with test_field set as expected. serializer.is_valid() returns True in that case. The problem? I need that same functionality but with a FloatField instead of SlugField. But I noticed serializer.is_valid() returns False in that case and I get a "This field may not be null." in serializer.errors in my view function. How is FloatField different from SlugField ? How can I get the expected functionality also with FloatField? djangorestframework==3.14.0 Django==4.0.5 -
Browser not downloading request response, even though Content-Disposition is 'attachment' and Content-Type is 'text/plain'
I am under the impression that if Content-Disposition is set to 'attachment' and Content-Type is set to'text/plain', the browser should download the request response as a .txt, but when I make the request locally on my browser, a download is not initiated. On other pages, like https://textdoc.co/, my browser does download a similar request response, so it doesn't seem like a browser issue. On my server: from django.http import FileResponse ... with open('readme.txt', 'w') as f: f.write('Create a new text file!') response = FileResponse(open("readme.txt", "rb"), as_attachment=True, filename="test.txt") response['Content-Type'] = 'application/download' return response After making this request on my client I get the following results in the google chrome developer console: **Response Headers:** Access-control-allow-origin: http://localhost:3000 Allow: POST, OPTIONS Content-Disposition: attachment; filename="test.txt" Content-Length: 23 Content-Type: application/download Cross-Origin-Opener-Policy: same-origin Date: Thu, 08 Jun 2023 21:46:37 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.11.3 Vary: Accept, origin X-Content-Type-Options: nosniff X-Frame-Options: DENY **Response:** Create a new text file! I was expecting this request to cause the browser to prompt the user to download the file. However, the browser is not prompting the user. Here is an example of what the prompt looks like on Google Chrome: -
request.POST.get() is returning nothing
The problem is though I am putting correct data in the form, it always redirects to the except block of views.py I tried to change and refresh data in the database but didn't work out. Here is my views.py @login_required(login_url='login') def card_payment(request): card_no = request.POST.get('cardNumber') pay_method = 'Debit card' MM = request.POST['MM'] YY = request.POST['YY'] CVV = request.POST['cvv'] request.session['dcard'] = card_no try: balance = Cards.objects.get(Card_number=card_no, Ex_month=MM, Ex_Year=YY, CVV=CVV).Balance request.session['total_balance'] = balance mail1 = Cards.objects.get(Card_number=card_no, Ex_month=MM, Ex_Year=YY, CVV=CVV).email if int(balance) >= int(request.session['pay_amount']): # print("if ma gayu") rno = random.randint(100000, 999999) request.session['OTP'] = rno amt = request.session['pay_amount'] username = request.user.get_username() print(username) user = User.objects.get(username=username) mail_id = user.email print([mail_id]) msg = 'Your OTP For Payment of ৳' + str(amt) + ' is ' + str(rno) # print(msg) # print([mail_id]) # print(amt) send_mail('OTP for Debit card Payment', msg, 'nafibinnoor@gmail.com', [mail_id], fail_silently=False) return render(request, 'OTP.html') return render(request, 'wrongdata.html') except: return render(request, 'wrongdata.html') HTML form for this view <form action="pessanger_detail_def/card_payment" method="POST" class="creditly-card-form agileinfo_form"> {% csrf_token %} <section class="creditly-wrapper wthree, w3_agileits_wrapper"> <!--<label>Name On Card</label></br> <input type="text" class="pipo1" placeholder="John smith" name="name"></br>--> <label>Card Number</label> <input type="text" class="pipo1" placeholder="**** **** **** *****" name="cardNumber"></br> <label>CVV</label></br> <input type="text" class="pipo1" placeholder="***" name="cvv"><br> <label>Expiration Date</label></br> <input type="text" class="pipo2" placeholder="MM" name="MM"><label> </label><input type="text" class="pipo2" placeholder="YY" … -
Trying to write a django query to count different rows and find the max value
I have a django app that stores documents (photos, pdfs, video, ect.) as well as some metadata (year, decade, etc.). The metadata is stored in a JSONField called metadata in a model called DocumentMetaData. I would like to create a django query that allows me to find the maximum number of documents for a certain metadata name. For example, all documents have in their metadata field a "Decade" value. I can loop through all the decades to find the decade with the most documents, like this: decades = ['1860', '1870', '1890', '1900', '1910', '1920', '1930', '1940', '1950', '1960', '1970', '1980', '1990', '2000','2010', '2020'] max_count = 0 max_decade = "" for decade in decades: count = DocumentMetaData.objects.filter(metadata__has_key='Decade').filter(metadata__Decade=decade).count() if count > max_count: max_count = count max_decade = decade Can I replace this code with a django query using annotate and aggregate? I am just not seeing how to create a query with a loop in it. Thanks! -
Workbox service worker only registering routes when CORS is turned off
I have a django/react app that is trying to use a service worker to allow precaching and offline operations. Specifically, I am using Workbox. It's actually working fairly well, except the ability to work offline. The service worker's file is located, the service worker installs without issue, and even precaches all necessary files. When I start in a chrome browser with all history/cache emptied, it starts up decently Service worker is installed on application tab: Manifest is present on the application tab And we even have precached files on the application tab. There is a log in the console from workbox that says six files are precached However, if we reload the page (which is necessary to get the routing) Workbox does not detect any routes And it doesn't work when you set it to offline in the network tab HOWEVER, if I disable web security/CORS in chrome with this command "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir=%LOCALAPPDATA%\Google\chromeTemp Everything else works the same, just the registering of routes and offline operations works fine. The service worker starts, installs, and precaches the same. The manifest is detected. But, on second load, the console logs that workbox has routes, and that they match the requests. … -
Django, how to do two-factor authorization via email?
I have a website and I have already redefined the user model, made authorization/registration via email. Now I want to do authorization when a user enters a username, password and a confirmation code is sent to his email. I am interested in the scheme of work. I see it this way: vyushka generates code using random, send_email sends it and this very code is written to the database. In my opinion, this is a bad decision (For example, to store the code in the database with the user, because you still have to implement the expiration date, etc.). So, are there any options for how this can be done. (generate code, where and how to store it for verification). I know about all sorts of libraries with 2FA, this is not my option. -
Django channel web socket to console.log() to the Browser
I am using npm wscat package to to send the message to django channels, when the message is sent through the terminal, it prints on the server console as expected, how ever when I send it to the browser the console is not logging the message following is my working code: #consumer.py from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): message_content = text_data print(message_content) self.send(text_data=message_content) #routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()), ] #index.html ... <script> let chat = null; function connect() { chat = new WebSocket("ws://localhost:8000/ws/chat/") chat.onopen = function (e) { console.log("Successfully connected to the WebSocket."); } chat.onmessage = function (result) { console.log(result.data); } chat.onerror = function (err) { console.log("WebSocket encountered an error: " + err.message); console.log("Closing the socket."); } chat.onclose = function (event) { console.log('WebSocket connection closed.'); }; <!-- --> } connect(); </script> ... In the brower chat.onopen function works perfectly, and is diplayed in the browser, however for some reason chat.onmessage function never gets executed. -
How call an API from Django before creating an object
I'm currently learning the Django framework, and I have a Account model. I want to retrieve data from an external REST API to populate the fields of this model. Here's an example: class Account(models.Model): external_id = models.CharField(max_length=60) account_id = models.CharField(max_length=60) puuid = models.CharField(max_length=85) name = models.CharField(max_length=20) def __str__(self) -> str: return "{} (id: {})".format(self.name, self.external_id) @classmethod def create(cls, nickname): # Here I would like to call the external API in order to recover some of those fields. account = cls(external_id = '', account_id = '', puuid = '', name = nickname) return account I can simply import the requests library here, make API calls, and it will work. However, I would like to know the correct way to do it. I assume that I should create a services.py file and implement the API call logic there, but I'm unable to find a style guide. Is there any convention? -
Can you side-load relations in a Django Rest Framework response?
I have an API endpoint that needs to return many thousands of results that share relations. I would like to return the ID on each result and then return a second set of data containing each of the relations (rather than repeating the relations on each result). What's the best way to go about side-loading relations? -
How can I add relation values to a serializer in Django Rest Framework?
I would like to return many thousands of results along with one attribute from a relation. I tried including the value in the fields array but got the following error: Field name checklist__location__latitude is not valid for model Sighting. Is there a way to add the latitude value to each sighting object? I'm cautious of adding too much overhead to the returned results (they could get very large, so I want the JSON to be as minimal as possible), and I don't want to iterate over every object to attach the value after retrieval from the database. -
Not getting specific object using foreign key relationship in django
I am facing an issue where iam trying to get an Egg item object by using foreign key relationship but it again and again show me this error "Some Error Occurred While Saving Data: Egg matching query does not exist." My models are: class SaleReturnItem(models.Model): salereturn = models.ForeignKey( SaleReturn, on_delete=models.CASCADE,related_name="salereturnitem" ) saleReturnItemName=models.ForeignKey(Egg, on_delete=models.CASCADE, related_name='salereturnitemegg',null=True) saleReturnItemQuantity=models.CharField(max_length=15,null=True) saleReturnItemUnitPrice=models.CharField(max_length=15,null=True) saleReturnItemTotalAmount=models.CharField(max_length=15,null=True) saleReturnItemDiscount=models.CharField(max_length=15,null=True) saleReturnItemDiscountPrice=models.CharField(max_length=15,null=True) class Egg(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE,default=1 ) eggName = models.TextField(null=True) eggInSection = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='eggsection',default=1) eggSalePrice = models.CharField(max_length=15,default=False) eggPurchasePrice = models.CharField(max_length=15,default=False) eggStockLimit = models.IntegerField(default=False) eggStockQuantity = models.IntegerField(default=False) eggInCategory = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='eggcategory',default=1) eggExpiryDate = models.DateField(blank=True, null=True) eggGst = models.DecimalField(max_digits=5, decimal_places=2,default=False) and my view function is this def saleReturn(request): if not request.user.is_authenticated: return redirect('login') elif request.user.userRole != 'admin': return render(request, 'pages/404.html') else: if request.method == "POST": try: searchSaleInvoiceId = request.POST.get('searchSaleInvoice') searchSaleInvoice = SaleInvoice.objects.get(id=searchSaleInvoiceId) invoiceDateSaleReturn = request.POST.get('invoiceDateSaleReturn') saleReturnObject = SaleReturn( user=request.user, searchSaleInvoice=searchSaleInvoice, invoiceDateSaleReturn=invoiceDateSaleReturn, ) saleReturnObject.invoiceDateSaleReturn = date.today() saleReturnObject.save() print("saleReturnObject",saleReturnObject) saleReturnItemNameId = request.POST.get('saleReturnItemName') saleReturnItem = Egg.objects.get(eggName=saleReturnItemNameId) print("-----------------1----------------------") saleReturnItemNameId = saleReturnItem.id saleReturnItemQuantity = request.POST.getlist('saleReturnItemQuantity') saleReturnItemUnitPrice = request.POST.getlist('saleReturnItemUnitPrice') saleReturnItemDiscount = request.POST.getlist('saleReturnItemDiscount') totalSaleAmountSaleReturn = 0.0 saleInvoiceAmountSaleReturn = 0.0 saleInvoiceDiscountSaleReturn = 0.0 for saleReturnItemNameId,quantity, price, discount, in zip(saleReturnItemNameIds, saleReturnItemQuantity, saleReturnItemUnitPrice, saleReturnItemDiscount ): saleReturnItemName = next(item for item in saleReturnItemNames if item.id == int(saleReturnItemNameId)) total_amount = int(quantity) * … -
Run a "always on" redis keyspace event listener with django
I have deployed a django application on an EC2 instance. I have used NGINX as the reverse proxy and gunicorn as the WSGI server to serve requests from the django app. As part of a functionality within the app, I want to listen to redis keyspace notifications on expiry of certain keys (which match a given pattern) and upon receiving the expiry event, perform something (write something to the database). This would require a piece of code (redis-listener) to be constantly running alongside my django app to listen to any incoming redis event. I am not able to arrive at an optimal implementation for this listener. One approach is that I can use threading to run the listener in a separate thread than the main django app thread (by running the listener in a new thread inside the ready() method) but then for each incoming request, gunicorn will create or assign a new worker process with its own instance of the django app and the listener thread. So, I end up running as many redis listener threads as there are active incoming requests. And each redis event will be effectively listened multiple times simultaneously, which is not what I want. … -
Using fuzz.ratio on Django object field confusion
I think this is a simple issue but I'm a little confused on the syntax for doing this. I have a Django model called Sentence which is exactly what it sounds like, just the text of a single sentence (related to a location model but that is irrelevant for this). Here is the model: class Sentence(models.Model): location = models.ForeignKey( Location, related_name="sentences", on_delete=models.CASCADE ) text = models.TextField() def __str__(self): return self.text In a view in views.py related to this model, I first filter so only sentences that contain words from a user query are kept. queryset = Sentence.objects.filter(text_icontains=query) I want to then sort these sentences in the queryset by a score given to them in relation to a query from the user using fuzz ratios (assume query is already established to be a string): queryset = queryset.annotate(score=fuzz.partial_ratio(query, '[CONFUSED HERE]')).order_by('-score') but I am having trouble figuring out how to compare this string query from the user to the text within each of the sentence objects, if that is something that is possible. Ideally, this would make the queryset be ordered by this fuzz ratio so the first value in the queryset is the sentence with the highest match to the user's query. … -
How to serialize two related models in Django
I have two model: class Liver_Function_Tests(models.Model): blood_lab=models.ForeignKey(Blood_Lab,on_delete=models.CASCADE,null=True, related_name='liver_function_tests') class Blood_Lab(models.Model): patient=models.ForeignKey(Patient,on_delete=models.CASCADE,null=True) I have created serializer for Liver_Function_Tests model class Liver_Function_Tests_Serializer(serializers.ModelSerializer): class Meta: model=Liver_Function_Tests fields = '__all__' Now, I need to include this serializer into Blood_Lab_Serializer class Blood_Lab_Serializer(serializers.ModelSerializer): liver_function_tests_details = Liver_Function_Tests_Serializer(source='liver_function_tests.last', required=False) class Meta: model=Blood_Lab fields = ['id','patient', 'liver_function_tests_details'] The problem is, when creating Blood_Lab I have to assign the blood_lab forign_key that is not created yet, http://127.0.0.1:8000/api/bloodlap/ What is possible solutions to this problem ? -
Randomly select from database using datetime in Python Django
I am making a project in Django right now that needs to select a daily item from the database (it's like a Wordle type of project). I have a database of 100 items and I want every user who visits the site to see the same daily item. I tried to do some logic of converting a date to an integer to index the database, but it got clunky and I figured there must be a better way to do this. The goal is to select from the database based on datetime.now and have it return one unique row. After the database has been used up it will just reset and start over again. I also considered having a daily job run every day to update the database with a 'todaysItem' flag but I don't think that is the best solution. -
Django: how to get a URL view name from a request?
In Django url configs, you can use url "view names" to aid various activities like redirects. Seen here in this example urls.py file (the final name arguments): urlpatterns = [ path('', views.home_view, name='home'), path('search/', views.search_view, name='search'), .... Now, in my Django view function, I would like to inspect the current request object to discover the current url "view name" for the current request. This could be useful to create a general-purpose "handler" function that could be called from multiple views (or better yet to use in a view decorator). This would allow your general purpose function to redirect to the current page on a POST request for example. But to redirect via redirect() requires knowing the "view name" you want to redirect to. How can I find the "view name" by inspecting the current request? -
checkbox becomes unchecked when another checkbox becomes checked django
I have two checkboxes , in two different HTML forms. In my template , i made that when a checkbox is clicked , its value gets submitted to the view function and saved to the database and then that checkbox becomes an icon using an if else statement. Like that: <form id='ISBN_form' action="{%url 'tracker:bookSteps' book_page.id%}" method="POST"> {% csrf_token %} <div class="columns is-mobile"> {% if book_progress.ISBNsent == 'True' %} <div class="content column is-5"> <label class="checkbox" dir="rtl"> <i class="fa-solid fa-check has-text-success"></i> تم التسليم </label> </div> {%else%} <div class="content column is-5"> <label class="checkbox" dir="rtl"> <input type="checkbox" name="ISBNsent" id="ISBNsent" value="True" onchange="submitCheckbox();"> تم التسليم </label> </div> {%endif%} </form> That works great and the value gets saved to database and it becomes an icon in the html page. But the problem is that when i check a checkbox the other one becomes unchecked and vice versa , only in the html template but in the database it stays checked. I don't know where the problem is and why this behavior is happening while i have the if else and the value that is being checked is from the database so why it gets unchecked again? my view function: def bookSteps(request,book_id): book_page = get_object_or_404(Book, pk=book_id) print(book_page.id) book_progress … -
How do i change translation values in Django wagtail?
How can I change some of the translations in wagtail which I don't like (or add new ones)? My first attempt was to change values in the wagtail/locale/{language-code}/django.po files, then to recompile them in .mo files, hoping to change translations, but this didn't work. Image -
Django library upload
not taking the created module and shows error enter image description here I am creating a website through django but when i tried to push data in the database it shows error in taking the module. And when i changed the name in module then it shows duplicate names mot allowed. enter image description here Github Repo link: https://github.com/Prakhar2706/Django_first_project -
Python and Django: How do I dynamically create a dynamic URL with employee ID
I have a specific template that can filter an activity logs of an Employee. This is my view: @login_required def activity_filter(request, buyer_id): """Returns activities based on the filter options sent by an (AJAX) POST.""" template_name = 'buyer/activity/activities.html' activities = _compile_activities(request.user.cached_buyer, request.user.cached_buyer_role.privacy_filter) year_range = list(range(activities[0].date_created.year, activities[len(activities) - 1].date_created.year - 1, -1)) form = _ActivitiesFilterForm( buyer_id=buyer_id, data=request.POST, user_choices=_compile_activity_users(activities), from_date=activities[len(activities) - 1].date_created, to_date=activities[0].date_created, from_to_year_range=year_range, ) if not form.is_valid(): _logger.debug("Filter validation errors: %r", form.errors) return render(request, template_name, status=400) query_params = getattr(request, request.method) # either the request.GET or request.POST dict from_date = query_params.get('from_date', None) if from_date: from_date = datetime.combine(from_date, datetime.min.time()) # first second of the day activities = activities.filter(date_created__gte=from_date) to_date = query_params.get('to_date', None) if to_date: to_date = datetime.combine(to_date, datetime.max.time()) # last second of the day activities = activities.filter(date_created__lte=to_date) selected_users = query_params.getlist('users', None) if selected_users: user_role_ids, user_role_types = _get_selected_user_role_details(selected_users) if user_role_types and user_role_ids: activities = activities.filter(user_role_type__in=user_role_types).filter(user_role_id__in=user_role_ids) if ( query_params.getlist('users') ): print("===selected_users===\n", query_params, "\n===selected_users===\n") context = { 'activities': activities[:MAX_NO_OF_ACTIVITIES], 'activities_search_form': form, } if is_ajax(request): return render(request, 'buyer/activity/activities_table.html', context) return render(request, template_name, context) <a href="{% url 'buyer:activity' employee.buyer_id %}"> {% svg_icon "Activity" "w-6 h-6 dui-stroke-primary" None "Latest Activity" %} </a> But I need this icon(URL) <a> tag once clicked it will redirect and automatically filtered on my Latest … -
NotFittedError at /classify/ Vocabulary not fitted or provided
I am trying to build a spam classifier. However, when sending a POST request, I am getting the error "NotFittedError: Vocabulary not fitted or provided". How can I solve this issue? My POST request looks: { "email":"Get free v-bucks. For that click on link https:/rk%jgqk@$bjg&kjraekj/youRickRolledXD" } Here my code in models.py file nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('punkt') try: wordnet.ensure_loaded() except LookupError: nltk.download('wordnet') class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear1 = nn.Linear(10000, 100) self.linear2 = nn.Linear(100, 10) self.linear3 = nn.Linear(10, 2) def forward(self, x): x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x def classify_spam(message): model = LogisticRegression() model.load_state_dict(torch.load('W:/SpamOrHamProject/SpamOrHamBack/api/AIModel/SpamClassification.pth')) model.eval() cv = CountVectorizer(max_features=10000, stop_words='english') processed_message = preprocess_message(message) vectorized_message = cv.transform([processed_message]).toarray() with torch.no_grad(): tensor_message = Variable(torch.from_numpy(vectorized_message)).float() output = model(tensor_message) _, predicted_label = torch.max(output, 1) return 'Spam' if predicted_label.items() == 1 else 'Not Spam' def preprocess_message(message): remove_non_alphabets = lambda x: re.sub(r'[^a-zA-Z]', ' ', x) tokenize = lambda x: word_tokenize(x) ps = PorterStemmer() stem = lambda w: [ps.stem(x) for x in w] lemmatizer = WordNetLemmatizer() leammtizer = lambda x: [lemmatizer.lemmatize(word) for word in x] processed_message = remove_non_alphabets(message) processed_message = tokenize(processed_message) processed_message = stem(processed_message) processed_message = leammtizer(processed_message) processed_message = ' '.join(processed_message) return processed_message And there code for my trained model: nltk.download("wordnet", "W:/SpamOrHamProject/SpamOrHamModel/nltk_data") os.listdir(r"W:/SpamOrHamProject/SpamOrHamModel/input/") data = … -
Django threading behind IIS and wfastcgi
I have a Django application that executes a lengthy task, that is controlled by Ajax on one of the app's pages. The first Ajax call creates an entry in a task table in the db, and then creates a thread that executes that task, by calling a Java app via Py4J. This sends a command to a legacy server and then regularly queries it for status and updates the task table until the task is complete. The code is as follows: # Get a PyFJ command def getMCLCmd(): gateway = JavaGateway() try: cmd = gateway.entry_point.getMCLCmd() return cmd except Py4JNetworkError as e: # maybe server not started logger.info('Py4J not started, starting it') pyserver = py4JVM() pyserver.start() # try again try: cmd = gateway.entry_point.getMCLCmd() return cmd except Py4JNetworkError as e: logger.debug('Py4J error' + e) return None class py4JVM(threading.Thread): def __init__(self): threading.Thread.__init__(self, daemon=True) self.error = None def run(self): try: process = subprocess.run(MCL_CMD, shell=True, check=True, stdout=subprocess.PIPE, universal_newlines=True) output = process.stdout logger.info(f'Py4J output: {output}') except subprocess.CalledProcessError as e: self.error = f"command return with error (code {e.returncode}): {e.output}" logger.error(self.error) # the thread class class FirstInitThread(threading.Thread): def __init__(self, task: ClientTask): self.task = task threading.Thread.__init__(self) def run(self): cmd = getMCLCmd() if cmd is None: self.task.status = 0 self.task.status_msg … -
Why is my Bootstrap checkbox always checked?
I'm using django-bootstrap for my Django project. A user of the website can create/update his posts, where one of the fields is Boolean field(is_public). The problem is, even when the user saved Boolean field as False, when he enters the update page the checkbox is checked. I first thought the data is not properly saved or passed to template, but it turns out it's not the case. Nothing is wrong with the backend logic. I checked this in my template. {{form.is_public}} Can be public. {{form.is_public.value}} <!-- Gives "False" which is correct --> So to wrap up, the value is passed correctly, but the checkbox is always checked by default. How do I solve this problem?