Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: invalid literal for int() with base 10: '' | Django
I'm using Django to build an ecommerce webapp. I wrote this code in models.py from django.db import models # Create your models here. class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to='mainShop/images', default="") Then, I performed makemigrations using python manage.py makemigrations which produced the following D:\Projects\PyCharm Projects\VeroniCart\home>python manage.py makemigrations No changes detected Then I did python manage.py migrate This gave me the error: ValueError: invalid literal for int() with base 10: '' I'm also attaching a log file with the complete error. Any help appreciated! -
Django convert to windows executable
Is it ok to convert Django Project to Windows Executable? Django project with a PostgreSQL as backend for database -
Django ORM: many_to_many.extend(some_queryset)
I read the docs for RelatedManager. I could not find a way to extend a many-to-many relation. Example (this is what my "dream" looks like): my_user.groups.extend(my_group_queryset) I know that I could use this: for group in my_group_queryset: my_user.groups.add(group) But I prefer looping in DB to looping in my code (guidelines). Is there a way to add several objects to a many-to-many relation in one method call? -
how to create collapse that display dynamic data using bootstrap and django
I have a django project that use cards to display retrieved data from the database i want to add a collapse inside the card but the problem is that once i tried to do a foreach loop to load dynamic data the collapse just work on one card and not all of them. I know that i must assigned the id of each card to the href & aria-controls parameters of the collapse class in bootstrap. but don't know how. this is the cards code. <!-- cards --> <div class="container"> <div class="row justify-content-center"> {% for obj in object_list %} <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-5"> <div class="p-2 my-flex-item"> <div class="card innercardzoom"> <div class="inner"> <img src="{% static '/img/card/1.png'%}" class="card-img-top" alt="..."> </div> <h5 class="card-header"> <a class="collapsed d-block" data-toggle="collapse" href="#table-collapsed" aria-expanded="true" aria-controls="collapse-collapsed" id="heading-collapsed"> <i class="fa fa-chevron-down pull-right"></i> Details </a> <a class="collapsed d-block" data-toggle="collapse" href="#collapse-collapsed" aria-expanded="true" aria-controls="collapse-collapsed" id="heading-collapsed"> <i class="fa fa-chevron-down pull-right"></i> CONTENT </a> </h5> <table class="card-body table-sm table table-hover text-right"> <tbody> <tr> <td>ID</td> <td>{{ obj.0 }}</td> </tr> <tr> <td>FULL NAME</td> <td>{{ obj.1 }}</td> </tr> <tr> <td>Mothe NAME</td> <td>{{ obj.2 }}</td> </tr> <tr> <td>Title</td> <td>{{ obj.3 }}</td> </tr> <tr> <td>ADDRESS</td> <td>{{ obj.5 }}</td> </tr> </tbody> </table> <div id="table-collapsed" class="collapse" aria-labelledby="heading-collapsed"> <table class="card-body table-sm … -
How do I determine which elements were changed in a django manytomanyfield
I have a model with a ManyToManyField (step). I'd like to delete the objects (ImagePlus) linked to via this field if there is no step element referencing them anymore. I tried to use the pre_delete signal and this works fine for half the problem (I can delete the referenced object if the last step referencing them is deleted). However, I struggle to delete a referenced ImagePlus object if it is disconnected by an update to the manytomanyfield in a step. I tried to solve it by overloading the save method or the pre_save/post_save signal of the step object, but the changes in the manytomanyfield are all either before or after either of those. I also tried to solve it by interceping the m2m_changed signal of the through table. Once more I can partially solve my problem. If I add/remove objects via .add or via .remove in the shell I get a proper post_add/post_remove signal that I can process like the delete one. The problem here is that when I try to change the contents of the manytomanyfield in Django admin, or via ajax/DRF) I always get 4 signals in this order: 'pre_clear', 'post_clear', 'pre_add' and 'post_add'. Now I cannot use … -
how to update if the checkbox is true or false
\\my template {% for me in student %} <input type='checkbox' name="check[0]" value="1" {% if me.Asthma %} checked="check" {% endif %} /> Ashtma </td></tr><tr valign='top'><td> <input type='checkbox' name="check[0]" value="1" {% if me.CongenitalAnomalies %}checked="check" {% endif %} /> Congenital Anomalies </td></tr><tr valign='top'><td> <input type='checkbox' name="check[0]" value="1" {% if me.ContactLenses %}checked="check" {% endif %} /> Contact Lenses </td></tr><tr valign='top'><td> {% endfor %} \\my views asthma = request.POST.get('check[0]') congenitalAnomalies = request.POST.get('check[0]') Contact = request.POST.get('check[0]') update.Asthma=asthma update.CongenitalAnomalies=congenitalAnomalies update.ContactLenses = Contact \\my models Asthma=models.BooleanField(null=True, blank=True) CongenitalAnomalies=models.BooleanField(null=True,blank=True) ContactLenses=models.BooleanField(null=True,blank=True) it works fine if i do not check everything but I check one automatic check all, please correct my code, -
How to get sum of all extact electric_bike_id not like electric_bike_id = 1
I am trying to get summary of all specific electric_bike_id and i tried alot but i could not so for just not i just mention electric_bike_id = 1 so i got in every electric bike for 1 bike id summery so how to change that i will get sum of all specific electric id and here is serializer.py and models.py code you can see and guide me thanks Serializer.py class ElectricBikeSerializer(serializers.ModelSerializer): total_milage = serializers.SerializerMethodField() class Meta: model = models.ElectricBike fields = ['id', 'label', 'total_milage',] def get_total_milage(self, obj): totalpieces = Delivery.objects.filter( electric_bike__id=1).aggregate(total_milage=Sum('milage')) return totalpieces["total_milage"] And here it is Model.py class Delivery(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) milage = models.IntegerField( help_text="Milage Will be in Km/hr", default=10) movingtime = models.FloatField( help_text="Milage Will be in 5.30hr", default=10) averagespeed = models.IntegerField( help_text="Average Speed Will be in km/hr", default=10) letteritems = models.IntegerField( default=10, help_text="This field Will be in digit") shipweight = models.IntegerField( default=10, help_text="This field Will be in kgs") package = models.IntegerField( default=10, help_text="This field Will be in digit") kgtrasported = models.IntegerField( help_text="Kg Transported will be in Kg", default=10) co2 = models.IntegerField(help_text="Co2 will be in mg ", default=10) additionalbox = models.IntegerField( help_text="Additional Boxes will be in Number ", default=10) nouser = models.IntegerField( help_text="No Of … -
virtualenv fails on digital ocean's ubuntu 18.04 server
I'm depoying a django app on digital ocean's ubuntu server 18.04 via SSH and is encountering an error: The path python2 (from --python=python2) does not exist I'm following this guide https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps. I've also installed used sudo apt install python3.7 python3-venv python3.7-venv to install python and the virtualenv but it's still getting The path python2 (from --python=python2) does not exist when I create a virtualenv I've installed virtualenv via pip too. What did I miss? -
MongoDB connector for Django
I could not find any standard database connector provided by Django for MongoDB. It seems that we have to use some third-party application/work around to do that. Is there any specific reason for this absence? -
"Must provide query string." graphene-python
i try to send a file as following in Altair tool to graphql (backend is graphene-python). I use this library for backend but every it raises this error: Must provide query string. how can I upload a file to graphql? -
what happens to existing data when we change model Charfield to IntegerField in django?
When the following migration is applied, class Migration(migrations.Migration): dependencies = [ ('outlets', '0009_auto_20190920_1155'), ] operations = [ migrations.AlterField( model_name='outlet', name='country', field=models.IntegerField(choices=[(1, 'UAE'), (2, 'India')], verbose_name='Country'), ), ] The following error happens, return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "United States" This is because i am changing CharField to IntegerField and following data "United States" already exists in db, Also i read in similar question, django migrations is not able to handle such changes. Is there any way to do this operation, without deleting existing data ? -
How to fix 'list' object has no attribute 'get' (AttributeError) in Python/Django
I want to use form to create new objects in database but i can't run this view. Where do i need to make some changes ? I was trying to delete "def get" function but it was only white screen, like blank page after that. class AddOrderForm(forms.Form): airport = forms.ChoiceField(choices=AIRPORT_CHOICES, widget=forms.RadioSelect(AIRPORT_CHOICES)) direction = forms.ChoiceField(choices=DIRECTION_CHOICES) adress = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Turmstraße 57"})) client = forms.CharField() telephone = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "+49XXXXXXXXX"})) flight_number = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "LL 0000"})) plane = forms.DateTimeField(input_formats=['%Y-%m-%d']) pick_up = forms.DateTimeField(input_formats=['%Y-%m-%d']) gate = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "G or A11"})) driver = forms.ChoiceField(choices=DRIVER_CHOICES) class AddOrderView(View): def get(self, request): form = AddOrderForm() return render(request, 'orders/add_order.html', {'form': form}) def post(self, request, *args, **kwargs): form = AddOrderForm(request.POST) if form.is_valid(): order = Order.objects.create(airport=form.cleaned_data['airport'], direction=form.cleaned_data['direction'], adress=form.cleaned_data['adress'], client=form.cleaned_data['client'], telephone=form.cleaned_data['telephone'], flight_number=form.cleaned_data['flight_number'], plane=form.cleaned_data['plane'], pick_up=form.cleaned_data['pick_up'], gate=form.cleaned_data['gate'], driver=form.cleaned_data['driver']) return redirect(f'order/{order.id}') return render(request, 'orders/add_order.html', {'form': form}) -
zoom level difference between google map api and mapbox
I am using google map api in wagtail cms admin,in that page zoom level and latitude would be adjusted by admin.Then I want to display the respective page corresponding latitude with zoom level in a different page.But zoom levels are differing in mapbox.I tried to adjust the zoom level in mapbox with a difference of 2 and 1 from google map.but still both the map view is looking different.can anyone help to resolve this? -
save user data to another model after user signup django
i have this portal where user can register as artists and i want to save those user on different artist category page after registration like if a user register as model it automatically saved on artist models so it can be fetch on artists page artist models.py: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.utils import timezone from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django_countries.fields import CountryField from phonenumber_field.modelfields import PhoneNumberField class artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) artist_name = models.CharField(max_length = 50) artist_type = models.IntegerField(choices = CHOICES) artist_image = models.ImageField(upload_to= 'media') description = models.TextField(max_length = 500) def __str__(self): return self.artist_name Custom User Manager class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields ): if not email: raise ValueError('user must have email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email = email, is_staff = is_staff, is_active = True, is_superuser = is_superuser, last_login=now, date_joined = now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user custom user model class … -
zoom level difference between mapbox and google map api
I am using google map api in wagtail,there i want to pass zoom level to another page.They used mapbox for displaying map.But zoom level is not same with google map and mapbox.I tried the difference of 2 and 1 but didnt find the view same. Can anyone help me with this to resolve? -
Send "form data" to AJAX call
html part <form id="custom_form" name="custom_upload" method="POST" enctype="multipart/form-data"> <label>Choose File:</label> <input id="in" name="csv_file" value="Add CSV" type="file" required /> <table class="opttable"> <tr> <td> Title<span style="color: red;">*</span> </td> <td> <select id="select1" class="optselect form-control"> <option>abc</option> <option>cde</option> </select> </td> </tr> </table> <input type="submit" value="Submit" class="onsubmit"> </form> javascript part $('.onsubmit').on('click', function (e) { var id = {{id}} var fd= $('form').serialize() console.log(fd) $.ajax({ url: '/someview/'+id, type: 'POST', data: fd, sucess: function(data) { console.log(data); }, error: function(err) { console.log('err: '+err); } }); }); This is my code. So basically I want to pass both file and normal data in ajax call. I think serialize method converts form data into strings and I want to send file as well so how can achieve this. -
bug in package xlsxwriter: can't multiply sequence by non-int of type 'float'
I found a bug since the version 1.1.7. I generate an excel sheet using xlsxwriter which worked fine until I upgraded to the version 1.2. My code: def write_template_portfolio(self): """Create the template for portfolio """ # create the worksheet self.current_worksheet = self.workbook.add_worksheet("Portfolio") # write header self.write_value_and_comment(1, 0, "Portfolio name", self.style_header, 'D2', 'Mandatory: The name of your Portfolio...') self.write_value_and_comment(1, 4, "Benchmark Name:", self.style_header, 'G2', 'Mandatory: The name of your Benchmark...') self.write_value_and_comment(1, 7, "Market Index Name:", self.style_header, 'J2', 'Mandatory: The name of your Market Index...') # qualitative information self.write_value_and_comment(2, 0, "Value Date", self.style_header, 'A3', 'Optional') self.write_value_and_comment(3, 0, "Inception Date", self.style_header, 'A4', 'Optional') self.write_value_and_comment(4, 0, "Manager", self.style_header, 'A5', 'Optional') self.write_value_and_comment(5, 0, "Philosophy", self.style_header, 'A6', 'Optional') self.write_value_and_comment(6, 0, "Currency", self.style_header, 'A7', 'Optional') self.write_value_and_comment(7, 0, "Region", self.style_header, 'A8', 'Optional') # time Series self.current_worksheet.write(5, 4, "Benchmark Value Date", self.style_header) self.current_worksheet.write(5, 5, "Benchmark Value", self.style_header) self.current_worksheet.write(5, 6, "Benchmark Type", self.style_header) self.current_worksheet.write(5, 7, "Market Index Value Date", self.style_header) self.current_worksheet.write(5, 8, "Market Index Value", self.style_header) self.current_worksheet.write(5, 9, "Market Index Type", self.style_header) for i in range(0, 25): self.current_worksheet.write(1, 10 + 3 * i, "Name:", self.style_header) self.current_worksheet.write(2, 10 + 3 * i, "Weight or Market Value:", self.style_header) self.current_worksheet.write(3, 10 + 3 * i, "Strategy:", self.style_header) self.current_worksheet.write(4, 10 + 3 * i, … -
How to use Two forms in Django Templates, And how to call different function when it submit the form
I am using two forms in one template. When i submit the 2nd form its calling first form only i'm little bit confusing where i did mistake anyone help me in this. index.html <form action="#" method="post"> <input type="text" name="username" id="username"> <a href="{% url 'app:profile' %}"><button type="submit"> Submit</button></a> </form> <form action="#" method="post"> <input type="text" name="review" id="review"> <a href="{% url 'app:feedback' %}"><button type="submit"> Submit</button></a> </form> views.py def profile(request): if request.method == 'GET': # Some operation return render(request, 'index.html'{}) elif request.method == 'POST': username = request.POST.get('username') res = User(username=username) res.save() return redirect('/home/') return redirect('/login/') def feedback(request): if request.method == 'POST': review= request.POST.get('review') res = Feedback(comment=review) res.save() return redirect('/home/') return redirect('/home/') urls.py app_name = 'app' urlpatterns = [ path('profile/', views.profile, name="profile"), path('feedback/', views.feedback, name="feedback"), ] -
How to warm up django web service before opening to public?
I'm running django web on AWS ecs. I'd like to warm up the server (hit the first request and it takes some time for django to load up) when deploying a new version. Is tehre a way for warming up the server before registering it to the Application load balancer? -
Manipulate Opengts servlet with python
I want to use OpenGTS but also I want to develop my web page with Django. Is there a way to integrate OpenGTS to Django or handle the servelets with python? Maybe handle the servelets with python to adquire the info (using POST and GET) and then process it with python? What do you think? -
Django update_or_create() method not working
Does django update_or_create() works in django 2.2,i have been searching from a while on internet about django upsert,but none of answer helped. I saw get_or_create() method and it successfully worked in my case,but replacing the it with update_or_create did not work. -
maximum number of fields in a single django model?
I am designing an app for the maritime industry. I am forced to add 62 float fields in a single django model. Would it make any problem with scalability? is there any alternative better method? Thanks, Tom Victor -
Automatically creating user profile
This may be a rookie mistake but it has been bugging me for days now I am trying to create a system in which after my registration is completed a profile is automatically made and saved for the user. I have applied all my current knowledge but the following error keeps showing up. IntegrityError at /register/ NOT NULL constraint failed: users_profile.standard Request Method:POST This is my views.py - `from django.shortcuts import render, redirect from django.contrib import messages from .form import UserRegisterForm 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() username = form.cleaned_data.get('username') messages.success( request, f'Your account has been created. You are now able to log in!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): return render(request, 'users/profile.html') and my signals.py - from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Please help me out here guys, I am desperate. -
How does the site react if there are too many requests?
I'm calling the API through another site with Django. How can I do a simple performance test? How long will it last when I make a request.get 500,000 for example? I tried something like this, but it's ridiculous. a = 1 while a < 1000: a += 1 requests.get('http://www.test.crm/api/v1/User/' + user_id, headers={"Authorization": credentials}).json() -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'routing'
I am trying to build a multiplayer game in Django, for which I needed to work on Django channels. but here's the issue while running it. Performing system checks... System check identified no issues (0 silenced). September 27, 2019 - 05:38:35 Django version 2.2.5, using settings 'multiproject.settings' Starting ASGI/Channels version 2.1.5 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/augli/.local/lib/python3.6/site-packages/channels/routing.py", line 33, in get_default_application module = importlib.import_module(path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'routing' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/augli/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/augli/.local/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 101, in inner_run application=self.get_application(options), File "/home/augli/.local/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 126, in get_application return StaticFilesWrapper(get_default_application()) File "/home/augli/.local/lib/python3.6/site-packages/channels/routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'routing' Here's my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', …