Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Field 'id' expected a number but got 'Processing'
I'm going to deploy my django application on DigitalOcean. Everything gone well, except following error, and my question is: where can I find source of this error, actually in which file ? ValueError: invalid literal for int() with base 10: 'Processing' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ... File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2361, in get_db_prep_value value = self.get_prep_value(value) File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value ) from e ValueError: Field 'id' expected a number but got 'Processing'. -
Django ORM - Cast and filter a queryset
I would like to cast a related column to integer and then filter a queryset, but I can not get it to work. These are my models class Author(models.Model): name = models.CharField(max_length=255) ... class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE) ... class MetricType(models.Model): label = models.CharField(max_length=255) class Metrics(models.Model): book = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="metrics") metric_type = models.ForeignKey(MetricType, on_delete=models.CASCADE) value = models.CharField(max_length=255) For simplicity, let's suppose I have the following data Author: - Name: Miguel de Cervantes - Name: William Shakespeare Book: - Title: Don Quixote, Author: Miguel de Cervantes - Title: Hamlet, Author: William Shakespeare MetricType: - Label: Pages Metrics: - Book: Don Quixote, MetricType: Pages, value: 100 - Book: Hamlet, MetricType: Pages, value: 40 Now, the only thing I want to do is get all the books that have more than N pages. This would be really easy to do in normal circumstances but in this case I need to cast the value of the metrics and then do the filter. I have tried the following: from django.db.models import IntegerField from django.db.models.functions import Cast from . import models value = 50 pages_metric = models.MetricType.objects.get(label='Pages') models.Book.objects.annotate( pages=Cast('metrics__value', IntegerField() ).filter( metrics__metric_type=pages_metric, pages__gte=value ) I'd like to get one book, but … -
How to add settings for admin to change edit some variables?
I want to give admin access for some variables like changing the message text or changing the Index page text. How could i do that? -
Can't modify files created in docker container
I got a container with django application running in it and I sometimes go into the shell of the container and run ./manage makemigrations to create migrations for my app. Files are created successfully and synchronized between host and container. However in my host machine I am not able to modify any file created in container. This is my Dockerfile LABEL maintainer="Marek Czaplicki <marek.czaplicki@dlabs.pl>" WORKDIR /app COPY ./requirements.txt ./requirements.txt RUN set -ex; \ apk update; \ apk upgrade; \ apk add libpq libc-dev gcc g++ libffi-dev linux-headers python3-dev musl-dev pcre-dev postgresql-dev postgresql-client swig tzdata; \ apk add --virtual .build-deps build-base linux-headers; \ apk del .build-deps; \ pip install pip -U; \ pip --no-cache-dir install -r requirements.txt; \ rm -rf /var/cache/apk/*; \ adduser -h /app -D -u 1000 -H uwsgi_user ENV PYTHONUNBUFFERED=TRUE COPY . . ENTRYPOINT ["sh", "./entrypoint.sh"] CMD ["sh", "./run_backend.sh"] and run_backend.sh ./manage.py collectstatic --noinput ./manage.py migrate && exec uwsgi --strict uwsgi.ini what can I do to be able to modify these files in my host machine? I don't want to chmod every file or directory every time I create it. For some reason there is one project in which files created in container are editable by host machine, but … -
Mocking a celery task call
I have a celery task that needs to be mocked. It is being called as:- def trigger_task(id): task_name(id).delay() I tried using this but because I am passing a parameter it is not getting mocked properly. @patch('domain.tasks.tasks.task_name.delay') def test_abc: pass How can i Mock it? -
Django Coalesce returns null if no rows are found
I'm using the Coalesce function to prevent an aggregate Sum from returning None Coalesce(Sum('ext_price'), 0) The problem is that if no rows are found it still returns null. Is there a way to modify the function so it returns zero if no rows are found? class Coalesce(Func): """Return, from left to right, the first non-null expression.""" function = 'COALESCE' def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError('Coalesce must take at least two expressions') super().__init__(*expressions, **extra) -
Execute a python function without response - Django
I'm working with Django in a project and I need to execute some functions depending on what user's want to do. If this action has to return and show new values I know how to do it, but when I just want to execute a function in my views.py that I don't need any response and don't know how to do it. Now what I'm doing is return something and don't use it, but I'm sure it is possible do it without returning anything. My code that returns a response is: $('#import_btn').click(function(){ updateData() }); function updateData(filt){ console.log('Hello'); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: '/../../updateBBDD/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'Filt': filt, }, dataType: "json", cache: true, success: function(response) { var cols = response.Cols; } }); } How I have to do it in my js to execute a python function with no response?? Thank you very much. -
Bootstrap distance between buttons in navbar
I have a problem with bootstrap. I tried to do simple site in django, I created navbar from bootstrap with some buttons depends of user. It's looks that: And as U can see, the distance between buttons is zero. I tried a margin css as internet say, and even something stupid like adding 'space'. But usually nothing changes. For sure I just do something wrong. So I decide to ask here. My CSS is basic, I want to learn it but first it I want to end django tutorial, and I stuck here. My actual code: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/heroes/">SNP list <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/heroes-new">New SNP</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> {% if user.is_authenticated %} <a> Witaj {{ user.username }} </a> {% if request.user.is_staff %} <a role="button" class="btn btn-outline-success btn-sm my-2 my-sm-0" href='/admin/'> Panel admina </a> {% endif %} <a role="button" class="btn btn-outline-success btn-sm my-2 my-sm-0" href='/logout/'> Logout </a> {% else %} <a role="button" class="btn btn-outline-success btn-sm my-2 my-sm-0" href='/login/'> Login </a> {% endif %} </form> </div> </nav> How can I handle it to make distance between that buttons? And... what should I know to handling … -
update an object in django model
I have a model in my app named foo class foo(models.Model): a = models.CharField(max_length=500, default=0,null=True) a_quantity = models.CharField(max_length=500, default=0, null=True) and I am updating this model from another form like this: def form_valid (self, form): product = form.save(commit=False) product.save() data = form.cleaned_data for i in range(1, 9): foo.objects.update_or_create(a=data["a" + str(i)], b=data["a_quantity" + str(i)]) But the problem here is that it creates a new entry if a is same but a_quantity. I want that when a is repeated its quantity should be summed to the existing quantity in the model. For eg id my input is this: bar 10 and the table is like this: a a_quantity nar 27 bar 15 lar 10 then when the function is called it should do this: a a_quantity nar 27 bar 15 lar 10 Currently it creates a new entry with the same name and different quantity. How can I do this ? -
How do I run a CGI script in python
I am trying to run a simple program of python when values are sent from html page. The html file is as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css"> <title>Minimum Bootstrap HTML Skeleton</title> <!-- --> <style> </style> </head> <body> <div class="container"> <form action="search.py" method="post"> <input type="text" name="x_name"> <input type="submit" name="submit" value="submit"> </form> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script> <script> </script> </body> </html> And here is my search.py file import cgi import cgitb form = cgi.FieldStorage() name = form.getvalue('x_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (name) print "</body>" print "</html>" Now, when I run the html file and enter name field and submit it, instead of processing the search.py file, it just displays the code written in search.py Like this: Check the output Any help regarding how to proceed further to run the files would be helpful. Thank you -
ModuleNotFoundError: No module named 'bootstrap4'
I installed bootstrap4 with $ pip install django-bootstrap4 It is being installed in this directory C:\Users\trade\techpit-match-env\Lib\site-packages Django seems to be looking at this directory C:\Users\trade\Anaconda3\lib\site-packages\django When I put 'bootstrap4' in the INSTALLED_APPS = ('bootstrap4') variable and then run $ python manage.py runserver I get this error C:\Users\trade\techpit-match-env\Scripts\techpit>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001C4D8F65488> Traceback (most recent call last): File "C:\Users\trade\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\trade\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\trade\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\trade\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\trade\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\trade\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\trade\Anaconda3\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\trade\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\trade\Anaconda3\lib\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 'bootstrap4' How can I resolve this error? I installed bootstrap4 in the django folder by using copy and paste and that did not work. Any help would be greatly appreciated. Thank You! -
'Event' object has no attribute 'get'
[Error on 'Event' object has no attribute 'get' ] (https://forum.djangoproject.com/t/error-event-object-has-no-attribute-get/596) anyone help me please -
Django Display User as user Full Name in Admin Field
I got stuck when trying to display User foreign as use full name models.py class Customer(models.Model): name = models.charfield(max_length=100) sales = models.foreignkey(User, on_delete=models.CASADE) admin.py <pre> @admin.register(Customer) list_display = ('name', 'sales') </pre> nah by default sales as user foreign display as username. But i want display it to first name or full name -
django two templates inside eachother Could not parse the remainder
I've got the error Could not parse the remainder: '"' from '"' in this part of my code: {% include 'test.html' with post_url="{% static 'blog-single.html' %}" %} Is it possible to write something like this in Django templates? -
How to access passed context objects in Django template without using loop (class based view )
views.py class RestaurantDashboard(TemplateView): template_name = "restaurant/restaurant_dashboard.html" def get_context_data(self, **kwargs): context = super(RestaurantDashboard, self).get_context_data(**kwargs) context['profile'] = RestaurantProfile.objects.order_by('id').filter(restaurant_id =self.request.user) return context template.html {% for obj in profile %} <div style="background-color:lightblue"> <h3>{{ obj.id }}</h3> <p>{{ obj.city }}</p> </div> {% endfor %} how to access this data without using a loop ? like i need use the name of the city inside a html tag -
Outputting variable that has new lines in the template breaks the JSON object
<script> window.some_object_that_will_be_used_by_react = { message: "{{ message }}" } </script> This is the code I have in my template. It works fine as long as the message has no newlines. However, if it does, it breaks the whole JSON object. I don't want to use linebreaksbr cause it is shown as <br /> on frontend. How I can solve this? -
Accessing request parameters django
Hi I am trying to capture sms parameters from a request that comes in this format b'name=kcom-sms04&number=%2B255688121131&content=Hello' Above appears when I print HttpRequest.body How can I access number, content and name parameters? I use django. -
How to add one custom column in Django built in auth_user table
I'm trying to ass one status field in my django auth_user(Built In) table. I'm using the below code. from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import User class Auth_user(AbstractBaseUser): status = models.CharField(max_length=12,unique=True) USERNAME_FIELD = 'status' An in the settings.py I'm mentioning like this. AUTH_USER_MODEL = "accounts.Auth_user" but the status field is not getting added in the table auth_user.Can somebody suggest how to add cutom field in Django in built table? -
How to export the result of Django admin custom views as csv?
I've got 4 custom admin views in my UserAdmin, which make queries to the database and render the results in new pages so that I can check a summary of user status immediately in the admin site. Actually, each view contains many Querysets from various models. @admin.register(User) class UserAdmin(admin.UserAdmin): # attributes omitted # ... def get_urls(self): """URLs for the admin views defined below.""" urls = super().get_urls() detail_urls = [ path( '<int:user_id>/challenge_history/', self.admin_site.admin_view(self.user_challenge_history), name='challenge_history', ), # omitted remaining three views # ... ] return detail_urls + urls @staticmethod def user_actions(obj): """Add buttons towards admin views.""" return format_html( '<a class="button" href="{}">Challenge History</a>&nbsp;', reverse('admin:challenge_history', args=[obj.pk]), # omitted remaining three views # ... ) def user_challenge_history(self.request, user_id): # Prepare querysets and some objects I need # ... context = dict( self.admin_site.each_context(request), # querysets and objects # ... ) return TemplateResponse(request, 'custom_admin/user_detail.html', context) # Three more admin views # ... This code works very well, it makes buttons on the User section in the admin site, and they are linked to the custom admin views (each one is connected to the different templates) that I've defined. Now, I'd like to add a button to each custom view which exports the result of each view as … -
How to make a form in django like google form? where user can add or delete field according to their need?User can add up to 10-20 field?
Need to create form where users can add or delete fields acc to their need like user can add email, phone no field in the form or like family info, etc or if the user doesn't want that field he can delete the field. Which Django property I can you to create this form or field. -
Deploying Django in nginx server on Windows
I have a django project . I want to deploy in nginx server.I have uploaded my files via FTP. How to configure my python files in nginx . I am using windows 7. -
AttributeError: 'NoneType' object has no attribute 'save' django
i have three models when i create user it will create userprofile and when i userprofile gets created it should create artist. everything working fine but when i update userprofile its getting error models.py: class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100,null= True) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return str(self.name) class UserProfile(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete= models.CASCADE) artist = models.ForeignKey(Artist,related_name='userprofile', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=True) artist_category = models.IntegerField(choices= CHOICES, null=True) mobile_number = PhoneNumberField(null=True) country = CountryField(default = 'IN') city = models.CharField(blank=True, max_length=100) bio = models.TextField(blank=True) def __str__(self): return str(self.user) def create_profile(sender,instance, created,**kwargs): if created: data = { 'name': instance.name } UserProfile.objects.create(user=instance,**data) post_save.connect(create_profile,sender=CustomUser) @receiver(post_save, sender= CustomUser) def save_profile(sender,instance,**kwargs): instance.userprofile.save() def create_artist(sender,instance,created,**kwargs): if created: data = { 'name': instance.name, 'artist_category': instance.artist_category, 'bio': instance.bio } Artist.objects.create(**data) post_save.connect(create_artist,sender=UserProfile) @receiver(post_save, sender= UserProfile) def save_artist(sender,instance,**kwargs): instance.artist.save() its getting none type instance............................................................................ -
Looping through Django Many To Many Form Field
I want to use the Chosen library of Jquery for my ManyToMany Field , This is the model: class StockItem(models.Model): organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE,related_name='organisation_stock_item', null=True, blank=True) stock_name = models.CharField(max_length=100) related_products = models.ManyToManyField("self", related_name="products", blank=True) This is what I have Tried: My forms.py: class StockItemForm(forms.ModelForm): """ Stock Item Form """ class Meta: model = StockItem fields = ('stock_name','related_products') def __init__(self, *args, **kwargs): self.company = kwargs.pop('organisation', None) super(StockItemForm, self).__init__(*args, **kwargs) self.fields['stock_name'].widget.attrs = {'class': 'form-control', } choices = [(ts.pk, ts.stock_name) for ts in StockItem.objects.filter(organisation=self.company)] self.fields['related_products'].choices = choices In my template I tried: <div class="form-group row"> <label class="font-normal col-lg-2">Related Products</label> <div class="col-lg-10"> <select data-placeholder="Choose a Product..." class="chosen-select col-lg-10" multiple style="width:350px;" tabindex="4"> <option value="">Select</option> {% for value, text in form.related_products.field.widget.choices %} <option value="{{ value }}">{{ text }}</option> {% endfor %} </select> </div> </div> The Items Are Rendering Correctly, But when trying to save the related products its not saving them at all i.e. when I am going to my update view I see the related product are not selected. Can any one tell me what is wrong in my code? I am Using Chosen jQuery Multi-Select for this operation. -
Django session in AWS EKS
My Django application is running in 3 nodes(AWS EKS) and the application is running in https. The Django session(LoginRequiredMixin) is dropping and I am not able to login to the application. I define the Django CACHE as below in settings.py SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" SESSION_CACHE_ALIAS = "default" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://XXXXXXXXXXXXXXX.XXXXX.amazonaws.com:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } How to create the session when the application is running in AWS EKS with multiple nodes? -
file uploading is successful in Postman but not in Ajax
I want to upload the file with Ajax in DRF, but I fail! var form = new FormData(); form.append("files[1]file", "/home/mshzsh/Pictures/photo.jpg"); var settings = { "async": true, "crossDomain": true, "url": "http://127.0.0.1:8000/api/pc/update/155/", "method": "PUT", "headers": { "User-Agent": "PostmanRuntime/7.20.1", "Accept": "*/*", "Cache-Control": "no-cache", "Postman-Token": "379c280a-c620-4e5f-8b9b-0ace0a9e6fa6,8c381931-20bb-480d-827d-11bb05718224", "Host": "127.0.0.1:8000", "Content-Type": "multipart/form-data; boundary=--------------------------641148104724362550775599", "Accept-Encoding": "gzip, deflate", "Content-Length": "1355503", "Connection": "keep-alive", "cache-control": "no-cache" }, "processData": false, "contentType": false, "mimeType": "multipart/form-data", "data": form } $.ajax(settings).done(function (response) { console.log(response); }); I have copied these codes from the postman but I get error : The submitted data was not a file. Check the encoding type on the form. in Ajax. I tried a variety of AJAX methods but failed!