Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save() got an unexpected keyword argument 'force_insert'
from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your account has been created. Log In to continue.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) This is the code when I run it I get an error. But that error shouldn't be there since I am not overriding the the save() method. please help. -
How to render in dropdown form in Django
How to make this in Django ? I have a ManyToMany Field in my models. When i rendered it out in HTML, it shows as radio button. How to make it in Dropdown form ? -
DJANGO - How to keep fields values after submit
I have a form and i would like to keep the fields values after click on submit. How can I do this ? Views.py : if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): form.save() else: form = MyForm() template.html <form method="post" id="Myform" > {{form}} <button class="btn btn-primary" type="submit" > </form> -
Scheduling a job with APScheduler: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS [Django and Heroku]
I am trying to set a scheduled job in my Django app. I want this sheduled job to be run every x minutes while my app is on Heroku. I am following this article explaining how to scheduling jobs using custom clock on heroku (python). Inside my project main folder, I have my Procfile: web: gunicorn aqi_luftdaten.wsgi clock: python clock.py and my clock.py: from apscheduler.schedulers.blocking import BlockingSchedule # import the script I want to be run every x minutes # this fills a model with new data coming from an api from pm_lookup.processing.scheduled_processing import save_history_pm sched = BlockingScheduler() sched.add_job(save_history_pm, 'cron', id='run_every_1_min', minute='*/1') sched.start() I can see from my requirements.txt that I have installed APScheduler==3.6.3. In my heroku app settings I have installed the heroku/python buildpack Then I git add . git commit -m "implement scheduled job" git push heroku master And when it is successfully push I finally heroku ps:scale clock=1 But then I can see my model is not getting any new data. So I run heroku logs --tail And actually see there are some errors: 2020-05-16T11:08:26.467364+00:00 app[clock.1]: File "/app/pm_lookup/models.py", line 10, in 2020-05-16T11:08:26.467498+00:00 app[clock.1]: class target_area_input_data(models.Model): 2020-05-16T11:08:26.467528+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 103, in new 2020-05-16T11:08:26.467664+00:00 app[clock.1]: app_config = … -
How can i fix double for loop in django
lostList.html shows LostNotices and Dogs. I want to match lostnotice and dog using foreign key in Dog model. So i used for loop and if in the template. But it doesn't work.... I am trying to fix this for 2 days but i couldn't. It will be really big help for me. Thank you {% for lostPost in lostPosts.all reversed %} <h6>{{lostPost.id}}</h6> {% for dog in dogs.all %} <h6>{{dog.breed}}</h6><br> <div class="col-lg-3 col-sm-6 col-md-6"> <div class="card"> <div class="card-body"> {% if dog.LostNoticeNum == lostPost.id %} views.py def lostList(request): lostPosts = LostNotice.objects dogs=Dog.objects return render(request, '/lostList.html', {'lostPosts' : lostPosts,'dogs':dogs}) model.py class LostNotice(models.Model): Title=models.CharField(max_length=20,null=True) State=models.IntegerField() PubDate=models.DateTimeField() MissingDate=models.DateTimeField() Text=models.TextField() Phone=models.CharField(max_length=20,null=True) Author=models.ForeignKey(Member, on_delete = models.CASCADE,null=True) Si=models.CharField(max_length=20,null=True) Gu=models.CharField(max_length=20,null=True) Dong=models.CharField(max_length=20,null=True) class Dog(models.Model): Name=models.CharField(max_length=20) Breed=models.CharField(max_length=20) Sex=models.CharField(max_length=20,null=True) Color=models.CharField(max_length=20,null=True) LostNoticeNum=models.ForeignKey(LostNotice, on_delete = models.CASCADE,null=True) FindNoticeNum=models.ForeignKey(FindNotice, on_delete = models.CASCADE,null=True) template: <div class="" id="list"> <div class="container"> <div class="row mx-auto"> <div class="col-lg-12 col-sm-12 col-md-12 col-12 pr-1"> <div class="row mb-2 ml-2 mr-2"> {% for lostPost in lostPosts.all reversed %} <h6>{{lostPost.id}}</h6> {% for dog in dogs.all %} <h6>{{dog.breed}}</h6><br> <div class="col-lg-3 col-sm-6 col-md-6"> <div class="card"> <div class="card-body"> {% if dog.LostNoticeNum == lostPost.id %} <h6>breed</h6> <h6 class="card-title" style="text-align: center; color: gray">{{dog.Breed}}</h6> {% else %} <h6 class="card-title" style="text-align: center">{{lostPost.sex}}</h6> {% endif %} {{lostPost.photo}} {% if lostPost.photo %} <img class="card-img-top rounded-circle … -
Pagination not working with Django-Filter
I'm using Django-filters to filter results. The filter is working correctly, but now the pagination is not working. It's being rendered, but now all the products are being displayed in one page. I was using paginate_by = 6 as it is a class based view. Even after filtering results, for example there are 8 products matching the filter, everything is being displayed in one single page. Why is it not working? Can anyone please help me out? Thanks in advance! My filters.py: import django_filters from .models import Item class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'category': ['exact'], 'price': ['lte'] } My views.py: class homeview(ListView): model = Item template_name = 'products/home.html' paginate_by = 8 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset()) return context My index.html: <div class="card mb-4"> <div class="card-body"> <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button type="submit" class="btn btn-primary mt-4">Filter</button> </form> </div> </div> </div> <h1>List Of Items</h1> <div class="row mb-4"> {% for item in filter.qs %} <div class="col-lg-4"> <img class="thumbnail" src="{{ item.image_url }}"> <div class="box-element product"> <h6><strong>{{ item.title }}</strong></h6> <h6 class="text-success">Category - {{ item.get_category_display }}</h6> <hr> </div> </div> {% endfor %} </div> <ul class="pagination justify-content-center"> {% if is_paginated %} {% if page_obj.has_previous %} … -
How to include html from separate template without the css of that affecting my whole other template?
I am including this template: {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'users/userstyles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'website/style.css' %}"> </head> <body> <form method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="create"> </form> </body> </html> in my other template like this: <div class="needbox"> {% for need in needs_user2 %} <li><a href="#">{{ need }}</a></li> {% endfor %} {% include 'problemdashboard/newneedform.html' %} </div> But the bootstrap css from the included template is effecting my own css on the parent template. I only want it to effect the child template though. How could I achieve that? -
I can't pass dictionary to html file in django
py file is : 'return render(request,'count.html' , worddic) ' and count.html is : {worddic} {fulltext} the out put : you'r words {worddic} -
How can I access Django returned data (json) in javascript?
I have the following view that returns data from StocksPrice model/DB. def getStocksAvailable(request, *args, **kwargs): StocksAvailable = StocksPrice.objects.all() structureStocks = serializers.serialize('json', StocksAvailable) return render(request, {"myData" : structureStocks}) url/view mapping: urlpatterns = [ path('terminal/getStocksAvailable/', getStocksAvailable), ] What I tried: Related SO thread var mydata = JSON.parse("{{data}}"); console.log(mydata) // Output VM12472:1 Uncaught SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse (<anonymous>) at VM12471 terminal.js:2 related SO thread var mydata = "{{data}}"; console.log(mydata) // Output {{data}} -
Conception: is my entity relation diagram correct?
I want to develop an app in Django to follow user account for our different applications. I have identify at least 3 entities: - Projects - Users - Applications A project can have many users. A user can be implied in many projects. A user in a project can have access to many applications. I think my first ER diagram is false (see below) because users will be duplicated for each projects it will be implied... I should have a many-to-many relationship between Projects and Users (intermediate models Project-User) and Applications should be related to this intermediate models Project-User with a FK. -
Django forms - nested filtering in a vew for form cleaned data validation
This is related to Filter queryset with multiple checks, including value_is_in array in a Django view, though addresses a slightly different issue. I need two levels of checking of my form data: I have a profile model with name, surname, and role (the last one is and array coming from a related model, one profile can have many roles). Upon submission of the form I need to check if a profile with a name and surname exists first; if it does, I need to check if that existing profile has already that role; if yes, throw an error. If not, keep the existing profile and only add the new role entered in the form. My models: class Role(models.Model): type= models.CharField(max_length=30) def __str__(self): return self.type class Profile(models.Model): first_name = models.CharField(max_length=120, null=True, blank=True) surname = models.CharField(max_length=120, null=True, blank=True) role = models.ManyToManyField(Role, blank=True) And this is what I have tried in my view: def clean(self): cleaned_data = super().clean() first_nameUnregistered = self.cleaned_data['first_nameUnregistered'] surnameUnregistered = self.cleaned_data['surnameUnregistered'] role = self.cleaned_data['role'] if Profile.objects.exclude(pk=self.instance.pk).filter( first_nameUnregistered=first_nameUnregistered, surnameUnregistered=surnameUnregistered ).exists(): if role__in=role: raise forms.ValidationError("This profile already exists") else: return cleaned_data return cleaned_data which gives me a syntax error on if role__in=role:. How can I check if the current Profile object being … -
using re.sub to find and replace all exact matches
The code below, aims to search hash signs in a string. If hash signed substrings ends in ([^\s#@$]*) it checks if the substring exists in database and if so it converts it to an anchor tag. if not bool(BeautifulSoup(content,"html.parser").find()): if "#" in content: title= re.findall(r"[#]([^\s#@$]*)(?=[\s#@$])", content) for i in title: if i not in check_list: check_list.append(i) try: title= Title.objects.get(title = i) c = re.sub("[#]({})([^\s#@$]*)".format(i,),"<a class='title-link' href='/titles/{}'>{}</a>".format(i,i),c) except: continue The problem occures when there is more then one hash signed substrings with the same value. Say the string is: "#title5 #title5xxx title5#title555" The result is: "<a class='title-link' href='/titles/title5'>title5</a> <a class='title-link' href='/titles/title5'>title5</a> title5<a class='title-link' href='/titles/title5'>title5</a>" But I want it to be: "<a class='title-link' href='/titles/title5'>title5</a> #title5xxx title5#title555" Because I want re.sub function to replace only exact matches starting with "#" and ending in [s-#-@-$] without replacing characters in which the string ends. As an amateur, I hope I expressed myself correctly without annoying you. Have a nice day! -
I want to be able to automatically mark a Boolean field as true after certain time frame, without using third party package
Am working on a django project, where users registered and pay if the payment have been verified i will update the paid attribute in the user Profile to True and automatically trigger a timer that calculate when the paid attribute will be return back to False after certain duration say 1 Day. How can this be done ? So far this is what i have achieved. class Profile(AbstractUser): paid = models.BooleanField(default=False) class TimeTracker(models.Model): user = models.OneToOneField(Profile,on_delete=models.CASCADE,related_name='usertime') created = models.DateTimeField(auto_now_add=True) @property def end_date(self): time_remaining = self.created + timedelta(days=1) time_remaining = time_remaining.strftime("%A %B %d %H:%M%p") since = str(time_remaining) return since I am able to Trigger the paid to True from the view function, when payment have been verified but i have not be able to set it back to false after 1 day. Something like if the difference between when the timer was created and now is 1 day, set the paid attribute to False. E.g if current_datetime - created == 1day: Profile.paid = False profile.save() I don't want this to be done by the user meaning,i want that function check to be running on his own and whenever i return true it update the user paid in its Profile to False. … -
How to append div using ajax
i am working on a website using django. I have implemented a code in Ajax/Jquery on how to append div. I have list of post in homepage and each post have a comment form, when form is submitted i append the comment to div and all comment only append to the first post. How do i append a div to the post id? So that when a use submit a form in second post, the comment will only append in second post not the first post. Template: <div class="container newfeeds-comment"> {% for comment in friends_comment %} {% if comment in post.comments.all %} <div class="row"> <div class="col-1 col-md-1 col-lg-1"> {% if comment.user.profile.profile_pic %} <span id="comment-img"> <img src="{{ comment.user.profile.profile_pic.url }}" class="d-flex rounded-circle mt-1" alt="image" height="28" width="28"> </span> {% endif %} </div> <div class="col-10 col-md-10 col-lg-10 p-2 ml-1" id="user-commentpost"> <span class="comment-post truncate"> <span class="name text-lowercase" id="comment-user">{{ comment.user.username }}</span> <span id="comment-post">{{ comment.comment_post }}</span></span> </div> </div> {% endif %} {% endfor %} </div> Ajax: <script type="text/javascript"> $(document).ready(function() { $('.feeds-form').on('submit', onSubmitFeedsForm); $('.feeds-form .textinput').on({ 'keyup': onKeyUpTextInput, 'change': onKeyUpTextInput }); function onKeyUpTextInput(event) { var textInput = $(event.target); textInput.parent().find('.submit').attr('disabled', textInput.val() == ''); } function onSubmitFeedsForm(event) { event.preventDefault(); console.log($(this).serialize()); var form = $(event.target); var textInput = form.find('.textinput'); var hiddenField = … -
Upload to AWS Bucket Stops Daphne Server running Django
When uploading in my django project, using Boto and django-storages, my server (daphne) stops but the upload will be successful. Here are the log entries for the daphne service: May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,586 DEBUG Making request for OperationModel(name=PutObject) with params: {'url_path': '/isppme-asset/media/exam-csv/2020/05/exam_data_JIhyjxO.csv', 'query_string': {}, 'method': 'PUT', 'headers': {'Cache-Control': 'max-age=604800, s-maxage=604800, must-revalidate', 'Content-Type': 'text/csv', 'User-Agent': 'Boto3/1.13.11 Python/3.7.3 Linux/5.0.0-25-generic Botocore/1.16.11 Resource', 'Content-MD5': 'bKzegIKj5nDGsBsm7Kv1Vg==', 'Expect': '100-continue'}, 'body': <s3transfer.utils.ReadFileChunk object at 0x7fc8f411ce80>, 'url': 'https://s3.us-east-2.amazonaws.com/isppme-asset/media/exam-csv/2020/05/exam_data_JIhyjxO.csv', 'context': {'client_region': 'us-east-1', 'client_config': <botocore.config.Config object at 0x7fc8f4201dd8>, 'has_streaming_input': True, 'auth_type': None, 'signing': {'region': 'us-east-2', 'bucket': 'isppme-asset', 'endpoint': 'https://s3.us-east-2.amazonaws.com'}}} May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,588 DEBUG Event request-created.s3.PutObject: calling handler <function signal_not_transferring at 0x7fc8f603f510> May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,588 DEBUG Event request-created.s3.PutObject: calling handler <bound method RequestSigner.handler of <botocore.signers.RequestSigner object at 0x7fc8f4201da0>> May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,588 DEBUG Event choose-signer.s3.PutObject: calling handler <bound method ClientCreator._default_s3_presign_to_sigv2 of <botocore.client.ClientCreator object at 0x7fc8f45b9b00>> May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,589 DEBUG Event choose-signer.s3.PutObject: calling handler <function set_operation_specific_signer at 0x7fc8fc135c80> May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,589 DEBUG Event before-sign.s3.PutObject: calling handler <bound method S3EndpointSetter.set_endpoint of <botocore.utils.S3EndpointSetter object at 0x7fc8f41ac860>> May 16 09:38:04 isppme-web-app daphne[15040]: 2020-05-16 11:38:04,589 DEBUG Checking for DNS compatible bucket for: https://s3.us-east-2.amazonaws.com/isppme-asset/media/exam-csv/2020/05/exam_data_JIhyjxO.csv May … -
Website POST works, but unit test to check that information has been updated fails
Im trying to test that my POST to /enrolment/personal_information/ successfully updates the users data, yet cant seem to get it to pass. Strangely enough the update works on my site, but my test fails. test.py def test_user_information_updated_on_success(self): user = User.objects.create_superuser('username') EmailAddress.objects.create(user=user, email="example@example.com", primary=True, verified=True) self.client.force_login(user) response = self.client.post('/enrolment/personal_information/', {'user': user.id, 'first_name': 'testuser', 'surname': 'testsurname', 'gender': 'M', 'dob': '1984-09-17 00:00:00'}) self.assertEqual(response.status_code, 302) # this passes - redirects to the next page self.assertEqual(user.personalinformation.first_name, 'testuser') # this fails The error: AssertionError: '' != 'testuser' Thank you -
Django error in Cutom user model save() method
I have a custom user model which was working without error, later I add field for user image then I can do registration but unable to login. I think there is error in the save() method. I don't accept user image in registration page, but there is template for loggedin user to add later from django.db import models from django.contrib.auth.models import AbstractUser from PIL import Image class User(AbstractUser): email = models.EmailField(verbose_name='email' ,max_length=223,unique=True) photo = models.ImageField(upload_to='prof_pic', blank=True,null=True) phone=models.CharField(null=True,max_length=11) REQUIRED_FIELDS = [ 'email','phone'] def save(self,*args, **kwargs): super().save() if self.photo: pic = Image.open(self.photo.path) if pic.height > 300 or pic.width > 300: output_size = (300, 300) pic.thumbnail(output_size) pic.save(self.photo.path) super(User, self).save(*args, **kwargs) -
Django: SystemError: <built-in function uwsgi_sendfile> returned a result with an error set
On localhost it works perfectly fine but on pythonanywhere it doesn't work anymore. When I press on a button which should download a word document I get this error message: SystemError: returned a result with an error set. views.py: def downloadWord(request, pk): order = Order.objects.get(pk=pk) order_items = order.order_items.all() date = f'{order.date}' d =date[8:] y = date[:4] m = date[5:7] date = f'{d}.{m}.{y}' context={ 'order_items': order_items, 'order': order, 'date': date } byte_io = BytesIO() tpl = DocxTemplate(os.path.join(BASE_DIR, 'media/word_documents/order.docx')) tpl.render(context) tpl.save(byte_io) byte_io.seek(0) data = dict() return FileResponse(byte_io, as_attachment=True, filename=f'order_{order.title}.docx') I also tried to use FileWrapper from werkzeug but then it says "AttributeError: 'FileWrapper' object has no attribute 'write'": from werkzeug.wsgi import FileWrapper def downloadWord(request, pk): order = Order.objects.get(pk=pk) order_items = order.order_items.all() date = f'{order.date}' d =date[8:] y = date[:4] m = date[5:7] date = f'{d}.{m}.{y}' context={ 'order_items': order_items, 'order': order, 'date': date } byte_io = BytesIO() byte_io = FileWrapper(byte_io) tpl = DocxTemplate(os.path.join(BASE_DIR, 'media/word_documents/order.docx')) tpl.render(context) tpl.save(byte_io) byte_io.seek(0) return FileResponse(byte_io, as_attachment=True, filename=f'order_{order.title}.docx') -
Django channels group handler / group manager
I'm willing to use Django-channels for creating a game backend, for the question purpose let's say it's a [multiplayer] trivia game. A client connect to the server and a Consumers handle its socket. Then, the client send a message that connect him to a specific group (group will be 1 instance of a game) after there are some users in a group, the game should start.. My question is: is there any way to create a "group handler"/"group manager" that run on the server and also connect to the same channel group and manages the gameplay? like send the questions to all other players, says who wins, etc.. I saw there is some "worker" in the channel library but it's not seems to be the solution becuase it's not dynamic, you need to run the worker manually.. Thanks! -
call back ForeignKey data after selecting an item django ajax
im trying to make an app for a car show with billing form , after the admin wants to sell a car the system has a customer form to billing , creating a form from Customer and its related to CarModel and every CarModel has its own CarFeature class CarModel(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) model = models.CharField(max_length=60,unique=True) company = models.CharField(max_length=60) class CarFeature(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) model = models.ForeignKey(CarModel, on_delete=models.CASCADE) color= models.CharField(max_length=20) new = models.BooleanField(default=True) automatic= models.BooleanField(default=True) #and other features class CarFeatureForm(forms.ModelForm): class Meta: model = CarFeature fields = ['model','color','new','automatic'] class CarModelForm(forms.ModelForm): class Meta: model = CarModel fields = ['model' , 'company'] class Customer(models.Model): customer = models.CharField(max_length=50) seller = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) model = models.ForeignKey(CarModel,on_delete=models.SET_NULL,null=True) price = models.IntegerField() class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['model','color','new','automatic'] i want to before saving Customer instance it will call back its car feature on the html form <form method="POST" id="print-form">{% csrf_token %} <table class="table"> <thead> <tr> {{ form.model.errors }} <td scope="col">car models</td> <!-- <td scope="col" id="model">{{ form.model }}</td> --> <td><div class="form-group floating-label" id="modeling"> {{ form.model | add_class:'form-control select2-list' | attr:'id:model'}} </div></td> {{ form.price}} <input type="submit" name="save" value="selling" class="btn btn-primary btn-block" id="submit"> </form> display car features in CarFeature model after selecting a model of a car … -
Django: want to make form field not required if checkbox is ticked
Problem is would like to change status of field 'extra' to not required when filling form if 'resolved_status' is not checked in my passion project. Got a model: class Post(models.Model): resolved_status = models.BooleanField() extra = models.TextField(max_length=20, default='') form.py: class PostForm(forms.ModelForm): class Meta(): model = Post Tried to put bellow model.Form: def clean(self): resolved_status = self.cleaned_data.get('resolved_status') if resolved_status == False: self.fields['extra'].required = False OR def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) if self.fields['resolved_status'] == False: self.fields['extra'].required = False Is it possible to do something like this, or better do follow up form that says form completed (if box is ticked), or direct to another form if not? Thank You! -
Valueerror on django-cities import in Mysql
I have installed gdal and django-cities packages and also changed the mysql connection to 'ENGINE': 'django.contrib.gis.db.backends.mysql'. I am trying to import django-cities with mysql as the database using this command: python manage.py cities --import=all Importing countries: 100%|████████████████████████████| 250/250 [00:00<00:00, 286.61it/s] Importing country neighbours: 100%|███████████████████| 250/250 [00:00<00:00, 548.11it/s] Building country index: 100%|███████████████████████| 250/250 [00:00<00:00, 13117.20it/s] Importing regions: 100%|████████████████████████████| 3955/3955 [00:12<00:00, 306.78it/s] Building region index: 100%|██████████████████████| 3955/3955 [00:00<00:00, 23073.45it/s] Importing subregions: 100%|███████████████████████| 44780/44780 [02:23<00:00, 312.34it/s] Building region index: 100%|████████████████████| 48704/48704 [00:02<00:00, 20783.33it/s] Importing cities: 100%|███████████████████████████| 50136/50136 [04:08<00:00, 201.41it/s] Building hierarchy index: 100%|██████████████| 488118/488118 [00:03<00:00, 160821.22it/s] Building city index: 100%|██████████████████████| 47401/47401 [00:04<00:00, 10881.61it/s] Importing districts: 1%|▎ | 746/50136 [00:00<00:12, 3842.99it/s] This is the progress. It shows this error: File "/env/lib/python3.7/site-packages/django/contrib/gis/db/backends/mysql/operations.py", line 78, in get_distance 'Only numeric values of degree units are allowed on ' ValueError: Only numeric values of degree units are allowed on geodetic distance queries How can I rectify this error? -
Channels consumers garbage collector
What happens to a consumer instance after a websocket client disconnects? Is there any specific cleanup of the instance done, or just regular garbage collection? Is it possible to reconnect to a channels consumer instance to recover the state of that instance? -
Upload multiple files in Django admin
Django==3.0.6 models.py class Image(models.Model): image_42_webp_1 = models.ImageField(upload_to=_get_upload_to, validators=[validate_image,], blank=True, verbose_name="42 webp 1х") image_42_fallback_1 = models.ImageField(upload_to=_get_upload_to, validators=[validate_image,], blank=True, verbose_name="42 1х") image_42_webp_2 = models.ImageField(upload_to=_get_upload_to, validators=[validate_image,], blank=True, verbose_name="42 webp 2х") <...> There are much more image fields in the model. As a matter of fact more than 50. Why do I need them is another question. But in short every image is adjusted manually for better site performance. Anyway, there are a lot of image fields and I wouldn't like to overburden the admin by loading so many files one at a time. I'd like to use something for bulk upload. I have failed to find a ready made app. So, if you suggest me some app, that would be great. If not, well, any solution would suit. Maybe this can be somehow used? https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/#uploading-multiple-files In model admin the template 'includes/fieldset.html' is responsible for creating/editing new model instance. What I need is just some means not fill the fields by hand. Any means, even Selenium would suit. Or maybe a raw http post request (though login is required and CSRF protection is switched on). Could you help mehere? -
Generating Custom html ids using Django for Bootstrap Carousels
I am generating a carousel for each gallery in my django model. However, as you know each Carousel in Bootstrap 4 requires their own id in order to use carousel-controls. To overcome this I tried to use the id of my model. However, instead of going back and forth between my images. The carousel buttons lead to a link with the id of the gallery selected. I've attached the code for my Carousel down below. {% for pics in gallery %} <div class="d-flex flex-column py-3 px-3 text-center"> <h4 class="">March 25th 2020</h4> <h1 class="mt-n2">{{pics.title}}</h1> <h6 class=""><a>View Full Gallery</a></h6> </div> <div class="container-fluid pb-4"> <div id="{{pics.id}}" class="carousel slide carousel-fade" data-ride="carousel"> <div class="carousel-inner"> <ul class="carousel-indicators"> {% for picture in pics.images.all %} {% if forloop.counter == 1 %} <li data-target="#{{pics.id}}" data-slide-to="{{forloop.counter0}}" class="active"></li> {% else %} <li data-target="#{{pics.id}}" data-slide-to="{{forloop.counter0}}"></li> {% endif %} {% endfor %} </ul> {% for picture in pics.images.all %} {% if forloop.counter == 1 %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <img src="{% thumbnail picture.image 1200x600 crop detail %}" alt="Image" class="d-block w-100"> <div class="carousel-caption"> <h3 class="h3-responsive">XXXXX</h3> <p> {{picture.description}}</p> </div> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#{{pics.id}}" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#{{pics.id}}" …