Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Responds to a request with an plain html page but does not load my static file
I have some html pages generated by an external tool. Now I need to take this full html file with .png file, .js file and .css file and serve it. I try path('rep/', TemplateView.as_view(template_name="output/23062020_14_32_44/Report_TC_trial_test.html")) #in urls.py #result: load html file but the other files do not from django.http import HttpResponse from django.template import loader def stet_report(request): template=loader.get_template('output/23062020_14_32_44/Report_TC_trial_test.html') return HttpResponse(template.render()) from django.shortcuts import render_to_response def stet_report(request): return render_to_response('output/23062020_14_32_44/Report_TC_trial_test.html') The same results for all my attempts As a mention, I am not allowed to modify the html file -
django time display by using timesince
i am using the django template filter tag timesince. it displays well time Greater than one minute.but when is less than one minute it showing 0 minutes ago i want it to be in seconds here is my code <p>{{ article.article_published_date| timesince |upto:',' }} ago</p> I need ouput as 20seconds ago is there any way to display any help will be appreciated Thanks in advance -
How To Create A Test User Which Inherits From User
I have the following User types: class User(AbstractUser): user_type = models.CharField(choices=USER_TYPES, max_length=255, default='student') class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) When creating a User for a functional test id usually do this: user = get_user_model().objects.create_user(username='test', email='test@example.com', password='passwordtest') EmailAddress.objects.create(user=user, email="example@example.com", primary=True, verified=True) For this test I need to create a Student, yet cant find any information on how to do this. Everything I try, such as this: user = get_user_model().objects.create_user(username='test', email='test@example.com', password='passwordtest') user = Student.objects.create(user=user) Results in errors such as this: django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'") Thank you. -
Manage multiple Django project with one Django project
I have designed website with Django that I call that consumer project. Then I deploy this project for multiple institutions. Now I want to create new Django project that act like a manager of these consumer projects. The connection between Manager Project and each consumer project has these features: Each user in Manager Project can login in consumer project. Each data that create in consumer project, send up to Manager Project and save in database. What is the best way to implement this need? -
what can i return in Django Views.py function if i dont want to return anything?
I am working on a project on Django where I am creating login authentication,I have created a function in Views.py ( login ) and I don't want to return anything, So I tried returning none, but it turns out to be an error, so what can I return instead. Thank you in advance. -
Server side storage technique of large HTML as a response to AJAX call
I have a Django backend and as a response to an AJAX call from the UI it has to respond with three different HTML divs in a JSON as shown below, { "success" : true, "data" : "<div>Some Content</div>" , "data_mobile" : "<div>Some More Content</div>", "data_tab" : "<div>Some More Content</div>", } Each of the HTML can be as long as 20000 characters, so I wanted to know what would be the best approach to store these on the server-side, in a DB, as a file or anything else? Please let me know if there is anything else required. -
django submit button not submitting
i have a html form with a submit button which is not working because i'm missing something and i don't know what. this is my view.py def articles(request): data = Artikel.objects.all() if request.method == 'POST': a_typ = request.POST('type') if a_typ == 'Raum': artikel_typ = 1; if a_typ == 'Artikel': artikel_typ = 2; if a_typ =='Raum': artikel_typ = 3; if a_typ =='Gerät': artikel_typ = 4; if a_typ =='Labor': artikel_typ = 5; bezeichnung = request.POST('bezeichnung') menge = request.POST('menge') preis = request.POST('preis') einheit = request.POST('einheit') artikel = Artikel(artikel_typ=artikel_typ, bezeichnung=bezeichnung, menge=menge, preis=preis, einheit=einheit) artikel.save() return render(request, 'articles.html', {'data': data}) def add_article(request): data = Artikel.objects.all() if request.method == 'POST': a_typ = request.POST('type') if a_typ == 'Raum': artikel_typ = 1; if a_typ == 'Artikel': artikel_typ = 2; if a_typ =='Raum': artikel_typ = 3; if a_typ =='Gerät': artikel_typ = 4; if a_typ =='Labor': artikel_typ = 5; bezeichnung = request.POST('bezeichnung') menge = request.POST('menge') preis = request.POST('preis') einheit = request.POST('einheit') artikel = Artikel(artikel_typ=artikel_typ, bezeichnung=bezeichnung, menge=menge, preis=preis, einheit=einheit) artikel.save() return render(request, 'articles.html', {'data': data}) this is the html form: <div class="card"> <div class="card-header">Artikel hinzufügen</div> <div class="card-body"> <form action="" method="post"> <!-- more elements --> <div class="card-footer"> {% csrf_token %} <button type="submit" class="btn btn-primary btn-sm" action="add_articles"> <i class="fa fa-dot-circle-o"></i> Artikel hinzufügen </button> … -
Django Autocomplete Light doesn't
I'm trying to use Django Autocomplete Light on my project follow this tutorial I have added DAL on my Django settings: INSTALLED_APPS = [ 'dal', 'dal_select2', ... ] And this is all the code affected by DAL package project/urls.py: path('app/', include((app_urls, 'app'), namespace='app')), app/urls.py: path('prueba/', app_views.prueba, name='prueba'), path('brand_autocomplete/', app_views.BrandAutocompleteView.as_view(), name='brand_autocomplete'), models.py: class Brand(models.Model): name = models.CharField(verbose_name="Nombre", max_length=100, unique=True) class Budget(models.Model): name = models.CharField(verbose_name="Nombre", max_length=100) brand = models.ForeignKey('Brand', verbose_name="Marca", related_name='budget_brand', null=True, on_delete=models.SET_NULL) forms.py: class BudgetForm(forms.ModelForm): brand = forms.ModelChoiceField(queryset=app_models.Brand.objects.all(), widget=autocomplete.ModelSelect2(url='app:brand_autocomplete')) class Meta: model = app_models.Budget fields = '__all__' view.py: class BrandAutocompleteView(autocomplete.Select2QuerySetView): def get_queryset(self): print("Brand Autocomplete") if not self.request.user.is_authenticated: return app_models.Brand.objects.none() qs = app_models.Brand.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs def prueba(request): form = app_forms.BudgetForm() return render(request, 'prueba.html', { 'form': form }) prueba.html: {% extends "base.html" %} {% load static %} {% block content %} <div> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} </form> </div> {% endblock content %} And i have this JS in base.html: <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> The result is that void dropdown input: <select name="brand" required="" id="id_brand" data-autocomplete-light-language="es" data-autocomplete-light-url="/app/brand_autocomplete/" data-autocomplete-light-function="select2"> <option value="" selected="">---------</option> </select> Anybody could help me please ? Thanks in advance. -
How to add a process bar when you waiting for a response from the server
could someone help me with one problem? I want to add a process bar when you waiting for a response from the server (Django 3.x). Step to reproduce: On the page 'A' we have the form. Enter data to form. Submit POST request by clicking to button on the page 'A'. Waiting for getting the result on the page 'A'. Get the result on the page 'A'. So, I want to add process bar after 4th and before 5th points on the page 'A'. When you will get the result on the page 'A' it should disappear. Python 3.7 Django 3.x -
Django How to get a queryset from a queryset
I want to filter a queryset that depends on another queryset that already depends on another queryset My models.py class Escola(models.Model): id = models.AutoField(db_column='ID', primary_key=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) class Inscrio(models.Model): id = models.AutoField(db_column='ID', primary_key=True) escolaid = models.ForeignKey(Escola, models.DO_NOTHING, db_column='EscolaID', blank=True, null=True) class Utilizador(AbstractBaseUser) id = models.AutoField(db_column='ID', primary_key=True) inscriçãoid = models.ForeignKey(Inscrio, models.DO_NOTHING, db_column='InscriçãoID', blank=True, null=True) I am doing {% for escola in escolas %} {% for inscrio in escola.inscrio_set.all %} {% for utilizador in inscrio.utilizador_set.all %} <tr> <td><center>{{inscrio.id}}</center></td> <td><center>{{escola.nome}}</center></td> <td><center>{{utilizador.id}}</center></td> {% endfor %} {% endfor %} {% endfor %} I am trying currently getting the Inscrio data from Escola. But when I try to get the Utlizador data from the Inscrio I get nothing. How can I do this? Thanks in advance -
One textfield rendered from forms.py that show and hide based on two radio button selection in django accepting value of the second textfie?
I have created a form in forms.py that contains many fields including payment = forms.CharField() and render it from views.py to my respective HTML page. Things are working properly till here. In my HTML file, I have set style="display:inline-block;" so that based on user selection, the textfield appears. <div class="col-md-10 mb-3"> Pay <input type="radio" onclick="javascript:paymentCheck();" name="yesno" id="pay"> <div id="payselect" style="display:inline-block;"> {{ form1.payment | add_class:'form-control Contact-textbox' }} </div> &nbsp &nbsp &nbsp &nbsp Use Code <input type="radio" onclick="javascript:paymentCheck();" name="yesno" id="usecode"> <div id="usecodeselect" style="display:inline-block;"> {{ form1.payment | add_class:'form-control Contact-textbox' }} </div> </div> and in the js code, <script> function paymentCheck() { if (document.getElementById('pay').checked) { document.getElementById('payselect').style.display = 'inline-block'; } else document.getElementById('payselect').style.display = 'none'; if (document.getElementById('usecode').checked) { document.getElementById('usecodeselect').style.display = 'inline-block'; } else document.getElementById('usecodeselect').style.display = 'none'; } </script> What the problem I'm facing, if the form is not filled will all the textfields with the values then it not submit to the database and If I fill payselect and usecodeselect textfield then it just store the value of usercodeselect. I'm not getting how to make it work, Please help -
can't raise ValidationError django validators
I need to know how I raise ValidationError of a validators in django. First I tried the methode on form in simple page and forms and it works perfectly. but the problems appear when I use modal fade class in a page works with pk for example(127.0.0.1:8000/wsheets/AMA2/). the message is (The view Home.views.wellsets didn't return an HttpResponse object. It returned None instead.) and mt views.wellsets is def wellsets(request, WeelN): serchedWl = WellSheets.objects.filter(WellID__exact=WeelN) form= WelshetForm() context ={ 'title': 'SearchWS', 'Wellslistsh':serchedWl, 'WeelN':WeelN, 'form':form, } if request.method == 'POST': form =WelshetForm(request.POST, request.FILES) if form.is_valid(): form.instance.author = request.user form.save() return redirect('WellSheetg', WeelN) else: return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context) and my form + validator is: from django.core.exceptions import ValidationError class WelshetForm(forms.ModelForm): WellID = forms.CharField(label='Well Name',max_length=15) FileNm = forms.CharField(label='File Name',max_length=15) def clean_SHRPath(self): SHRPath = self.cleaned_data.get('SHRPath') size= SHRPath._size if SHRPath._size > 1024*1024*10: raise forms.ValidationError('Size is bigger than allowed') return SHRPath and at last this is my html form <button type="button" class="btn button1 btn-outline-success mb-2 btn-block" data-toggle="modal" data-target="#myModal" > <p class="thicker">Add new Well-Sheet</p></button> <div class="modal fade" id="myModal" role="dialog" > <div class="modal-dialog "> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"><p class="thicker">Upload Well-sheet</p></h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <p class="thicker">Check your file before uploading ({{WeelN}})</p> <div class="w3-panel w3-light-grey w3-round-large solid""> <form … -
How to update some field data of foreginKey model? In Dagango Model
I have created 2 models, I want whenever I change the value or adding new value in the count_of_B field of ModelB, I want to add that value in the count_of_A field of ModelA. class ModelA(models.Model): nameA = models.CharField(max_length=20, null=True, blank=True) count_of_A = models.IntegerField(default=0) class ModelB(models.Model): attached = models.ForeignKey(ModelA, on_delete=models.CASCADE) nameB = models.CharField(max_length=20, null=True, blank=True) count_of_B = models.IntegerField(default=0) def save(self, *args, **kwargs): mA = ModelA.objects.get(id=self.attached.id) mA.count_of_A += self.count_of_B mA.save() super(ModelB, self).save(*args, **kwargs) but when I ran some following syntax: >>> from ForTesting.models import ModelA, ModelB >>> ModelA.objects.all().delete() (2, {'ForTesting.ModelB': 1, 'ForTesting.ModelA': 1}) >>> ModelB.objects.all().delete() (0, {'ForTesting.ModelB': 0}) >>> mA=ModelA.objects.create(nameA="shiv", count_of_A=1) >>> mB=ModelB.objects.create(nameB="shankar", count_of_B=1, attached=mA) >>> print("A count: ", mA.count_of_A, "B count: ", mB.count_of_B) A count: 1 B count: 1 >>> mB.count_of_B=4 >>> mB.save() >>> print("A count: ", mA.count_of_A, "B count: ", mB.count_of_B) A count: 1 B count: 4 I didn't get value change in the ModelA field. Is there anything wrong when I am defining save method in ModelB or I have to use post_save method for this kind of work. -
Limit number of model instances to be created - django and consider deletion as well in admin panel
I have a model called Test. i want to limit user to create only 3 instances from admin panel. The scenario is when 3 tests are created, he/she should not be able to delete one from django admin and create another again.once created just keep a counter or something and limit only 3 creation -
django-redis-cahce creates random keys with integer values
I am using the following in my Django project: django-redis-cache==2.1.1 redis==3.5.5 Django==2.2.13 Python 3.7.5 In my settings.py I specified the following cache: CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'xxxxx.cloud.redislabs.com:10790', 'OPTIONS': { 'DB': 0, 'PASSWORD': 'xxxxx', 'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool', 'CONNECTION_POOL_CLASS_KWARGS': { 'max_connections': 20, 'timeout': 3, }, }, "KEY_PREFIX": "django_backend_2" } } Nowhere in any of my django apps am I actually using this redis cache, and I also have never_cache enabled in all my apps. The session_engine is set to use files: SESSION_ENGINE = 'django.contrib.sessions.backends.file' But, when I check the keys in my redis, I see random keys get created and removed all the time: (My prefix was django_backend then I changed it to django_backend_2 that is why you will see some prefixes as django_backend and some as django_backend_2.) The values in these keys are also just integers. b'django_backend_:1:rl:5409e278e64a68dc9647a76efdb1ebc6' b'3' b'django_backend_2:1:rl:7782bafff6e59026ab9128fcc171e742' b'1' b'django_backend_2:1:rl:8e35c29a5fcaea902eecb25b1eee5819' b'4' b'django_backend_:1:rl:8e35c29a5fcaea902eecb25b1eee5819' b'2' b'django_backend_2:1:rl:3d985fa28195dd6b27e8daa27d7a5b9c' b'3' b'django_backend_2:1:rl:97dbbf58e1f6191742336f77d6a0ee3f' b'4' b'django_backend_2:1:rl:d910a2d3f55adfcf17800e1be0a29ccc' b'1' b'django_backend_2:1:rl:a441f5cb14e949fd09ba967eb46df4a3' b'2' b'django_backend_2:1:rl:bd0ea6a16e224fd4dc7d00ee4923d502' b'1' b'django_backend_2:1:rl:db9c27edb5144791755378ed13691895' b'1' b'django_backend_2:1:rl:ddd02c9082d5203419fcd111f5d99b4a' b'2' b'django_backend_:1:rl:645c9769365940fa54818e0a99b5f7c6' b'1' b'django_backend_2:1:rl:9451df4e327529d0a9280c0cb3a76bbf' b'1' b'django_backend_2:1:rl:5409e278e64a68dc9647a76efdb1ebc6' b'6' b'django_backend_2:1:rl:b00a484f84287df2318b18ac6c3831aa' b'2' b'django_backend_2:1:rl:ee4f17e6c6fa1004811335ba199b5514' b'1' b'django_backend_:1:rl:ddd02c9082d5203419fcd111f5d99b4a' b'1' b'django_backend_2:1:rl:ec0959c9a1fb66a639fa4335b674cd1b' b'1' b'django_backend_:1:rl:3d985fa28195dd6b27e8daa27d7a5b9c' b'1' b'django_backend_2:1:rl:645c9769365940fa54818e0a99b5f7c6' b'4' b'django_backend_2:1:rl:13c420622b99b075ac456310ce353ef9' b'1' b'django_backend_2:1:rl:527977de6f4097bc2e9479f1d395e94f' b'1' b'django_backend_2:1:rl:3200f5f1ed135d5875a48cb2abc16a1a' b'1' b'django_backend_2:1:rl:9a069775ac907715dd5d35e32d622070' b'1' Why is this happening as the number of keys just seem to keep on … -
Change django model from one app to another, but on makemigrations, new model is added
I have two this model, which I want to move to another app. class ClientSubscription(AbstractAuditModel): """Subscription Details for the client.""" broker = models.ForeignKey(Broker, on_delete=models.CASCADE) category = ChoicesField( choice_class=SubscriptionCategory, default=SubscriptionCategory.NOT_SET) purchase_datetime = models.DateTimeField(null=True, blank=True) start_datetime = models.DateTimeField(null=True, blank=True) end_datetime = models.DateTimeField(null=True, blank=True) counter = models.ForeignKey( Counter, on_delete=models.CASCADE, null=True, blank=True) status = ChoicesField( choice_class=ClientSubscriptionStatus, default=ClientSubscriptionStatus.INACTIVE ) def __str__(self): """Return string representation.""" return str(self.broker) class Meta: """Meta Information.""" ordering = ('-created_at',) verbose_name = 'Client Subscription' verbose_name_plural = 'Client Subscriptions' This is my migration in this old app. from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('broker', '0019_auto_20200615_1120'), ] operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField( model_name='subscriptionpurchase', name='created_by', ), migrations.RemoveField( model_name='subscriptionpurchase', name='modified_by', ), migrations.RemoveField( model_name='subscriptionpurchase', name='payment', ), migrations.RemoveField( model_name='subscriptionpurchase', name='subscription', ), migrations.RemoveField( model_name='subscriptionpurchase', name='tenant', ), migrations.DeleteModel( name='ClientSubscription', ), ], database_operations=[], ) Then in my new app, I moved the model and added db_table, referring to the oldapp_tablename. I ran make migrations on my new app, and edited it. class Migration(migrations.Migration): initial = True dependencies = [ ('broker', '0020_auto_20200623_2020'), ('counter', '0002_counter_tenant'), ('tenant', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('payments', '0042_auto_20200615_1716'), ] operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.CreateModel( name='ClientSubscription', fields=[ ('uuid', models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Created At')), ('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')), ('category', base.fields.ChoicesField( choice_class=broker.choices.SubscriptionCategory, default=broker.choices.SubscriptionCategory(0))), … -
Django: TypeError: UserRegisterForm() missing 1 required positional argument: 'UserCreationForm'
I am pretty new to django and I am trying to add email field to the UsercreationForm. However, I am getting the below error: TypeError: UserRegisterForm() missing 1 required positional argument: 'UserCreationForm' I was wondering if someone can suggest me by seeing my views.py and forms.py that where I am going wrong with my coding? Views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def home(request): return render(request, 'index.html') def task(request): return render(request, 'task.html') def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): users = form.cleaned_data.get('username') return redirect('home') else: form = UserRegisterForm() return render(request, 'registration/register.html', {'form':form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm def UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username","email", "password1", "password2"] -
Django raw SQL query error 1241, 'Operand should contain 1 column(s)'
I'm trying to count the results of a raw SQL query using the following code: len(tuple(passwords.raw('SELECT classifyID FROM djangomysqldb.password_classify WHERE pw IN (%s)', [list]))) I have read on stack overflow that this is an effective method, however it results in the following error: (1241, 'Operand should contain 1 column(s)') Why do I get this error when this method seems to work for other users? -
how to hide profile logo after getting preview profile pic in javascript
I want to remove the logo by preview photo on logo and my script is <script type='text/javascript'> function preview_image(event) { var reader = new FileReader(); reader.onload = function() { var output = document.getElementById('output_image'); output.src = reader.result; } reader.readAsDataURL(event.target.files[0]); } </script> IN HTML <label for="id_Photo"><img height="120" width="120" alt="Image description" src="{% static 'images/imglogo.png' %}"></label> <input type="file" name="Photo" required="" id="id_Photo" style="display:none" onchange="preview_image(event)"> <img height="120" width="120" id="output_image"/> -
Circular Import Error on Model While Querying Within Different Python File in App
I am trying to import my journal app model from models.py into prompts.py file within the same journal app to run a function on one of the objects in the journal model. How can I avoid a circular model error with this model import? My model is set up within the journal app as such in models.py: class Journal(models.Model): user = models.ForeignKey(User,related_name='journal',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) prompt = models.CharField(max_length=256,default=prompt.prompt_gen()) prompt_html = models.CharField(max_length=256,editable=False,default=prompt.prompt_gen()) entry = models.TextField(default='What are you thinking about?') entry_html = models.TextField(editable=False) def __str__(self): return self.prompt,self.entry def save(self,*args,**kwargs): self.prompt_html = misaka.html(self.prompt) self.entry_html = misaka.html(self.entry) super().save(*args,**kwargs) def get_absolute_url(self,*args,**kwargs): return reverse('journal:single_entry',kwargs={'username':self.user.username, 'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user','entry'] verbose_name='entry' verbose_name_plural='entries' My prompts.py file within the journal app is set up as such: def prompt_gen(): from .models import Journal journal_str = Journal.objects.raw('SELECT entry FROM journal_Journal') qg = TextGenerator(output_type="question") prompt = qg.predict([journal_str]) return prompt I get this error: File "/Users/-/Desktop/Full_Stack/Projects/My_Django/filter/journal/models.py", line 17, in <module> class Journal(models.Model): File "/Users/-/Desktop/Full_Stack/Projects/My_Django/filter/journal/models.py", line 20, in Journal prompt = models.CharField(max_length=256,default=prompt.prompt_gen()) File "/Users/-/Desktop/Full_Stack/Projects/My_Django/filter/journal/prompt.py", line 5, in prompt_gen from .models import Journal ImportError: cannot import name 'Journal' from partially initialized module 'journal.models' (most likely due to a circular import) (/User s/-/Desktop/Full_Stack/Projects/My_Django/filter/journal/models.py) -
Share website content without redirecting or window pop up
I want to share my website content with platforms like Facebook, Youtube, etc but don't want the site to redirect me to these platforms. What would be the simplest ways to do it. -
How can I figure out "cannot pickle '_io.BufferedReader' object" error when trying to multiprocess with django
I'm trying to do db connection through multiprocessing for my app. I assume that an error is occurring from where I call my function. I've been struggled with multiprocessing in these few days. I found the codes from https://engineering.talentpair.com/django-multiprocessing-153dbcf51dab/ here my code is as follows views.py from src.conf.multiproces import MultiProcess class GridSearchAPI(generics.GenericAPIView): @transaction.atomic def post(self, request): with MultiProcess() as mp: mp.map(request) returnData = mp.results() if returnData['result']: return Response(returnData, status=status.HTTP_200_OK) else: returnData["message"] = "no data found" return Response(result, status=status.HTTP_400_BAD_REQUEST) multiprocess.py from __future__ import print_function, absolute_import, unicode_literals import time try: from Queue import Empty except ImportError: from queue import Empty # from pathos import from multiprocessing import Process,cpu_count, Manager import logging import traceback from django import db from django.conf import settings from django.core.cache import caches from elasticsearch_dsl.connections import connections from app.viewSet import SelectAPI loggly = logging.getLogger('loggly') class Timer(object): """ Simple class for timing code blocks """ def __init__(self): self.start_time = time.time() def done(self): end_time = time.time() return int(end_time - self.start_time) def close_service_connections(): """ Close all connections before we spawn our processes This function should only be used when writing multithreaded scripts where connections need to manually opened and closed so that threads don't reuse the same connection https://stackoverflow.com/questions/8242837/django-multiprocessing-and-database-connections """ # close db … -
inset data on paricular time automatically using Django
I want to insert data into model trackHabit model from DailyHabit on particular time automatically here is model DailyHabit: class DailyHabit(models.Model): Habit = models.CharField(max_length=50) Date_created = models.DateTimeField(auto_now_add=True) here is model TrackModel: class TrackHabit(models.Model): Hid = models.ForeignKey(DailyHabit, null=True, on_delete=models.SET_NULL) done = models.BooleanField(null=True, default=False) done_Date = models.DateTimeField(auto_now_add=True, null=True) Actually I want that everyday Habits from DailyHabit will added to TrackHabit to check that it will done or not. Thank you in Advance -
For Loop Django Template
I am trying to figure out the best way to loop a given number of times within a Django template from an integer field For example, if I have a model: models.py class Rating(models.Model): checked = models.IntegerField(default='0') unchecked = models.IntegerField(default='0') And I have a record where checked = 5, in the template how can I do the following: {% for i in checked %} <div>some repeatable content here </div> {% endfor %} Since checked is an integer, it is a non-iterable and it cannot be used in the for-loop. Is there a more simple solution? -
Django Recaptcha fails the form validation
I'm implementing RecaptchaV3 on a Django application. I am currently following this github(https://github.com/kbytesys/django-recaptcha3) README text to set it up. I have a feedback form that sends an email with the subject and text. However, when I add RecaptchaField in django form, the POST request no longer passes the form.is_valid() in views.py. Does anyone have a thought/fix on how to overcome this problem? Thank you in advance