Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change input type of form field in django forms?
I have a form class in my form.py file where I initiated properties of form fields. I want to change my 'Description' field from an input field to a textarea field of height 5 lines. Also want to change my 'Deadline' field to a date input field because at the moment it's an input text field. class JobPost_form(ModelForm): class Meta: model = Job_post fields = "__all__" def __init__(self, *args, **kwargs): self.fields['Job_role'].widget.attrs.update( {'class': 'form-control Password2', 'id': 'form3Example1c', 'placeholder': 'Job role'}) self.fields['Company'].widget.attrs.update( {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Company'}) self.fields['Deadline'].widget.attrs.update( {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'YYYY-MM-DD HH:MM:SS'}) self.fields['Description'].widget.attrs.update( {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Description'}) -
Selenium thread only works once
I have a dockerized Django app with some threads. Those threads perform periodic tasks, and use Selenium and Beautiful Soup to scrap data and save it to the database. When initializing one thread, the first scrap goes well, data is checked and the function sleeps. However, when the sleep finishes the next scrap isn't performed. This is the thread head code: def thread1(): time_mark = 0 while True: print('Thread1 START') op = funct_scrap(thread1_url) ... sleep(60) The funct_scrap scrapes the web using Selenium, works for the first time but it stops after that. I'd need it to check periodically. In development server works well, but now on Docker there is this problem. What's going on? -
Apex charts only shows latest django value as opposed to latest 12 results
I am trying to get Apex Charts to log values from my django view but I am only getting the most recent value as opposed to the latest 12 values. I may need to do something in javascript to get this to work (like map), but I am struggling to think of what to try next... My Django Model: from django.db import models from datetime import datetime class Telemetry(models.Model): building_name = models.CharField(max_length=200) space_type = models.CharField(max_length=200) reference_point = models.CharField(max_length=100, help_text='eg: ASP') temperature_value = models.DecimalField(max_digits = 5, decimal_places = 2) people_sensor_value = models.IntegerField() humidity_value = models.DecimalField(max_digits = 5, decimal_places = 2) co2_value = models.DecimalField(max_digits = 5, decimal_places = 2) voc_value = models.DecimalField(max_digits = 5, decimal_places = 2) time_stamp = models.DateTimeField(default=datetime.now, blank=True) class Meta: verbose_name = 'Console Value' verbose_name_plural = 'Console Values' def __str__(self): return self.space_type My Django View: def chart_view(request): if not request.user.is_authenticated: return HttpResponseRedirect('/') else: console_points = Telemetry.objects.all()[:12] context = { 'console_points': console_points } return render(request, 'charts/line_charts.html', context) My HTML Template: {% load static %} {% load humanize %} {% block content %} {% for console_point in console_points %} {{ console_point.voc_value }} {{ console_point.time_stamp|naturaltime }} {% endfor %} <section class="row gap-1 justify-center"> <div class="col-1-xs"> <div class="card bg-white"> <div class="card-body"> <h3>Office Temperature</h3> … -
How to save a unique search result in django
I want the user to save individual search result when they click on the star button as shown below in the SS: figure 1 This results are not from the database but rather they are collected from an API.When the user clicks on the "star" button beside each search result,I want this data to be saved in the database.When the star button is pressed,I want this entire piece of data to be passed on to an approrirate function to save it in the database.I need help in forming the url when the button is pressed.Given below is the html part for the "star" button: <a href="#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" class="feather feather-star" > <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon> </svg> </a> </div> ` ` I was thinking of generating unique id for each search result and then pass this along with the url.But dont know how to create the url pattern. -
Can I add search field more than one in django admin
I want to know about can I add another search field more than one. If it can't how can I do for this action I use a long time to solve this problem -
Combining multiple Django filters
So I'm struggling with filtering my products in Django. I currently have a search bar which works and the result of submutting a query ('whey' in this case) looks like this: The thing I can't figure out is how to get the sort filter to work now ('Sorteer op:). Because when selecting an option my function in the view gets called, which looks like this: def zoekopdracht(request): if request.GET.get('search') != '': try: search = request.GET.get('search').lower() queryset = models.Product.objects.annotate(search_name=Concat('title', Value(' '), 'categorie', 'brand' , output_field=TextField())) products = queryset.filter(search_name__icontains=search) product_amount = len(products) # sorteer filter filtered = SortFilter( request.GET, queryset=products ) # paginator paginator = Paginator(filtered.qs, 12) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) product_front_end = { 'final_products': response, 'filter': filtered, 'count': product_amount, } except AttributeError: print(request.GET) response = [] product_front_end = { 'final_products': response, } else: response = [] product_front_end = { 'final_products': response, } return render(request, 'zoekopdracht.html', product_front_end) Because the GET request from the search bar is empty now I lose the products. Is there a way to get the current products back to the view function? That way I can use my SortFilter on the current products. urls.py: urlpatterns … -
Redis is disconnecting in production when using in docker with Django channels
can someone explain what is this error is all about, I am new to Redis and first time I'm using it my websocket connection is rejected by server in the production environment. most of the time it is getting rejected, but one time I got the error like this future: <Task finished name='Task-2137' coro=<Connection.disconnect() done, defined at /usr/local/lib/python3.11/site-packages/redis/asyncio/connection.py:720> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/redis/asyncio/connection.py", line 729, in disconnect self._writer.close() # type: ignore[union-attr] ^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/streams.py", line 344, in close return self._transport.close() ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 839, in close self._loop.call_soon(self._call_connection_lost, None) File "/usr/local/lib/python3.11/asyncio/base_events.py", line 761, in call_soon self._check_closed() File "/usr/local/lib/python3.11/asyncio/base_events.py", line 519, in _check_closed raise RuntimeError('Event loop is closed') in the ubuntu server my Dockerfile looks like this FROM python:3.11.1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] my docker-compose.yaml looks like this version: '3' services: db: image: postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=2221 - POSTGRES_DB=social-network volumes: - db-data:/var/lib/postgresql/data/ ports: - "5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - … -
Has anyone come across django here ever come across a site with two members that have different dashboards. E.g footballers and coaches [closed]
A django sites with two members that can register theiself and each has their own dashboard. E. G a footballer and coach. When a footballer or coach login the system dynamically checks and redirects to the right dashboard users register their self. I can't find a tutorial or project that it has been done and most are redirected using Login redirect in settings -
How to create a custom user model with an email and/or a phone number as a login with Django REST framework?
I want to create the custom user model with the email and/or the phone number as a login. I understood how make them separately but how to combine them together? For instance, should i do the same like this but instead of the email the phone number? Managers.py : rom django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) Models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects … -
How to add object level permission on a particular field of a model in Django Rest Framework?
I have a model: class Employee(models.Model): name = models.CharField(max_length=128) nic = models.CharField(max_length=25, unique=True) def __str__(self) -> str: return self.name class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") def __str__(self) -> str: return self.name class Standup(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.DateTimeField(auto_now=True) This is a viewset: class StandupViewSet(ModelViewSet): serializer_class = serializers.StandupSerializer queryset = Standup.objects.all() When I hit the API to post the data of standup, Standup.employee field should list only that employee who is currently logged in,so that it cannot select other employees. Admin can see all the employees: https://i.stack.imgur.com/sASrq.png Do I need to apply object level permission? How to do it? -
I am not getting my full payload in my Jac program when it is forwarded from Django
When my Django program receives a post request, it extracts the necessary information and forwards it to my Jac Application. But my Jac program is not receiving the full payload. [The payload I received in my Jac application] (https://i.stack.imgur.com/hUTCH.png)[Some of the information sent in the payload] (https://i.stack.imgur.com/SdPxF.png) I tried changing the format of the payload, but my Jac application is still not receiving the complete payload. -
ValidationError pass multi level dictionary insted of single dict
Is there a way to raise a ValidationError with nested dict of errors?. For example: raise ValidationError({ "index_errors": {"index1": { "test_con": "Error text example", "test_con2": "Error text example2" }} } I am getting 'ValidationError' object has no attribute 'error_list' -
Change flag icon position django-countries dropdown
I am using the django-countries module to create a country selector in Django, but the flag appears underneath the selection field instead of in it. Flag icon appears underneath selection field This is the code of forms.py: class TweetForm(forms.ModelForm): class Meta: model = TweetSearch fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country', 'tweet_count'] widgets = {'country': CountrySelectWidget(attrs={'class': 'form-control'}), } How do I change the flag position to inside the selection field? -
WebSocket connection fails Django-channels
I am trying to create a socket-based application using Django-Channels, but I have a problem with connection to the WebSocket. To showcase my problem I created a test project. The error message from the JS Console: WebSocket connection to 'ws://127.0.0.1:8000/' failed: The error appears to happen on the line 25 of the html file, which is creating an instance of a WebSocket() Screenshot of the error Here is the code: # consumers.py import ... class ChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.groupname = 'dashboard' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() ... # routing.py import... websocket_urlpatterns = [ path("", ChatConsumer.as_asgi()), ] # views.py import ... def chatPage(request, *args, **kwargs): context = {} return render(request, "chatPage.html", context) # asgi.py import ... os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ChatApp.settings') application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) } ) # settings.py ... CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } ... <!--chatPage.html--> ... <script> const chatSocket = new WebSocket("ws://" + window.location.host + "/"); document.querySelector("#id_message_send_input").focus(); document.querySelector("#id_message_send_input").onkeyup = function (e) { if (e.keyCode === 13) { document.querySelector("#id_message_send_button").click(); } }; document.querySelector("#id_message_send_button").onclick = function (e) { const messageInput = document.querySelector( "#id_message_send_input" ).value; chatSocket.send(JSON.stringify({ message: messageInput, username : "{{request.user.username}}"})); }; chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); … -
How to get serializer data before response in DRF ListAPIView to order it by all fields?
I have two models. class Team(models.Model): user = models.ManyToManyField(User, related_name='%(class)s_user') company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') is_active = models.BooleanField(default=True) has_user = models.BooleanField(default=False) class Meta: app_label = 'accounts' class TeamTranslation(models.Model): team_name = models.CharField(max_length=100) team_description = models.TextField() team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='%(class)s_team') languages = models.ForeignKey(Languages, on_delete=models.CASCADE, related_name='%(class)s_languages') is_active = models.BooleanField(default=True) This is list view... class teamListView(generics.ListAPIView): search_fields = ['teamtranslation_team__team_name'] filter_backends = (filters.SearchFilter,) serializer_class = teamSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): accessor_id = self.request.user.id queryset = Team.objects.filter(is_active=True).order_by("id") return queryset def post(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_serializer_context(self): lang_id = UserProfile.objects.get(user_id=self.request.user.id).languages_id return {"lang_id": lang_id} And this is serializer... class teamSerializer(serializers.ModelSerializer): team_id = serializers.IntegerField(source='id') members_count = serializers.SerializerMethodField() team_description = serializers.SerializerMethodField() team_name = serializers.SerializerMethodField() company_code = serializers.CharField(source='company.company_code') def get_team_description(self, obj): lang_id = self.context.get('lang_id') if TeamTranslation.objects.filter(team_id=obj.id, languages_id=lang_id, is_active=True): return f'{TeamTranslation.objects.get(team_id=obj.id, languages_id=lang_id, is_active=True).team_description}' return f'{""}' def get_team_name(self, obj): lang_id = self.context.get('lang_id') if TeamTranslation.objects.filter(team_id=obj.id, languages_id=lang_id, is_active=True): return f'{TeamTranslation.objects.get(team_id=obj.id, languages_id=lang_id, is_active=True).team_name}' return f'{""}' def get_members_count(self, obj): return len(obj.user.values_list('id', flat=True)) class Meta: model = Team fields = ("team_id", "team_name", "team_description", 'members_count', 'company_id', 'company_code', 'has_user') I try to order my data according to query parameter comes from request. So there is no problem when use order_by clause for Team model fields. The problem starts when try to order TeamTranslation fields. … -
When and where is `Model.blank` checked by DRF?
I have a model class SomeModel(models.Model): emails = ArrayField(models.EmailField(), default=list) And let's say I have the following Serializer of the model: class SomeModelSerializer(serializers.ModelSerializer): class Meta: model = SomeModel fields = ['emails'] The email field is not blank-able, i.e: It's required to set a value for it when submitting a Form of the model, or when saving its Serializer. Everything works as expected. So my understanding is that DRF relies on Django's internal machinery to validate whether emails is missing on the Serializer data or not. But the thing is that I can't find where (and when) this happens. I've found that DRF is not calling the Model's clean() method anymore (link)... So do you have any idea of when and where DRF checks for a field's blank value? Thanks! -
DRF with JS Framework retrieving state from URL and making request gets page not found
I'm new in Django. I worked with PERN and PEAN stack before. So, let's say I have product page which stores page state in a URL, and retrieves it when reloading, then makes request to backend, to "product/getOne". But, this works only for first time when actually gets it from link state. Then, when I reload I'm getting Page Not Found Error, and my URL looks like this. Why current path is matter if my request defined like "product/getOne" in my client? -
Django Rest Framework Image with Bad Request with Axios and Expo
I am trying to upload an image to my Django APÌ through a form in expo, but I keep getting an error 400. it is for a social feed style post with image and text. This is the model: class Post(models.Model): user = models.ForeignKey(User, related_name="post_creator", on_delete=models.CASCADE) text = models.CharField(max_length=900, blank = True, null = True) image = models.ImageField(blank = True, null = True, upload_to = post_directory_path) likes = models.ManyToManyField(User, blank = True) comments = models.ManyToManyField(Comment, blank = True) def __str__(self): return f"{self.user}: {self.text}" The serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" Views.py: (permission_classes is commented for testing purposes) class PostList(generics.ListCreateAPIView): # permission_classes = (IsAuthenticated, ) serializer_class = PostSerializer queryset = Post.objects.all() parser_classes = (MultiPartParser, FormParser) this is my function to the post itself, in Expo: const postData = async () => { try { const formData = new FormData() formData.append('image', image) formData.append('user', 2) // 2 here is just for testing purposes formData.append('text', text) console.log(formData) const resp = await authAxios.post('posts/', formData, { headers: { "Content-Type": "multipart/form-data", }}) console.log(resp.data) setText('') setImage(null) } catch (error) { console.error(error) } } I tried a lot of stuff, but no success, I am using expo-image-picker. Thank you! -
ModuleNotFoundError: No module named 'actstream'
want to setup Mayan-EDMS framework to my laptop I read a lot of document but still I face problem to run this server on my laptop. I need someone who have a good experience and work on this platforms. -
Localhost not connecting with any port on chrome browser
apache is installed .on testing localhost(127.0.0.1) refuse to connect with any port number .Chrome Browser shows connection error. How to open a port number manually for connection with server(apache2 webserver/microsoft iis). firewall is already disabled -
SqlAlchemy AttributeError: 'category' object has no attribute 'subcategories'
I am using python (django) with sqlalchemy. I created these two paintings related to each other. def CreateDynamicSubCategories(): try: category_subcategory = Table('category_subcategory', Base.metadata, Column('category_id', Integer, ForeignKey('category.id')), Column('subcategory_id', Integer, ForeignKey('subcategory.id')), __table_args__ = {'extend_existing': True} ) except Exception as e: GetErrorDetails(e) class Category(Base): __table_args__ = {'extend_existing': True} __tablename__ = 'category' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) subcategories = relationship("Subcategory", secondary=category_subcategory, back_populates="categories") products = relationship("Product", back_populates="category") class Subcategory(Base): __table_args__ = {'extend_existing': True} __tablename__ = 'subcategory' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) categories = relationship("Category", secondary=category_subcategory, back_populates="subcategories") products = relationship("Product", back_populates="subcategory") The problem is that I wanted to add a new table with the following codes: Session = sessionmaker(bind=engine) session = Session() # Adding category new_category = Category(name="Electronics") session.add(new_category) session.commit() new_subcategory = Subcategory(name="Smartphones") session.add(new_subcategory) session.commit() new_category.subcategories.append(new_subcategory) session.commit() new_subcategory.categories.append(new_category) session.commit() I encounter an error like this: new_category.subcategories.append(new_subcategory) AttributeError: 'category' object has no attribute 'subcategories' What is the problem here? Can someone who knows please help? I continued to get the same mistakes even after the chatgpt help. Can someone who knows the problem say? -
Crispy form is not rendring
Trying to render the form but it renders without crispy tags. I have done installed django-crispy-forms (using pip) added 'CRISPY_TEMPLATE_PACK' to my settings added 'crispy_forms' to my applications load the crispy tag to register.html (using {% load crispy_forms_tags %}) forms.py --------- from django import forms class helomodel(forms.Form): name = forms.CharField() email = forms.EmailField() content = forms.CharField() views.py --------- from django.shortcuts import render from . forms import helomodel def register(response): form = helomodel() return render(response,'main/register.html',{'form':form}) settings.py ----------- INSTALLED_APPS = [ 'main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' Register.html -------------- {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} -
What meaning by this self.session?
I know a little about sessions in Django. Do you explain the below line? self.session = request.session common_session = self.session.get(settings.SESSION_ID) What meaning here by self.session this line? -
Django: how to filter by day/month range without setting the year
I have a course Model but want to add a available period date on it, but without concidering the Year. so I can: store 2 dates and wont concidering the years on the Course model or store 4 numbers (from_day, from_month, to_day, to_month) on the Course model First I don't know what is the best solutions (what type of data to store, date or numbers?) Second, I don't know how to filter later with checking the actual date. def get_available_courses(self): from apps.adc.models import Course, MetaEmailTemplate courses = self.account.get_courses().filter( ... ) -
why do I can not output my parsed data in django?
from django.shortcuts import render import requests from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} def index(city): if city.method == 'POST': city = city.replace(" ","+") response = requests.get(f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers) soup = BeautifulSoup(response.text,'html.parser') data={ 'location': soup.select('#wob_loc')[0].getText().strip(), 'time': soup.select('#wob_dts')[0].getText().strip(), 'info': soup.select('#wob_dc')[0].getText().strip(), 'weather': soup.select('#wob_tm')[0].getText().strip(), } return(data['location']) return(data['time']) return(data['info']) return(data['weather']+"°C") else: data ={} return render(city, "main/index.html", data) I search soulutions for this error