Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
XML error while visiting the localhost:8000/sitemaps.xml | Django
When I visit the localhost:8000/sitemap.xml It shows This XML file does not appear to have any style information associated with it. The document tree is shown below. The tree <urlset> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> Where I expected this tree to be more like this <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> I have followed the django documentation as well as seen other websites. But every time I get the same result. Can you please help. How can I remove the XML error and show my xml like this <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> settings.py INSTALED_APPS = [ # # "django.contrib.sites", "django.contrib.sitemaps", # # ] SITE_ID = 1 sitemaps.py from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from .models import Product # Inherting the Sitemap class of the sitempas module. class ProductSitemap(Sitemap): # These two attributes indicate the change frequency # and the relevencae in the webiste. changefreq = 'weekly' priority = 0.9 def items(self): # This method return the QuerySet of objects # to include in the sitemap products = Product.objects.all() products = products.prefetch_related('seller_product') return products def lastmod(self, obj): # receives each object returned by … -
GIS plugin in Django is throwing openssl error. undefined symbol: EVP_md2
I am trying to use the Geodjango plugin django.contrib.gis for my project. But as soon as I add it to the INSTALLED_APPS I am getting the following traceback. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ec2-user/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/widgets.py", line 3, in <module> from django.contrib.gis.gdal import GDALException File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/gdal/__init__.py", line 28, in <module> from django.contrib.gis.gdal.datasource import DataSource File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/gdal/datasource.py", line 39, in <module> from … -
How to implement Search/Filter and Pagination in FBV
I am trying to implement Search Functionality and Pagination for Django based (model) table.1. At a time only one is working please find the views.py and I am not able to figure out how to manage logically in views.py so that both of them work together. Views.py from .filters import ShiftChangeFilter from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def retrieve_view(request): # if not request.user.email.endswith('@apple.com'): # return redirect('/logout') # post_list = ShiftChange.objects.all() # for pagination allgenesys = ShiftChange.objects.all() paginator = Paginator(allgenesys,10) page_number = request.GET.get('page') try: allgenesys = paginator.page(page_number) except PageNotAnInteger: allgenesys = paginator.page(1) except EmptyPage: allgenesys = paginator.page(paginator.num_pages) # allgenesys = ShiftChange.objects.filter(EmailID=request.user.email) #For filtering using 'django_filters', genesys_list = ShiftChange.objects.all() genesys_filter = ShiftChangeFilter(request.GET, queryset=genesys_list) allgenesys = genesys_filter.qs return render(request, 'apple/shift2.html', {'allgenesys': allgenesys,'genesys_filter':genesys_filter}) pagination.html <style> .pagination { float: left; </style> {% if page.has_other_pages %} <ul class="pagination"> {% if page.has_previous %} <li><a href="?page={{ page.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li><a href="?page={{ page.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif … -
Custom login using Django user model
I'm trying to make my custom login form using Django's user template. What i'm trying to do is the authentication of a user using username and password. Register works, every user is registered correctly, but when i'm trying to login using the correct fields, my: user = authenticate(request, username=username, password=password) returns None as value. Here is my def login_view in views.py (i'm using logger to know what is going on) def login_view(request): import logging logging.basicConfig(filename='mylog.log', level=logging.DEBUG) logging.debug('start') title = 'LOGIN' form = UserLoginForm() if request.user.is_authenticated: return redirect('board.html') if request.method == 'POST': form = UserLoginForm(request=request, data=request.POST) username= request.POST.get('username') password= request.POST.get('password') print(form.errors) if form.is_valid(): logging.debug('form is valid') logging.debug('called form.save(), result=%s', UserLoginForm) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) user = authenticate(request, username=username, password=password) logging.debug('user, result=%s', user) #### if user is not None: login(request, user) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) messages.info(request, "You are now logged in as {username}") return redirect('board.html') else: messages.error(request, "Invalid username or password.") logging.debug('first else') return redirect('/') #### else: print(form.errors) logging.debug('errore form: , result=%s', form.errors) messages.error(request, "Invalid username or password.") logging.debug('second else') username = request.POST.get('username') password = request.POST.get('password') messages.error(request, "Invalid username or password.") logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) return redirect('/') return render(request=request, template_name="login.html", context={"form": form , "title":title}) And that's … -
i want to count the number of correct answers in jS or jquery
I want to count the number of correct answers and display it.i tried many ways but couldn't go through.will appreciate if anybody can help me .Thanks in advance. {% extends 'base.html' %} {% block title%}Quiz{% endblock title %} {% block content %} <div class=" text-danger mt-5 text-center"> <!-- <h2><b id="count">Timer</b></h2> --> <h3>+++Quiz on Indian Politics+++</h3> <hr> </div> <div class="pt-5"> {% for item in obj %} <table> <tr> <h2>Q{{item.id}}. {{item.question}}</h2><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt1" value="{{item.opt1}}">&nbsp;{{item.opt1}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt2" value="{{item.op2}}">&nbsp;{{item.opt2}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt3" value="{{item.opt3}}">&nbsp;{{item.opt3}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt4" value="{{item.opt4}}">&nbsp;{{item.opt4}}</input><br> </tr> <tr> <label id="lb" class="rd" name="{{item.id}}" value="{{item.cor_ans}}" style='display:none;color:green'><b>The correct answer is: {{item.cor_ans}}</b></label> </tr> <tr> </tr> </table> <hr> {% endfor %} <div class="pt-4"> <button type="submit" class="btn btn-success" id="btn">Submit</button> </div> <div class="pt-3"> <b id="counter"></b> <b id="ans"></b> </div> </div> {% endblock content %} {% block scripts %} <script> const rad = document.getElementsByClassName('rd') const input = document.getElementsByTagName('input') const bt = document.getElementById('btn') const label = document.getElementsByTagName('label') const counter = document.getElementById('counter') var score = 0; bt.onclick = function() {} // JQuery code $(document).ready(function() { $('#btn').click(function() { $('.rd').show(); $('.rd').attr("disabled", true); }); }); // # javascript code bt.addEventListener('click', function() { for (i = 0; i < input.length; … -
Docker-compose with Django, MongoDB using Djongo ERROR - pymongo.errors.ServerSelectionTimeoutError
I want to get a django app running using djongo with mongo, and docker. My setup looks like this: docker-compose.yml version: '3.7' services: webserver: build: context: . ports: - "8000:8000" volumes: - ./webserver:/webserver command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 links: - mongo depends_on: - migration mongo: image: mongo:latest restart: unless-stopped volumes: - ./mongo/data/db:/data/db environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: raspicam ports: - "27017:27017" migration: build: . image: app command: sh -c "python manage.py migrate" volumes: - ./webserver:/webserver links: - mongo depends_on: - make_migrations make_migrations: build: . image: app command: sh -c "python manage.py makemigrations" volumes: - ./webserver:/webserver links: - mongo depends_on: - mongo Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" ENV LIBRARY_PATH=/lib:/usr/lib COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers jpeg-dev libjpeg-turbo RUN apk add build-base python3-dev zlib-dev RUN pip install --upgrade pip RUN pip install --no-cache-dir -r /requirements.txt RUN apk add libjpeg RUN apk del .tmp RUN mkdir /webserver COPY ./webserver /webserver WORKDIR /webserver COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] settings.py DATABASES = { "default": … -
Class 'staffdata' has no 'objects' memberpylint(no-member)
from django.shortcuts import render,redirect from staff.forms import StaffdataForm from staff.models import staffdata imported staffdataform and staff data module from staff app. # Create your views here. def home(request): return render(request,'home.html') def stafflists(request): allstaffs=staffdata.objects.all() return render(request,'stafflists.html',{'staff':allstaffs}) created two functions home and stafflist . getting error in second function. please help me -
Retrivieng data from database using objects.all() not working
I am new to django and python and I am trying to retrieve some entries from a a database, but when calling Criminal.objects.all() I don't get anything, hence "Nothing" is displayed. However, I checked and I have 2 entries in my table. models.py from django.db import models # Create your models here. class Criminal(models.Model): cid = models.CharField(max_length=20) cssn = models.IntegerField() cfirst_name = models.CharField(max_length=20) clast_name = models.CharField(max_length=20) cdob = models.DateField() cpob = models.CharField(max_length=15) class Meta: managed = True db_table = "criminal" views.py from django.http import * from django.shortcuts import render from .models import * # Create your views here. def home(request): return render(request, 'home.html', {'name': 'SE mini project'}) def index(request): criminals = Criminal.objects.all() return render(request, 'home.html', {'obj': criminals}) home.html {% extends 'base.html' %} {% block content %} <h1> {{name}} </h1> {% if obj %} {% for v in obj %} {{v.cfirst_name}}<br> {{v.clast_name}}<br> {{v.cdob}}<br> {{v.cpob}}<br> {% endfor %} {% else %} Nothing {% endif %} {% endblock %} -
Send email using Django management command
I want to send emails using Django management commands and o365 (outlook) settings.I have achieved sending normal email via the application earlier but how to do the same from command line. Any ideas on how to achieve this? -
Save an InMemoryUploadedFile to OS in Django
I want to save a temporary uploaded file in the django os. How can I do that ? The file is received as the following: file_obj = request.FILES['document'] I tried the following method but it saves the file in my AWS account but I just want to save it in the os and delete is as soon as I am done with it. file_name = default_storage.save(file_obj.name, file_obj) file_url = default_storage.url(file_name) when I pass the file_url in a function and try to read it I get the following error: OSError: [Errno 22] Invalid argument: 'https://xxxxxxxx.s3.amazonaws.com/media/Sample%20PFEP%20(2).xlsx' I face no problem when I read the same file from local in my jupyter notebook. Why is that ? -
Reactjs- React cannot resolve module in my directory
this is how my react app looks like right now. So I want to import the css file app_style.css into status_bar.jsx How can I do this? When I try importing the file like this import React, { Component } from 'react'; import '.../static/css/app_style.css' I get the following error: Compiling... Failed to compile. ./src/components/general_interface/status_bar.jsx Module not found: Can't resolve '.../static/css/app_style.css' in 'C:\Users\iyapp\OneDrive\Desktop\python projects\PixSirius\PixSirius\react-app\src\components\general_interface' Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp' Why is this happening? How can I fix this? Also, I am using Django for the backend. This is my static_files configuration: # settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'react-app/src/static'), ] Is there any better area/ way to store my static css files and import them into react-js? Please help me, thanks a lot! -
django.template.exceptions.TemplateSyntaxError: Unclosed tag on line 2: 'block'. Looking for one of: endblock. in django
I am making a django app. This is my index.html template: {% extends "blog/base.html" %} {% block content %} {% if latest_post %} <div class="jumbotron p-4 p-md-5 text-white rounded bg-dark"> <div class="col-md-6 px-0"> <h1 class="display-4 font-italic"> {{ latest_post.title }} </h1> <p class="lead my-3"> {{ latest_post.body|truncatewords:30 }} </p> <p class="lead mb-0"> <a href="{% url 'blog:post' post.pk %}" class="text-white font-weight-bold">Continue reading...</a> </p> </div> </div> {% endif %} {% for post in posts %} <div class="row mb-2"> <div class="col-md-6"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative" > <div class="col p-4 d-flex flex-column position-static"> <h3 class="mb-0">{{ post.title }}</h3> <div class="mb-1 text-muted">{{ post.date_posted }}</div> <p class="mb-auto"> {{ post.body|truncatewords:30 }} </p> <a href="{% url 'blog:post' post.pk %}" class="stretched-link">Continue reading</a> {% endfor %} {% endblock %} However, I am getting this error: django.template.exceptions.TemplateSyntaxError: Unclosed tag on line 2: 'block'. Looking for one of: endblock. in django I have made sure: All the blocks are closed There is no whitespaces between the percent signs and the block names I am not missing any percent signs Please help me -
getting error while using model form for model in model_or_iterable: TypeError: 'ModelFormMetaclass' object is not iterable
i was using model form in a django project but while registering model in admin i m getting this error my admin.py from django.contrib import admin from .models import contactForm class contactFormAdmin(admin.ModelAdmin): model = contactForm admin.site.register(contactForm, contactFormAdmin) my model.py from django.db import models from django.forms import ModelForm from django.core.validators import RegexValidator class contactForm(models.Model): name = models.CharField(max_length=255) Phonenumber = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) email = models.EmailField(max_length=254) def __str__(self): return self.name class contactForm(ModelForm): class Meta: model = contactForm fields = '__all__' -
Django importError (cannot import name 'six')
serializer.py: from .models import stock from rest_framework import serializers class StockSerializer(serializers.ModelSerializer): class Meta: model = stock fields = ('id', 'stock_name', 'price', 'stock_gain', 'market_name') views.py: from django.shortcuts import render from rest_framework import viewsets, filters from .seriaizer import StockSerializer from .models import stock from django_filters.rest_framework import DjangoFilterBackend class StockViews(viewsets.ModelViewSet): queryset = stock.objects.all() serializer_class = StockSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) search_fields = ('stock_name',) ordering = ('stock_gain',) urls.py: from django.contrib import admin from django.conf.urls import url from django.urls import path, include from rest_framework import routers from restapp.views import StockViews from restapp import views router = routers.DefaultRouter() router.register('stock', views.StockViews) urlpatterns = [ url(r'', include(router.urls)), path('admin/', admin.site.urls), ] this error comes to me: ImportError: cannot import name 'six' from 'django.utils' (C:\Users\hajar\OneDrive\Desktop\stockm\env\lib\site-packages\django\utils_init_.py) i installes six pip install six but not work???? may any one can help my?! -
Domain name redirects to ip:port after page loads
I am using nginx for reverse proxy. Here is my .conf configuration: listen 80 default_server; server_name xyz.com; return 301 http//:www.xyz.com$request_uri; } server { listen 80; listen [::]:80; access_log /var/log/nginx/reverse-access.log; error_log /var/log/nginx/reverse-error.log; location / { proxy_pass http://xx.xxx.xxx.xxx:8000; } } when I type xyz.com it serves my content but shows the ip and ports. How can I stop my ip and ports to appear on browser and show only domain name even after site is loaded. -
"'str' object is not callable" after I tried to break the circular import (Django)
I have been trying to solve this circular import issue in order to implement unit testing without failure. If I may show you the short version of the previous solution I got: This.... serializer_class = serializers.CompanyMappingSerializer should be changed to This: serializer_class = "serializers.CompanyMappingSerializer" After doing this, the unit tests run fine. However, when I run the api with POSTMAN, it shows this error: TypeError at /api/v1/company/ 'str' object is not callable What should I do in this situation? -
No Icons Shown in the Django admin with DO Spaces
After moving my static files to DigitalOcean Spaces. I can't see Django admin icons. But I can see those image files in the Object Storage. What is the reason for that -
Writing serializer errors to the logger. Django rest
I have a logger that records actions in a view. I successfully record all completed requests, but I cannot figure out how to write validation errors of the serializer, for example, if I entered a date out of format, I want to write to the logger logger.warning('Error Incorrectly entered data {}'.format(Output serializer error here) Where and how should I log my message to the logger? my code views.py logger = logging.getLogger(__name__) class EventView(viewsets.ModelViewSet): queryset = Event.objects.all() lookup_field = 'pk' serializer_class = EventSerializer permission_classes = [ProjectPermission.IsPartner | ProjectPermission.IsAdmin] def perform_create(self, serializer): serializer.save(partnerId=self.request.user.user) @action(detail=True, methods=['get']) def getEvent(self, request, *args, **kwargs): response = self.retrieve(request, *args, **kwargs) logger.debug('Event {} name was get'.format(response.data)) return response @action(detail=True, methods=['put']) def putEvent(self, request, *args, **kwargs): response = self.update(request, *args, **kwargs) logger.debug('Event {} was change'.format(response.data)) return response @action(detail=True, methods=['delete']) def deleteEvent(self, request, *args, **kwargs): response = self.destroy(request, *args, **kwargs) logger.debug('Event {} was delete'.format(response.data)) return response @action(detail=True, methods=['post']) def postEvent(self, request, *args, **kwargs): response = self.create(request, *args, **kwargs) logger.debug('Event {} was delete'.format(response.data)) return response serializers.py class EventSerializer(serializers.ModelSerializer): start_date = serializers.DateTimeField(format='%d-%m-%YT%H:%M:%SZ') end_date = serializers.DateTimeField(format='%d-%m-%YT%H:%M:%SZ') class Meta: model = Event fields = ('id', 'title', 'description', 'start_date', 'end_date', 'cover_page_url', 'address', 'city', 'sportType', 'participantLimit', 'generalInformation', 'enabled', 'partnerId' ) extra_kwargs = {"partnerId": {'read_only': True}} -
Better way to query from multiple tables using django ORM
I have the following models: class Client(BaseModel): #other fields engineers = models.ManyToManyField(Engineer, null = True, blank = True, related_name='clients') class OrganizationMember(MPTTModel): designation = models.CharField(max_length = 100, blank = True) user = models.OneToOneField(User, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.SET_NULL) Now I would like to get all engineers of a client instance and check if each engineer has an organizationmember instance or not. Then if they belong to some organization then I should get_ancestors of that organizationmember and then the users. If they do not have any organizationmember then just get the user of that engineer instance. For this I have written a method in Client model as below: class Client(BaseModel): def get_users_from_engineers(self): users_in_organization = [] users_outside_organization = [] engineers = self.engineers.all() if engineers: for engineer in engineers: user = engineer.user if hasattr(user, "organizationmember"): users_in_organization += [orgmember.user for orgmember in user.organizationmember.get_ancestors(include_self=True)] else: users_outside_organization.append(user) Now this code is working correctly but I am sure that I can use django filters here instead of two for loops and optimize this code. But I do not know how. For eg: OrganizationMember.objects.filter(user__engineer__in=self.engineers.all()) can be used to get all the organizationmembers of the engineers of that particular client instance. But I need the users of … -
I want to update a boolean field in a different model using a foreign key
I have a unit model and a tenant model. ` class Unit(models.Model): property_name = models.ForeignKey('Property', on_delete=models.CASCADE) unit_name = models.CharField(max_length=300) floor = models.IntegerField() unit_type = models.CharField(max_length=300) rent_value = models.IntegerField() occupied = models.BooleanField(default=False) def __str__(self): return '%s' % (self.unit_name) class Tenant(models.Model): property_occupied = models.ForeignKey('Property', blank=True, default=None, on_delete=models.CASCADE) unit_occupied = models.OneToOneField('Unit', unique=True, on_delete=models.CASCADE, related_name='tenant') first_name = models.CharField(max_length=300) last_name = models.CharField(max_length=300) id_number = models.IntegerField(unique=True) phone_number = models.IntegerField(unique=True) date_occupied = models.DateField(auto_now_add=True) def __str__(self): return '%s, %s, %s' % (self.unit_occupied, self.first_name, self.last_name)` I want to update the unit.occupied field to true whenever I add a tenant and false whenever I delete a tenant.I want to do it automatically. I'm using a onetoone field on the tenant model to assign a unit to a tenant because a unit can only have one tenant I am using a tenant_form to add tenants and a unit_form to add a unit. How can I update the specific unit_occupied field for the tenant i'm adding automatically when i add/delete a tenant? This is my views.py: ` def add_tenant(request): form = AddTenantForm if request.method == 'POST': form = AddTenantForm(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, 'Tenant added successfully') # units = Tenant._meta.get_field('unit_occupied').remote_field.model # for unit in units: # ou = unit # if ou.occupied … -
matplot with click event to webserver
I have seen many cases where matplot is imaged and rendered on a website. However, is it possible to show a plot with a click event on the website and make the click event work on the website? python - plot with click event import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set(xlim=[-2, 2], ylim=[-2, 2]) ax.set_aspect('equal', adjustable='box') line, = ax.plot([], [], color='k', linewidth=2) def move_cursor(event): if event.inaxes != ax: return x = event.xdata y = event.ydata line.set_data([0, x], [0, y]) plt.draw() plt.connect('motion_notify_event', move_cursor) -
How to update multiple records of the same model in django at once?
Good day everyone. I have a model called Members, which includes students and courses and their associated data. One of which is the Exam_Score. For Entering the Exam_Score, first the user Should query the database using a form to get the right set of students and then enter the scores. I got the first part but I don't know how to solve the last part which is entering the students scores. This is the form: forms.py class CourseMemberForm(forms.Form): course = forms.CharField(max_length=50) department = forms.CharField(max_length=10) year = forms.IntegerField() semester = forms.IntegerField() This is the view: def ent_exmscr(request): form_fields = ['course', 'department', 'semester', 'year'] form = CourseMembersForm() if request.method == 'POST': form = CourseMembersForm(request.POST) if form.is_valid(): course = form.cleaned_data["course"] dep = form.cleaned_data["department"] smstr = form.cleaned_data["semester"] yr = form.cleaned_data["year"] crs = Course.objects.get(name=course) stdnts = Members.objects.filter(department=dep, semester=smstr, course=crs.id, year=yr) return render(request, 'office/exm_mrk.html', {'stdnts': stdnts}) else: return form return render(request, 'office/exmrk_form.html', {'form': form}) The above view queries the database based on parameters entered by the user and returns a list of students in a new template. So how can I enter the students' scores in the new template? Thanks in advance. This is the model: dep_choices=[ ('MIS','MIS'), ('BBA','BBA') ] course = models.ForeignKey(Course, null=True, on_delete=models.SET_NULL) student … -
How to get a Python/Django app web ready?
I have a python > django project ready to be launched to the web but I'm having trouble configuring it. What do I need to do to the files to get it ready to be launched? Does anyone have a link to a tutorial or such? -
What is the use of False in delete() function in django?
I'm working on code refactoring of django project which was like 4 years old and came across a syntax which confused me. They passed a boolean parameter False to django ORM like object.delete(False). I checked the docs for delete() function in django ORM. But couldn't find False parameter to it. And there is no method overriding in Django Model for delete() method. What is this False parameter for? -
How to get value of model method in Django Rest Framework?
So basically I have a django model that has a ManyToManyField of friends and two methods that run on it. Here are my files: Models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) friends = models.ManyToManyField(User, blank=True, related_name='friends') def friends_list(self): return self.friends.all() def number_of_friends(self): return self.friends.all().count() Serialzers.py: from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' Views.py: from rest_framework import viewsets, permissions from .models import Profile from .serializers import ProfileSerializer class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ProfileSerializer The issue is that in the Api, the return values of the method aren't there. The friends_list method for example is supposed to return a list of friends you have and even though this does work in a traditional django project, the Django Rest Framework is not showing any value for this method. How can I fix this and get the return values for both methods to show up in the api?