Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: Changing a value based on related model
I want to set a value into a field, which depends on another field from another model. I'm having a model CollectionObject and Transaction, those have a many-to-many relationship. My code looks like this: collectionobject/model.py: from django.db import models from collectingevent.models import CollectingEvent # Create your models here. ## Collection Object class CollectionObject(models.Model): ID = models.IntegerField(primary_key=True, editable=False) inventory_number = models.CharField(max_length=500) remarks = models.CharField(max_length=500) collecting_event = models.ForeignKey(CollectingEvent, related_name='collection_object', on_delete=models.DO_NOTHING) # many-to-1 class Meta: #ordering = ['pk'] db_table = 'collection_object' transaction/models.py: from django.db import models from collectionobject.models import CollectionObject ## Transaction class Transaction(models.Model): class TransactionType(models.TextChoices): LOAN = 'loan', DIGITIZATION = 'digitization', MOVEMENT = 'movement', RESAMPLING = 'resampling' ID = models.IntegerField(primary_key=True, unique=True, editable=False) collection_object_ID = models.ManyToManyField(CollectionObject, related_name='status')#, on_delete=models.DO_NOTHING)#CollectionObject, related_name='transaction')#, on_delete=models.DO_NOTHING) # many-to-many transaction_type = models.CharField(max_length=500) # TODO: here choices transaction_date = models.DateTimeField() remarks = models.CharField(max_length=500) class Meta: db_table = 'transaction' collectionobject/serializer.py: from rest_framework import serializers from .models import * from collectingevent.models import CollectingEvent from transaction.serializers import TransactionSerializer class CollectionObjectSerializer(serializers.ModelSerializer): # many-to-1 collecting_event = serializers.PrimaryKeyRelatedField(queryset=CollectingEvent.objects.all(), many=False) # 1-to-many determination = serializers.PrimaryKeyRelatedField(many=True, read_only=True) # transaction available = serializers.BooleanField(default=True) status = TransactionSerializer(many=True) class Meta: model = CollectionObject #fields = "__all__" fields = ( 'ID', 'inventory_number', 'available', 'status', 'remarks', 'collecting_event', 'determination', ) And transaction/serializer.py: from rest_framework import … -
ValueError: invalid literal for int() with base 10: '' only on Windows [closed]
I'm getting this error on Windows 10 native Python 3.8 + Django 2.2.7 setup. Doesn't throw any error in Docker or VirtualBox setup. ValueError: invalid literal for int() with base 10: '' -
django user queryset to profile queryset
I am trying to convert a query set to one to one related query set. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) one user must have one profile in the database. from django.contrib.auth.models import User us = User.objects.all() # is there a way t o convert user query set to profile query set? PS: I need profiles to be a query set instead of a list to perform future functioning. I have read the query set api reference and tried prefetch_related but did not work. I will be very glad with your help. -
How to make FK field in Django Admin not a link?
So...I am trying to alter the highlighted field as visible in the attached snip, in order to make it such it's not a link (does not redirect to the /change form - link visible in the lower part of the snip). The aforementioned field is a PK in another table and a FK in this table. And the end result would be that the field can be edited and is visible as a link for the users with the is_superuser flag and not editable and visible only as a string for the users that have the is_staff flag. I was already here and down the rabbit whole. Using readonly_fields makes the field uneditable, which is good, but does not remove the link. From the info that I found until now, it would seem that setting the list_display_links() to None does not work for the add/change forms that come out of the box with Django and it can only be used in the general list/table templates that show the model elements/entries/records from the db. Looking forward to getting some help if possible. Thank you. snip with the current behavior -
Django Admin, show inline based on slug
Have the following models class FootballWebsite(models.Model): """Football service website.""" url = models.URLField, unique=True) #football service id = models.CharField(primary_key=True, #is this domain blocked blocked = models.BooleanField(default=False) #is it online or offline online = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True, auto_now_add=True) sub_categories = models.ForeignKey(SubCategory, default=1) referral = models.TextField(blank=True) mirror = models.ForeignKey('FootballWebsite', blank=True, null=True) rank = models.PositiveIntegerField(default=0, blank=True, null=True) screenshot = models.BooleanField(default=False) class Meta: """Meta class.""" app_label = 'ahmia' def __unicode__(self): return u'%s' % (self.url) """The datetime when the football service was last seen online""" try: return self.footballwebsitestatus_set.filter(online=True).latest('time').time except FootballWebsiteStatus.DoesNotExist: return None class FootballWebsiteDescription(models.Model): """Football service website description.""" about = models.ForeignKey(Footballebsite) title = models.TextField(blank=True, null=True) keywords = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) relation = models.URLField(blank=True, null=True) subject = models.TextField(blank=True, null=True) type = models.TextField(blank=True, null=True) updated = models.DateTimeField(auto_now=True, auto_now_add=True) language = models.TextField(null=True, blank=True) contactInformation = models.TextField(null=True, blank=True) officialInfo = models.BooleanField(default=False) slug = AutoSlugField(populate_from=['title'], allow_duplicates=True, null=True) class Meta: """Meta class.""" app_label = 'ahmia' def __unicode__(self): return unicode(self.about.url) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(FootballebsiteDescription, self).save(*args, **kwargs) def __unicode__(self): return u'%s' % (self.title) I have a huge amount of links, and i would like to bulk assign them into a category or mark them as blocked based on identical title slug. Managed to at least get … -
Django ORM if subquery
Is it possible in Django ORM use CASE with subquery? I want to change my query string if subquery gives me exact value. something like this subq = NetData.objects.filter(port=OuterRef('abc')).values('value') query_string = Sometable.objects.annotate(another_value=Case (When(Subquery(subq) = 'value', then = Value('123')), default=Value('123'))).filter(**finder) -
Aggregate tag names in Django Taggit
I am using the django taggit library. I have a Queryset that lists objects, which have a few tags attached to each object. How to get them all in one query? While I know how to get tags for each objects on model level, I haven't found a way to do so at Queryset level. How to get all objects tags in Queryset in the same query? Something like Book.objects.filter(year=2020).values('bookname', 'published_at', 'tag_names_list')[:] -
Gmail less secure app access is no longer available I am getting errors
I am sending mail using django as EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "ali412514n@gmail.com" EMAIL_HOST_PASSWORD = env("GMAIL_PASSWORD") now that google turned off less secure app, I am getting errors. any solutions? -
Django User specific page
I m creating a Leave Web Application. I want to show each user's leave status according to the user who is logged in. from django.db import models from django.contrib.auth.models import User types_of_leaves = ( ('Sick Leave', 'Sick Leave'), ('Earned Leave', 'Earned Leave'), ('Annual Leave', 'Annual Leave'), ) # Create your models here. class LeaveApp(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE) fdate = models.DateField() tdate=models.DateField() type_of_leave=models.CharField(max_length=20 ,choices =types_of_leaves, default = "" ) reason = models.CharField(max_length=500) def __str__(self): return self.reason class Sick_leave(models.Model): leave=models.CharField(max_length = 40) def __str__(self): return self.leave -
Django filter by empty string or empty string made of spaces
I would like to filter by a given name that is either an empty string or a string of only blank spaces For example, I have these names name1 = '' name2 = ' ' name3 = ' ' name4 = 'john door' I would like the query to return all values without characters but made of only spaces which in this case name 1, 2 and 3 Here is my initial attempt but I think it can be made more accurate. missing_names = Loan.objects.filter( Q(Q(name__startswith=' ') & Q(name__endswith=' ')) | Q(name__exact='') ) -
In my django project wanted to show specific data on bootstrap modal as per project grid clicking but it's showing first grid data only
Here's my Model View Template enter image description here -
Calculation is producing wrong result in annotate using Django ORM
I am using this query to calculate the total amount, but also deducting discount and adding Sales tax. But in second annotate I am not getting correct results, as you can see the query is straight forward to calculate sales tax (price + price * tax_percentage / 100). After struggling for hours, I couldn't figure it out, Am I doing something wrong ? Order.objects.filter(customer__zone__distribution=get_user_distribution(request.user.id)) .annotate(trade_price=ExpressionWrapper( Sum(F('items__trade_price') * ExpressionWrapper(0.01 * (100 - F('items__discount__discount')), output_field=DecimalField()) * F('items__quantity') ) , output_field=DecimalField() ) ).annotate(total_price=F('trade_price') + F('trade_price') * Sum(F('items__sales_tax__percentage') / 100)) -
Django Form Date Input Field Not Showing Errors
I have a form on a registration page that requires a date to be entered, along with a few other fields. If the user enters non-valid information into the date field (like a string) and submits the form, Django rejects the form as non-valid, but I don't get any error messages on the page - But for the other fields on the form, I do get error messages (ex: Passwords Don't Match, User Already Registered, etc). Here is what the form looks like: Link to image of registration form Here is my forms.py file - I'm using two classes to create the form on the registration page: from django import forms from users.models import Profile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User #fields = UserCreationForm.Meta.fields + ("email",) fields = ['username', 'email', 'password1', 'password2'] class EmployeeForm(forms.ModelForm): hireDate = forms.DateField( required=False, error_messages={'required': 'Please enter a valid date'}, input_formats=[ '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y' ]) # '10/25/06') class Meta: model = Profile fields = ['hireDate', 'employeeNumber'] Here is the models.py field with the model for the profile: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class … -
SSE streaming api call more the 50 at a time in django
I have created a simple SSE streaming URL in Django(3.2.13). def index(request): def chunks(): c = 0 while True: c += 1 yield "\ndata: {}\n\n".format(c) time.sleep(1) return StreamingHttpResponse(chunks(), content_type='text/event-stream') my query is when I run this on a single tab on the browser it frequently. but when I run more than 6 tabs it does not work on the 7th tab and more, so how to create an SSE streaming URL that runs more than 50 tabs at a time. -
How to double click on the login button in test selenium
I'm testing my Django application with selenium. I would like to click on the login button twice in a row to raise the 403 error "CSRF token missing or incorrect." I tried to do it like this: btn = self.driver.find_element(By.ID, "buttonLogin") btn.click() btn.click() Not working... I also tried this : element = self.driver.find_element(By.ID, "buttonLogin") actions = ActionChains(self.driver) actions.double_click(element).perform() Do you know how I can click multiple times on the same button before the page changes ? Thanks ! -
How to exclude certain urls from django debug tool bar?
My settings.py file looks like- import os # This file contains Django settings for lower environments that use the Django Debug Toolbar. # Currently those envronments are DEV and QA. from core.settings import * # noqa: F403 # We need the ability to disable debug_toolbar for regression tests. DEBUG = os.getenv('DEBUG_MODE', 'FALSE').upper() == 'TRUE' def toolbar_callback(request): return DEBUG DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": toolbar_callback, } INSTALLED_APPS += ['debug_toolbar', ] # noqa: F405 MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] # noqa: F405 I want to exclude certain pages from loading debug toolbar. The reason being that the pages have a lot of SQL and debug toolbar is taking too long to load and hence page results in a timeout -
why can't import django in vscode
Help me please figure out what this is about, it shows that Django is not found `from django.urls import path urlpatterns = [ path('', views.index, name='index') ]` -
Django admin application works 100% for superuser but for staff users with full permissions some apps don't appear for users
My Django admin application works 100% for superuser but for staff users with full permissions some apps like GARAGE don't appear for users even though it has full permissions! How can I debug or where can I be blocking this access in my code? I don't use decorator or proxy! I don't use custom template! I don't have has_perm or has_module_perms in my code Permissions user all users permissions actived Admin Site Django Admin dont show App #settings.py INSTALLED_APPS = [ 'garagem.apps.GaragemConfig', 'ckeditor', 'covid', 'documento', 'agenda.apps.AgendaConfig', 'mailer', 'ouvidoria.apps.OuvidoriaConfig', 'licitacao.apps.LicitacaoConfig', 'demanda.apps.DemandaConfig', 'compras.apps.ComprasConfig', 'procedimento.apps.ProcedimentoConfig', 'solicitacao.apps.SolicitacaoConfig', 'endereco.apps.EnderecoConfig', 'servidor.apps.ServidorConfig', 'parametros.apps.ParametrosConfig', 'comunicacao.apps.ComunicacaoConfig', 'receita.apps.ReceitaConfig', 'artigo.apps.ArtigoConfig', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar', 'core', 'rest_framework', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) #urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView from . import views from django.views.generic import TemplateView # <-- from django.contrib.auth import views as auth_views import debug_toolbar from rest_framework.schemas import get_schema_view from rest_framework import routers from servidor.api import viewsets as servidorsiewset route = routers.DefaultRouter() route.register(r'servidorapi', servidorsiewset.ServidorViewSet ,basename='servidorapi') favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True) urlpatterns = [ path('garagem/', … -
serializer import error in django rest-framework
#serializers.py from rest_framework import serializers class CommunitysStaffSerializer(serializers.ModelSerializer): role = serializers.CharField(max_length=100,default='management') community = serializers.PrimaryKeyRelatedField(read_only=True) user = serializers.PrimaryKeyRelatedField(read_only=True) #views.py from rest_framework.response import Response from admindashboard.serializers import CommunitysStaffSerializer @api_view(['POST']) def Communitystaff(request,pk=None): if request.method == 'POST': serializer = CommunitysStaffSerializer(data = request.data) if serializer.is_valid(): Staff = CommunityStaff.objects.get(id = request.data['id']) Staff.community=serializer.validated_data['community'] Staff.role=serializer.validated_data['role'] Staff.save() return Response({'detail': 'entry successfully'}) else: return Response({'error': 'unable to entry staff'}, status=status.HTTP_400_BAD_REQUEST) else: return Response (serializer.data) #error File "C:\Users\Pinakee.Somyadarshee\Desktop\mykommunity\admindashboard\urls.py", line 2, in from admindashboard.views import Login_post,City_post,City_list,City_update,City_remove,Community_update,Community_list,Community_post,Community_detail,Admindash_list,Admindash_update,Admindash_remove,Admindash_post,Admindash_detail,Communitystaff File "C:\Users\Pinakee.Somyadarshee\Desktop\mykommunity\admindashboard\views.py", line 11, in from admindashboard.serializers import CommunitysStaffSerializer ImportError: cannot import name 'CommunitysStaffSerializer' from 'admindashboard.serializers' (C:\Users\Pinakee.Somyadarshee\Desktop\mykommunity\admindashboard\serializers.py) -
Django socketio history
I am trying to do a chat app in django with socketio. I tried to do it from this video. I did it but how can I add history to the chat with consume the least space in my computer? With history I mean even for example if I refresh the page or close the computer If I go again I will see the same conversation. But I don't want the messages consume much space in my computer. -
django pagination duplicate posts
Hello i got a wierd error pagnation works fine on my home.html but in my categories.html it duplicate post as soon as it paginates how can i fix this. Here is code to the files that the problem is in. problem should be from the def CategoryView. i tried to change the order_by id and some small stuff in the categories but cant understand why post duplicates on pagnation. views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator def LikeView(request, pk): post = get_object_or_404(Post, id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name = 'home.html' cats = Category.objects.all() ordering = ['-post_date'] paginate_by = 3 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', { 'cat_menu_list': cat_menu_list}) def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, … -
Django Q Error: could not translate host name "db" to address: Temporary failure in name resolution
This is the docker compose production configuration that I have created: version: '3' services: db: image: postgres:12.8-alpine restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db ports: - 5400:5432 redis: image: redis:alpine ports: - 6379:6379 web: build: context: . dockerfile: Dockerfile volumes: - .:/ps_survey - static_volume:/ps_survey/staticfiles env_file: - ./.env.prod depends_on: - redis - db django-q: build: . command: python manage.py qcluster volumes: - .:/ps_survey env_file: - ./.env.prod depends_on: - redis nginx: build: ./nginx volumes: - static_volume:/ps_survey/staticfiles ports: - 86:80 depends_on: - web volumes: postgres_data: static_volume: Dockerfile configuration: FROM python:3 WORKDIR ./ps_survey ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./req2.txt . RUN pip install -r req2.txt COPY . . CMD gunicorn ps_survey.wsgi:application --bind 0.0.0.0:8000 .env.prod configurations DEBUG=0 SECRET_KEY='******************************' DJANGO_ALLOWED_HOSTS=["*"] DB_NAME=********* DB_USER=********* DB_PASSWORD=******** DB_HOST='db' DB_PORT=5432 EMAIL_HOST_PASSWORD=********** EMAIL_HOST_USER=********** EMAIL=************* PASSWORD=********** BACKGROUND=True .env.prod.db configurations POSTGRES_USER=******* POSTGRES_PASSWORD=****** POSTGRES_DB=******* Error that I am getting : django-q_1 | 16:00:19 [Q] ERROR could not translate host name "db" to address: Temporary failure in name resolution Because of which, the task is not running -
Running Django + Postgresql + Gunicorn in Docker container using compose - file permission errors
I am using Docker-desktop version version 20.10.16 on Ubuntu 20.0.4 LTS I want to Dockerise Django (v3.2), PostgreSQl (v14.3) and Gunicorn (v20.1.0) in a single container. And use those containers as Virtual hosts being serviced by a single Nginx instance that is running on my local machine. I am able to build images, and a container, but setting up the django application fails, because of a file error in creating/writing to myporoj.log I am currently, not using nginx as a proxy server to the virtual hosts - I want o resolve this isse first before moving on to using Nginx with my setup. Here are additional relevant details: My file structure (on local machine), is as follows: /path/to/myprojectweb/ /myproj /myproj settings.py wsgi.py # etc. Dockerfile.prod compose.prod.yml Dockerfile.prod.yml # Builder Image FROM python:3.8-slim-buster as Builder WORKDIR /usr/src/app ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWEITEBYTECODE 1 RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev RUN pip install --upgrade pip pipenv COPY Pipfile* ./ RUN pipenv lock --keep-outdated --requirements > requirements.txt \ && pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt # Final Image FROM python:3.8-slim-buster RUN mkdir -p /home/app /var/log/gunicorn # create user + group app that apps will run as. … -
How to get Select Option Value in Views Django
This is my HTML form template <form action="" method="post"> {% csrf_token %} <div class="d-flex form-inputs"> <select class="form-select" aria-label=".form-select-lg"> <option selected>Spanish To English</option> <option selected>English To Spanish</option> <option value="1">French To English</option> </select> <input name="txt" class="form-control p-3" type="text" placeholder="Search..."> <a href="#"><img src="/static/assets/image/search.png" alt=""></a> </div> </form> I want to get User selected value from Select Option to views. This is views function def lang_convert_view(request): if request.method == "POST" and 'txt' in request.POST: txt = request.POST.get('txt') data = custom_function_name(txt) context = {'data': data} else: context = {} return render(request, 'index.html', context) Anyone, please help me -
How do I format Django form CharFields to be next to each other one the same line?
Currently, I'm using a the Django Form class to create a form. I'm trying to make it so that all of the CharField fields have their own row, except for a few specific one's that I would like to share a row. These are the CharFields I currently have: class ExampleForm(forms.Form): example_1 = forms.CharField(max_length=20, required=False) example_2 = forms.CharField(max_length=20, required=False) example_3= forms.CharField(max_length=20, required=False) def __init__(self, *args, **kwargs): super(MetadataForm, self).__init__(*args, **kwargs) self.fields['example_1'].widget.attrs['style'] = 'width:15%;' self.fields['example_2'].widget.attrs['style'] = 'width:15%;' self.fields['example_3'].widget.attrs['style'] = 'width:15%;' Here is how they're rendered in the HTML: <label for="id_example_1">Example 1:</label> <input type="text" name="example_1" maxlength="20" style="width:15%;" id="id_example_1"> <label for="id_example_2">Example 2:</label> <input type="text" name="example_2" maxlength="20" style="width:15%;" id="id_example_2"> <label for="id_example_3">Example 3:</label> <input type="text" name="example_3" maxlength="20" style="width:15%;" id="id_example_3"> In an attempt to format example_1 and example_2 on the same line, I tried floating the labels to the left and then adding space between them by increasing the margin: #example_1, #example_2, #example_3 { float: left; margin-left: 100px; } However, while this formats the boxes very oddly: It also doesn't do anything for the labels. I'm not sure how to reference the labels since they don't have id values I can use. If there's a way that I can have example 2 and 3 formatted on the …