Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to customize fields in nested serializer?
class ListSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = JobseekerProfile fields = ('user',) *How to modify this fields so that I can add only one field from user like user.username? * -
How to put Image reference in Character Field in Django db?
I am making an E-learning website using Django. The website would have questions along with answer options from which the user has to choose the correct answer. Most of the answer options are texts because of which I have declared the options in my model as CharField. class Question(models.Model): question = models.CharField(max_length=250) option_1 = models.CharField(max_length=50) option_2 = models.CharField(max_length=50) option_3 = models.CharField(max_length=50) option_4 = models.CharField(max_length=50) But I realized that in some questions, instead of text fields there are images as options. For example, there will be four images instead of texts and the user has to choose one answer among them. How do I include both ImageField and CharField in my model as answer choices? -
Modbus sensors in Django project
I'm working on a project in Django/Python. In one of the applications, we need to get data from the water level sensor and write it to the SQL database. Users should see the information from the sensors in one of the tables on the site. The sensors operate via the ModBus protocol. I found out that there are at least three Python libraries for working with Modbus (pymodbus, MinimalModbus, Modbus-tk), and there are also OPC servers that, as far as I understand, can read data from Modbus devices themselves and allow them to be managed, for example, via the REST API. I need advice on which software architecture is best to choose, taking into account the goal. What is better to read about possible solutions to such problems? -
Please help me with this question if anybody have a solutions
I have one model in that, I have many attributes I want to query the attributes based on the term in a search query for that I have applied Q annotate method, like below result = queryset.filter(Q(cu__icontains=term) | Q(s__icontains=term) | Q(region__icontains=term) |Q(owner__icontains=term) | Q(irr_no__icontains=term) | Q(contactperson__icontains=term) | Q(targetdate__icontains=term) | Q(briefinquirydescription__icontains=term)) Instead of this if I made a list of all attributes of my model like list = ['sdf','sf','ff','fffd','fdf','fdf','gg'] how I can query for a list of attributes of my model, any methods for this please guide or suggest other methods -
What is the best backend if front-end is React for CNN model? [closed]
I have front-end in react.js because I have expertise in it. -
Performance issue with django postgres delete
In my application I have a caching mechanism for requests to a different API. This is designed to store the request and response for 24 hours. Every-time the 24 hour limit is over the entry gets deleted from the database before creating a new request and saving the result again in the cache. It seems like there is an issue with a delete, only from time to time. Some of my delete requests take multiple minutes, even though the caching database has only around 100 entries and consists of a url, params (md5), body (md5), response and created date field. I analyse the performance through sentry. Below you can find a screenshot of the event. As you can see there is also a select beforehand that has no performance issue. Furthermore it happens that the delete has no performance issue. The database is a postgres database that runs on a different dedicated server. I already tried to recreate the database but without any success. I would assume that the ssh connection should not be the problem, because the select before the delete runs without any issue (and there are other selects beforehand as well. I also checked and debugged the … -
Make Django fail silently if an image isn't found
I'm getting a 500 error because when I run the app locally it tries to load an image that only exists on the production server. How do I make Django fail silently when this happens. I'm unable to load any page that has an image in it. -
Django User locked for 30 minutes after many attempts login failed
User will be locked out for 30min if the password is incorrect 5 times within 10min advance thanks -
Django format string based on model fields
Let's say we have a very big string with 3 parameters: "Stack Overflow is the {0} place to {1} answers from {2} problems" The parameters are based on model fields that calculated at runtime. Is it possible to store the model fields on another table? eg: | position | param | |---------------------|------------------| | 0 | modelA.field0 | | 1 | modelA.field1 | | 2 | modelB.field0 | and use them accordingly to format the above string? -
How to do Live search Using Fetch Ajax Method In Django Python?
I am getting Post.match is not a function error when i do this :( Please help, i am a newbie in JavaScript part. (I am getting back an object so have to turn it into an array but still get this error after using the Objects.values Method) My Views.py File: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Post def Data(request): items = Post.objects.all() data = [] for qs in items: I = {"title":qs.title, "content": qs.content, "image": qs.image.url, } data.append(I) return JsonResponse({"data":data}) My HTML File: {% extends 'blog/base.html' %} {% load static %} {% block content %} <div class = 'w-100 text-center'> <h1>Search Results</h1> <form id = "search-form" autocomplete="off"> {% csrf_token %} <input name = 'game' type="text" id = "search-input" placeholder= "Post Search.."> </form> <div id = "results-box" class = "results-card"> </div> </div> {% endblock content %} {% block js %} <script defer src="{% static 'blog/S1.js' %}"> </script> {% endblock js %} My Java Script File: console.log('Heelowwww') const url = window.location.href const searchForm = document.getElementById("search-form") const searchInput = document.getElementById("search-input") const resultsBox = document.getElementById("results-box") const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value options = {method: "GET", headers: { Accept: "application/json" }, data:{ 'csrfmiddlewaretoken': csrf, } } const SearchPosts = async SearchIt … -
UnidentifiedImageError at /login/ cannot identify image file 'default.jpg' [duplicate]
This error occours when I try to login to the account this is my models.py which I have used to resize my image: from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) image = models.ImageField(default = 'default.jpg',upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open((self.image.name)) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) This is my signals.py it states that the error is in line 14 of 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 from django.core.exceptions import ObjectDoesNotExist @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, created, **kwargs): try: instance.profile.save() except ObjectDoesNotExist: Profile.objects.create(user=instance) please help me solve this error I will upload files if you need any other -
Show result of form submitting in pop up box in javascript after submitting form
I have used Django to develop a web app. I want to show the form submitting result in pop up box immediately after form submmited in Django I have caught the form submitting result in messages, but could not show it immediately in javascript pop up box. 1 I could not pass the messages to js immediately. The {{ messages }} I console.log in js does not out put anything. 2 I do not know how to generate the pop up box immediately after submitting the form. view.py: def content_checklist_name_url(request): if request.method == 'POST': Course_Form = ContentChecklistForm(data=request.POST) # Check if the form is valid: if Course_Form.is_valid(): messages.success(request, 'Entries have been saved.') else: messages.error(request, 'Form error') HTML: <script> {% block script %} var a = "{{ messages }}"; console.log(a); if ({{ messages }} == "Entries have been saved.") { alert("success"); } else { alert("fail"); } <script> How to change my code to do a immediate pop up box to show the form submitting results? -
Django Dynamic Template with Custom function problem
As I have using the django custom table for authentication and session id for setting the navbar action but not able to change with custom function able to find similar things but how i can write my custom function pls find Code for userauth inbuilt management which i intent to change user.authenticated to a custom function {% if user.is_authenticated %} {{user.username}} <li><a href="/logout">Logout</a></li> {% else %} <li><a href="/login">Login/a></li> <li><a href="/register">Register</a></li> {% endif %} -
How do I implement category selection in Django? Help me. teachers
I'm a student learning Django. I'm trying to make a shopping mall, but I'm having a hard time registering the product. When a member registers a product himself, I would like to select the category designated in the database and register the product. My current code is this, how can I select a category as a drop-down and register it? Great developers, I'd really appreciate your help. +I tried other methods, but the form is not applicable. Is there any other way than to designate category_code as Choice Field in the form? I'd like to implement a category selection using the drop-down. model.py # 카테고리 class Category(models.Model): category_code = models.AutoField(primary_key=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, allow_unicode=True) class Meta: ordering =['category_code'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_in_category', args=[self.slug]) # 상품 class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): … -
How to use heroku as the main server for my django project
I want to deploy my Django project to the world. I already deployed it to Heroku (currently using the free version) But I am planning on buying a paid version for my project as it has faster access and everything. My problem is I am new to this. I don't know any steps that I have to take before or after buying it. I also want to know how to keep the database changes and media changes. What are the steps that I have to take before deploying it. How to set our own domain i.e I want to get www.myapp.com instead of myapp.herokuapp.com. I am also ready to buy a domain name. If Heroku is not the optimal way to deploy a Django project properly , please share the best ways to do so. Please help me and guide me through all the processes that I have to take to achieve my desired goal. Thank you in advance. -
How can i add field and value on queryset
There is a model class Computer(models.Model): mouse = models.CharField(max_length=15, db_index=True) keyboard = models.CharField(max_length=15, db_index=True) Computer.objects.all().values() > [ {cpu: 'c1', keyboard: 'k1'}, {cpu: 'c2', keyboard: 'k2'} ] there is dict cpuToMouse = {'c1': 'm1', 'c2': 'm2'} I want to add field and value computer = Computer.objects.all() for com in computer: com.mouse = cpuToMouse[com.cpu] and filtering computer.filter(mouse='m2') but.. not working.... i tried annotate computer.annotate(mouse=F(cpuToMouse[com.cpu]) but it's not working too -
Django_q Scheduler Issue
i want to run djangoq-scheduler on every weekend but having two issues with it-: i) creating two entries in django_q_scheduler models as soon as i run development server and qcluster ii) scheduler starts executing immediately as soon as entry is created in the model, instead of executing on every weekend. Here is the code used -: Django-Q Cluster Q_CLUSTER = { 'name': 'DjangQORM', 'max_attempts': 1, 'retry': 14400, 'orm': 'default' } Schedule.objects.create(func='func()', schedule_type=Schedule.CRON, cron='30 18 * * 6' ) Version Used - python-> 3.6.8 django-q -> 1.3.4 Database- postgres OS - Linux -
How to auto populate data from other model and how to add calculated fields?
I am learning django and I have not been able to properly do two things within model clearance: Within modelRetrieve the name fields that correspond to the imo number selected. Autopopulate a date field with the current day plus 7 days. Any ideas what I am doing wrong? Here is my code: from django.db import models from django.core.exceptions import ValidationError from django.utils import timezone from datetime import timedelta, datetime def imo_validator(value): if value < 0 or value > 9999999: raise ValidationError( 'This is not a valid IMO number', params={'value':value}, ) class ship(models.Model): imo = models.IntegerField(unique=True,validators=[imo_validator]) name = models.CharField(max_length=20) rpm = models.FloatField() power = models.FloatField() main_engine = models.IntegerField() class Meta: ordering = ['imo'] def __str__(self): return "{}, (IMO:{})".format(self.name, self.imo) class clearance(models.Model): STATUSES = [ ('PENDING','PENDING'), ('REJECTED','REJECTED'), ('APPROVED','APPROVED'), ] PORTS = [ ('PACAN','PACAN'), ('PABLB','PABLB'), ('PACCT','PACCT'), ('PAANP','PAANP'), ('PAANA','PAANA'), ] date_of_request = models.DateField(default=timezone.now,blank=False,editable=True) imo = models.ForeignKey(ship, on_delete=models.PROTECT) port = models.CharField(max_length=20,null=True,choices=PORTS) eta = models.DateField(null=False) name = ship.name.get(imo=imo) calculated_eta = models.DateField(datetime.today + timedelta(days=1)) aduanas = models.FileField(blank=True) aduanas_ok = models.CharField(max_length=15,default='PENDING',choices=STATUSES,editable=False) minsa = models.FileField(blank=True) minsa_ok = models.CharField(max_length=15,default='PENDING',choices=STATUSES,editable=False) def __str__(self): return "{}, ETA:{}".format(self.imo, self.eta) class Meta: ordering = ['eta'] -
Redirect a user to a 3rd party app with the POST method using Django views
I am trying to make an e-commerce site using Django. And when I want to integrate my webpage with a payment gateway, rather than having the <form method="POST"> in my HTML is there any way I would be able to redirect a user to a third party app FROM the Django views by sending a POST request with values such as payment, first_name etc. Any help is greatly appreciated! -
Django Allauth Override / Extend Password Reset View In Your Own Project
I want to override / extend the allauth password reset view and do it from within my own project. I don't want to explicitly edit the third party allauth code itself and want to keep all the password reset functionality the same - I just want to add additional functionality. This is what I did: from project_app.views import CaptchaPasswordResetView url('^accounts/password/reset/', CaptchaPasswordResetView.as_view(), name="account_reset_password"), class CaptchaPasswordResetView(PasswordResetView): def get_context_data(self, **kwargs): ret = super(CaptchaPasswordResetView, self).get_context_data(**kwargs) return ret The one for the signup view seems to work this same way: Override signup view django-allauth The password reset email sends, the url gets redirected to /accounts/password/reset/done but it does not redirect to the /accounts/password/reset/done template. Any ideas? -
ModuleNotFoundError: No module named 'django_filters' when django-filter is installed
when I try to start my django app by running python manage.py runserver I get the error ModuleNotFoundError: No module named 'django_filters' however I have installed django-filter using pip install django-filterand added 'django_filters' to my INSTALLED_APPS in settings.py as the documentation says. So I'm having a hard time figuring out what's causing this issue. I appreciate any help. Here is my INSTALLED_APPS INSTALLED_APPS = [ 'rest_framework', 'corsheaders', 'students.apps.StudentsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'crispy_forms', ] and these are the packages I have Package Version ------------------- ------- asgiref 3.3.4 Django 3.1.3 django-cors-headers 3.3.0 django-crispy-forms 1.10.0 django-filter 2.4.0 djangorestframework 3.11.0 pip 21.1.2 pytz 2021.1 setuptools 46.0.0 sqlparse 0.4.1 wheel 0.34.2 thanks for any help! -
Convert Django Filters to RAW SQL Queries
Hello Everyone Can anyone Help Me ragarding this? I want to convert a django filter query to raw sql query and below is the example Django Query Product.objects.filter(name__icontains=self.request.GET.get('product_name')) Is there a online method or some other way that i can convert it to RAW sql Query for my postgresql database or any database. I dont know that much about database queries Ill be thankful if someone could help. -
why django auto reload track log file changes
[2021-05-27 02:22:47,349] INFO [django.utils.autoreload] [/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py.trigger_reload():250] /backend/qa/deployment/unify_service/logs/unify_service.log changed, reloading. [2021-05-27 02:22:49,102] INFO [django.utils.autoreload] [/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py.run_with_reloader():636] Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 27, 2021 - 02:22:50 Django version 3.2.3, using settings 'unificater.settings' Starting development server at http://0.0.0.0:7198/ Quit the server with CONTROL-C. [2021-05-27 02:38:45,949] INFO [django.utils.autoreload] [/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py.trigger_reload():250] /backend/qa/deployment/unify_service/logs/unify_service.log changed, reloading. [2021-05-27 02:38:47,472] INFO [django.utils.autoreload] [/usr/local/lib/python3.6/dist-packages/django/utils/autoreload.py.run_with_reloader():636] Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 27, 2021 - 02:22:50 Django version 3.2.3, using settings 'unificater.settings' Starting development server at http://0.0.0.0:7198/ Quit the server with CONTROL-C. each request logging module writing to log file. When file have new entry server will reload automatically. How to exclude logging files from django auto reload ? -
Field 'id' expected a number but got 'gifts'
I'm working on a small project using Django / Rest, i try to open my GenericViewSet method called gifts in my browser but doesn't works if i add a parameter, this is my code : @action(methods=['get'], detail=False) def gifts(self, request, pk=None): getRelatedContact = Contact.objects.filter(account = pk).exclude(id = self.contactID) serializer = ContactSerializer(getRelatedContact, many=True) return Response(serializer.data) This is my urls.py from django.urls import path from apps.contacts.api.views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register(r'contacts', ContactView, basename="contact") urlpatterns = router.urls the urls i follow : /contacts/gifts/1/ but it works fine if I remove the number 1, I mean it works fine if I don't pass a parameter how can I access my gifts method, with a parameter in the url -
Wagtail/Django Internal AttributeError: 'NoneType' object has no attribute '_inc_path'
When I try to publish a Page using the Wagtail CMS I am presented with the following error traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/pages/add/home/product/3/ Django Version: 3.2.3 Python Version: 3.8.5 Installed Applications: ['home', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wagtail.contrib.settings'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback (most recent call last): File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/wagtail/admin/urls/__init__.py", line 108, in wrapper return view_func(request, *args, **kwargs) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/wagtail/admin/auth.py", line 193, in decorated_view return view_func(request, *args, **kwargs) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/wagtail/admin/views/pages/create.py", line 99, in dispatch return super().dispatch(request) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/wagtail/admin/views/pages/create.py", line 107, in post return self.form_valid(self.form) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/wagtail/admin/views/pages/create.py", line 117, in form_valid return self.save_action() File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/wagtail/admin/views/pages/create.py", line 135, in save_action self.parent_page.add_child(instance=self.page) File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/treebeard/mp_tree.py", line 1083, in add_child return MP_AddChildHandler(self, **kwargs).process() File "/home/bailey/.local/share/virtualenvs/shop-ipmx96Bd/lib/python3.8/site-packages/treebeard/mp_tree.py", line 377, in process newobj.path = self.node.get_last_child()._inc_path() Exception Type: AttributeError at /admin/pages/add/home/product/3/ Exception Value: 'NoneType' object …