Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly kill MySQL/ MariaDB connections in Django using custom connectors
I am currently working on a project and I use the MariaDB connector to run the queries. I can't use ORM so I have to use raw queries. In general, the system works fine, as expected, but when I make a bit 'big' queries I get a Too many connections error message. This has happened to me for both MySQL and MariaDB connectors, but I mainly use MariaDB. Example of my code (truncated / simplified): import mariadb def get_cursor(): conn = mariadb.connect( user="user", password="pass", host="localhost", database="db") return conn, conn.cursor(named_tuple=True) def get_duplicated_variants(): results = [] conn_cursor = get_cursor() cursor = conn_cursor[1] conn = conn_cursor[0] try: cursor.execute("SELECT * FROM `db`.s_data;") columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) cursor.close() conn.close() return results except mariadb.Error as e: print(f"Error: {e}") What I've tried: show status like '%onn%'; And also: show variables like 'max_connections'; So the max_used_connections = 152 and I have 2503 Connections. I also tried to execute the following query: SELECT CONCAT('KILL ', id, ';') FROM INFORMATION_SCHEMA.PROCESSLIST WHERE `User` = 'user' AND `Host` = 'localhost' AND `db` = 'db'; As seen in this question. But the number of connections is the same after running the … -
how to make a message model in Django where you can choose more than one person as the recipient
So, I'm trying to make a messaging model(between users) in Django admin where the sender can choose more than one recipient for the message. Models.py: class Message(models.Model): body = models.TextField(verbose_name=") sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,editable=False) recipient = models.ManyToManyField(settings.AUTH_USER_MODEL) admin.py: class MessageAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs sender_query = qs.filter(sender=request.user) recipient_query = qs.filter(recipient=request.user) return sender_query | recipient_query My current approach is the code above using a ManyToManyField. But this has created two bugs: The sender will see the same message more than once if more than one recipient are chosen, for example if the sender chooses three recipients, he will have three of the same message in his queryset The sender will not be able to open the message he has sent(if more than one recipient are chosen) because this error will get raised:get() returned more than one Message -- it returned 2!. of course the "2" can be any other number The thing I can't figure out Is that these bugs won't produce if the sender is superuser(And I assume that means there is a problem with my get_queryset code) What am I doing wrong in here? P.S: the reason of sender field being … -
Getting logic error while making put request in Django rest framework
my model class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='') I have created a answer field to only superuser editable by using question admin class QuestionAdmin(admin.ModelAdmin): readonly_fields = ['answer'] def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return [] else: return self.readonly_fields admin.site.register(QuestionModel, QuestionAdmin) my views.py def put(self, request, type_of_class=None,pk=None): if int(request.data.get('author')) != self.request.user.id: return Response("you cannot edit othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if pk: question_id = models.QuestionModel.objects.filter(id=pk).first() #if answer originally exists if len(question_id.answer) > 0: self.update(request, type_of_class, pk) #this means answer is just updated if len(question_id.answer) > 0 : return Response("Successfully updated answer", status=status.HTTP_200_OK) # this means that answer is deleted so decrease doubt address count else: if type_of_class =='doubtclass': class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': class_id = question_id.conceptual_class_id class_id.doubtsAddressed -= 1 class_id.save() return Response("Successfully deleted answer", status=status.HTTP_200_OK) #if answer is not originally there self.update(request, type_of_class, pk) #this means that a student has updated his answer if question_id.answer == '': return Response("successfully updated a question", status=status.HTTP_200_OK) #this means that a mentor has posted a answer if type_of_class =='doubtclass': print("type_of_class =='doubtclass'") class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': print("type_of_class =='conceptual_class'") … -
can't create data for testing in async function?
goal Test async function with test database Issu I have async functions for Django channels and when I create data in setUp the data are not reflected in the project!!! my tests: note: these tests inside a APITestCase class class WebsocketTests(APITestCase): def setUp(self): user1 = User.objects.create(username='Alex',email='Alex@g.com') user2 = User.objects.create(username='Sam',email='Sam@g.com') user3 = User.objects.create(username='Clover',email='Clover@g.com') async def test_connect(self): communicator = WebsocketCommunicator(application, 'alerts/') connected, subprotocol = await communicator.connect() assert connected await communicator.disconnect() @database_sync_to_async def get_user(querys): ic(User.objects.count()) #<======= this returns 0 while it should return 3 try: token = parse_qs(querys.decode("utf8"))['token'][0] token_data = UntypedToken(token) user_id = token_data["user_id"] except: return 'token is invalid' try: return User.objects.get(id=user_id) except User.DoesNotExist: return 'AnonymousUser' class QueryAuthMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): scope['user'] = await get_user(scope["query_string"]) return await self.app(scope, receive, send) application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": QueryAuthMiddleware( URLRouter( websocket_urlpatterns ) ), }) #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'OPTIONS': { 'timeout': 20, # in seconds # see also # https://docs.python.org/3.7/library/sqlite3.html#sqlite3.connect }, 'TEST': { 'NAME': os.path.join(BASE_DIR, "db_test.sqlite3"), }, } } I tride replace APITestCase with django TestCase switch to postgres use from asgiref.sync import sync_to_async -
Django - how to handle form using jquery multiple emails
I'm trying to make a form where users can input more than 1 email in the input form. I'm planning to jquery plugin multiple-email, how can I handle this in Django to get the user emails. -
How to create an account/login using google api client in django
I want to implement the same scenario for use in Android Kotlin which is given in this url. For Web Application I have created login with apple for web application by follow this link. Here is my Google Login View in views.py for access token (as one user have explained here ) class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter And It's working for me as I expected. For Android Application Now, Somehow I have managed a code for this google scenario. Here is my Google Client login View.view.py code class GoogleClientView(APIView): def post(self, request): token = {'id_token': request.data.get('id_token')} print(token) try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID) print(idinfo) if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') return Response(idinfo) except ValueError as err: # Invalid token print(err) content = {'message': 'Invalid token'} return Response(content) When I am requesting POST method with IdToken then this is providing below information and ofcourse we need this. { // These six fields are included in all Google ID Tokens. "iss": "https://accounts.google.com", "sub": "110169484474386276334", "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com", "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com", "iat": "1433978353", "exp": "1433981953", // These seven fields are only included when the user has granted the "profile" and // … -
Javascript code is not working but file is linked correctly
First function working correctly when i delete second one but when i rewrite it it doestn't work! Here is the javascript file. window.onload=function(){document.getElementById('loader').style.display='none';}; function toggle(){var blur = document.getElementsByClassName('blur'); blur.classList.toggle('active'); }; Please help me to solve it out. Here is HTML file. {% load static %} <html> <head> <meta name="website" content="Coding Tutorials" /> <meta name="keywords" content= /> <meta name="robots" content="nofollow" /> <meta http-equiv="author" content="Navneet Kaur" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Just Code </title> <link rel="stylesheet" href="{% static '/css/home.css' %}" type="text/css"/> <link rel="stylesheet" href="{% static '/css/googlesearch.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"/> <link href="https://fonts.googleapis.com/css2?family=Limelight&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="{% static 'images/favicon48.png' %}" sizes="48×48" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon96.png' %}" sizes="96×96" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon144.png' %}" sizes="144×144" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon192.png' %}" sizes="192×192" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon288.png' %}" sizes="288×288" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon384.png' %}" sizes="384×384" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon576.png' %}" sizes="576×576" type="image/png"> <style> @font-face { font-family: 'Blanka-Regular'; src: local('Blanka-Regular'), url('{% static 'fonts/Blanka-Regular.otf' %}'); } </style> </head> <body> <div id="loader"> <img src="{% static 'images/preloader.gif' %}" alt="Loading"/> </div> <div class="blur"> <div id="searchoverall"> <div class="dropdown"> <a href="#"class="divasigninbttn dropbttn"><img id="signinbttn"src="{% static 'images/signinbttn.jpg' %}" alt="signin"></img></a> … -
How to modify the id field in django-rest-framework-simplejwt?
I have a custom token serializer: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class TokenObtainPairWithoutPasswordSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].required = False def validate(self, attrs): attrs.update({'password': ''}) return super(TokenObtainPairWithoutPasswordSerializer, self).validate(attrs) This worked but now I'd like to change the id -field of my User to be userId and after that I can't get tokens anymore because it is searching for a field id. There must be some pretty simple way to modify this? -
multiple Modelform, multiple selection and multiple records
My aim is to put all the questions(IsSoru) of the relevant section and the options(IsSecenek) under the questions from the questions table on a page. To save by entering the person information(UserIs) at the bottom after the selected answers. To do it all with a single submit button. models class IsSoru( models.Model ): soru= models.CharField(max_length=145) metin_tr = models.CharField(max_length=250) sira = models.IntegerField() isaltgrup = models.ForeignKey(IsAltGruplari, on_delete=models.CASCADE) class IsSecenek( models.Model ): secenek_tr = models.CharField(max_length=145) sira = models.IntegerField() issoru = models.ForeignKey(IsSoru, on_delete=models.CASCADE) class UserIs( models.Model): eposta = models.EmailField(max_length=145) telefon = models.CharField(max_length=145) adres = models.CharField(max_length=245) sehir = models.CharField(max_length=45) mesaj = models.TextField() tarih = models.DateTimeField(auto_now_add=True) isdurumu = models.CharField(max_length=45, default='Yeni' ) isaltgrup = models.ForeignKey(IsAltGruplari, on_delete=models.CASCADE) kullanici = models.CharField(max_length=150) class Cevap( models.Model ): soru = models.ForeignKey(IsSoru, on_delete=models.CASCADE) cevap = models.ForeignKey(IsSecenek, on_delete=models.CASCADE) useris = models.ForeignKey(UserIs, on_delete=models.CASCADE) forms class UserIsForm(forms.ModelForm): class Meta: model = UserIs fields = ("kullanici", "eposta", "telefon", "adres", "sehir", "mesaj", "isaltgrup") widgets = { 'kullanici': forms.TextInput(attrs={'id': 'name','placeholder': _('Name/Surname'),"required":""}), 'eposta': forms.EmailInput(attrs={'id': 'email','placeholder': _('E-mail'),"required":""}), 'telefon': forms.TextInput(attrs={'id': 'phone','placeholder': _('Phone'),"required":""}), 'adres': forms.TextInput(attrs={'id': 'address','placeholder': _('Address'),"required":""}), 'sehir': forms.Select(attrs={'id': 'privence','placeholder': _('Privence'),"required":""}), 'mesaj': forms.Textarea(attrs={'id':'message', 'placeholder': _('Your Message'),"required":""}), } labels = {'kullanici':'', "eposta":'', "telefon":'', "adres":'', "sehir":'', "mesaj":'', "isaltgrup":''} class UserCevapForm(forms.ModelForm): class Meta: model = Cevap fields = ("cevap", "soru") view class SecDetay_View(CreateView): model = UserIs … -
from .api.serializers import EmployeeSerializer ModuleNotFoundError: No module named 'Auth.api.api
I am getting the following error when I trying to include my app URLs in base URLs Auth.api.views urlpatterns = [ path('', views.employee_list), ] Base.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Auth.urls')), path('api/', include('Auth.api.urls')), path('api-auth/', include('rest_framework.urls')), ] -
How to set custom primary keys of different models as foreign key and migrate to mysql properly in django?
I created this model for my django project and connected it with mysql. I created customerid as the primary key in the Customer model and used it as a foreign key in the cart to represent the owner. There should not be an id field since django does not create one when primary key is true. Whenever I try to migrate the model, it errors "Cannot drop 'id': needed in a foreign key constraint 'api_cart_owner_id_c65befd7_fk_api_customer_id' of table 'api_cart'"). I tried fake migration but that created an unwanted id field in the mysql schema. And if I leave it like that and make a post request with a customerid I get this error "Incorrect integer value: '' for column 'owner_id' at row 1". I suppose that owner_id is looking for id field from customer model instead of customerid. I believe I have not set the cart model correctly. How do I represent the customerid and itemid (custom primary keys of different model) as a foreign key for the cart model and migrate it properly? class Item(models.Model): itemid = models.TextField(primary_key=True) name = models.TextField() price = models.FloatField() quantity = models.IntegerField() ordered = models.IntegerField(default=0) def __str__(self): return self.name class Customer(models.Model): customerid = models.TextField(primary_key=True) name … -
how to make a field in Django only superuser editable and for other users it is read only?
my model class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='') This is a question model where a user is allowed to post new questions but i want that this answer field is only superuser editable and a normal user have only readonly access for that field, needs help i searched for possible answers but didn't get any -
Why is my dockerized Django app so slow and shows ([CRITICAL] WORKER TIMEOUT)?
I'm trying to deploy a Django app in a Docker container. It works well but the first time I open a page I receive these messages: [CRITICAL] WORKER TIMEOUT [INFO] Worker exiting [INFO] Booting worker with pid: 19 The next time I open the same page it's pretty fast. Here's my Dockerfile (generated by wagtail app starter) FROM python:3.8.6-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ nano \ vim \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . . USER wagtail RUN python manage.py collectstatic --noinput --clear CMD set -xe; python manage.py migrate --noinput; gunicorn mysite.wsgi:application How can I fix that? -
How to copy a Django SQlite database to a Docker container?
I'm new to Docker. I am trying to dockerize a Django app. My project contains a Wagtail app and I'm using the auto generated Dockerfile by Wagtail. FROM python:3.8.6-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ nano \ vim \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . . USER wagtail RUN python manage.py collectstatic --noinput --clear CMD set -xe; python manage.py migrate --noinput; gunicorn mysite.wsgi:application It's working well but my sqlite Database is empty and I'd like to run my container with the wagtail pages that I will create locally. How can I change the Dockerfile for that endeavor? -
Can't figure out why I'm getting `Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found` in a django project
The project has 2 apps - accounts (very basic custom users) and portal. myproject/myproject/urls.py: from django.contrib import admin from django import urls from portal import admin as user_admin from portal import views urlpatterns = [ urls.path(r'admin/', admin.site.urls), urls.path(r'portal/mymodel/', views.testview), urls.path('', user_admin.user_site.urls), ] myproject/portal/templates/portal/mymodel/testview.html: {% extends "admin/change_list.html" %} {% block after_field_sets %}{{ block.super }} <h2> hello world </h2> {% endblock %} myproject/portal/templates/portal/views.py: from django.shortcuts import render def testview(request): return render( request, 'portal/mymodel/testview.html', {'app_label': 'portal'} ) and the stacktrace: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or self.get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or … -
Source specified in Javascript not showing up in Django template
Maybe this is a really dumb question, but I'm learning Javascript and Django and can't figure it out. I've spent a few hours on this and maybe it's a syntax error or something else. I want to specify the source of an image in javascript and then display the image in Django HTML template. It's not working, even with simple images Here is my javascript: $(document).ready(function() { var image = document.getElementById("image").src('https://res.cloudinary.com/.../{{ object.id}}'); } Here is my image info: <img src="#" id="image" class="mx-auto" width="250px" onerror='this.onerror = null; this.src="https://res.cloudinary.com/.../image.jpg"'/> What am I doing wrong? It's definitely not working - the image is not showing up even when it exists. I either get the default image or no image. -
When and what data should be cached?
I want to know when should I cache data? Should I cache ListViews? or DetailViews? What kind of data do I need to cache and does the amount of data matter? When to cache? When not to cache? I want to know when should I decide to cache data? P.s: I don't want to know how to cache, what I want to know is when to cache. -
How to check if redis connection is available when server starts running in django rest framework and return the error response if not connected
I'm doing multiple API calls but in each API call I'm checking if redis connection is available. showing only one of the API calls below. def check_redis_conn(): redis_exists = RedisCache.is_redis_available() if redis_exists is True: set_Data = RedisCache.set_data("message", "This is redis Test") return True else: return redis_exists def hello_vortex(request): is_redis_connected = check_redis_conn() if is_redis_connected is True: data = {'Description': 'This is the sample API call', 'version': 1.0} return JsonResponse{data,safe=False} else: return is_redis_connected RedisCache class: @classmethod def set_connect(cls): try: redis_instance = redis.StrictRedis( host='127.0.0.1', port=6379, ) @classmethod def get_conn(cls): try: cls.redis_instance = cls.set_connect() return cls.redis_instance except Exception as e: return JsonResponse{'message':'Error while connecting', safe=False} @classmethod def is_redis_available(cls): try: isConn = cls.get_conn() isConn.ping() return True except Exception as e: return JsonResponse{'message':'Error while connecting', safe=False} How can I check the redis connection only once when the server starts and return the Json Response on the server if the connection is not available. -
Tweet won't embed in django
Here's my html for my Django Twitter project. I am trying to embed tweets in Django <html lang="en"> <h1>Tweets</h1> <form action="" method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> <body> {% if tweets %} <p>{{tweets}}<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p> {% endif %} </body> </html> Here's my views.py: import tweepy from tweepy.auth import OAuthHandler from .models import Tweet from .models import Dates from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.shortcuts import render from django.db import models, transaction from django.db.models import Q import os import tweepy as tw from .forms import TweetIDForm from django import template import requests consumer_key = 'dddddd' consumer_secret = 'cccccc' access_token = 'dddddd' access_token_secret = 'ccccc' def clean_tweet_id(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TweetIDForm(request.POST) print(form) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required tweet_id = form.cleaned_data.get("tweet_id") #act = form.cleaned_data.get("action") auth = tw.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw.API(auth, wait_on_rate_limit=True) twtjson = requests.get('https://publish.twitter.com/oembed?url=' + tweet_id + '&omit_script=true') tweets = twtjson.json() tweet = tweets.get('html') return render(request, 'tweet/tweet-list.html', {'form': form, 'tweet_id':tweet_id, 'tweets': tweet}) My code … -
django html set class as query set items
I have a query set that wants each string/item display in a class name for example : queryset = classes.all() what I tired: <div class="queryset"><h4>student1</h4></div> what I got: <div class="<QuerySet [<classTag: English>, <classTag: Math>, <classTag: CS>]>"><h4>student1</h4></div> what I want: <div class="English Math CS"><h4>student1</h4></div> -
Having solme logical error in my RegisterClass View?
My models.py Here I am have registered_students in as many to many field to Registered Names to store all the students that have registered for the class class RegisteredNames(models.Model): name = models.CharField(max_length=100, unique=True) class LiveClass_details(models.Model): chapter_details = models.TextField(default='') mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) no_of_students_registered = models.IntegerField(default=0) registered_students = models.ManyToManyField(RegisteredNames, null=True, blank=True) no_of_students_attended = models.IntegerField(default=0) This model is for registering a student class RegisteredClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) my views.py @api_view(['GET', 'DELETE']) @permission_classes((IsAuthenticated, )) def RegisterClassId(request, id): print(request.method) if request.method == 'GET': print("in get method") if not models.RegisteredClass.objects.filter(class_details=models.LiveClass_details.objects.get(id=id), user=request.user).exists(): print("in get method") registered_class = models.RegisteredClass.objects.create(class_details=models.LiveClass_details.objects.get(id=id), user=request.user) registered_class.save() registered_live_class = models.LiveClass_details.objects.get(id=id) registered_live_class.no_of_students_registered += 1 registered_live_class.no_of_students_attended += 1 # registered_live_class.save() print(request.user.username) registered_name = models.RegisteredNames(name=request.user.username) print('registered name : ', registered_name) registered_name.save() registered_live_class.registered_students.add(registered_name) registered_live_class.save() else: print("already registered") return Response(status=status.HTTP_201_CREATED) elif request.method == 'DELETE': print("in delete method") registered_class = models.RegisteredClass.objects.get(class_details=models.LiveClass_details.objects.get(id=id), user=request.user) print("registere_class : ", registered_class) registered_class.delete() registered_class.save() registered_live_class = models.LiveClass_details.objects.get(id=id) if(registered_live_class.no_of_students_registered != 0): registered_live_class.no_of_students_registered -= 1 registered_live_class.no_of_students_attended -= 1 registered_live_class.save() print('error here') registered_name = models.RegisteredNames.objects.get(name=request.user.username) print('error after registered name') print(registered_name) registered_name.delete() return Response(status=status.HTTP_204_NO_CONTENT) Here in this view i am getting error in Adding as well as deleting registered_names from my liveclass_api model , In delete request it is returning error like RegisteredNames … -
Display data that no model exists in a serializer - Python - Django - Django Rest Framework
I have a "Model-Viewset-Serializer" and I need my Serializer to display additional fields that don't exist in the model. Model: class MyModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) type = models.CharField(max_length=100, null=False, blank=False) name = models.CharField(max_length=100, null=False, blank=False) Viewset: class MyViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = MyModel.objects.all() serializer_class = MySerializer def list(self, request, *args, **kwargs): queryset = MyModel.objects.filter(organization_id=request.user.my_connection_id) page = self.paginate_queryset(queryset) serializer = MySerializer(page, many=True) return self.get_paginated_response(serializer.data) Serializer: class MySerializer(ModelSerializer): class Meta: model = MyModel fields = ('id', 'type', 'name', 'description', 'array') I need to add the following object to the preview Value: [ {'status': 'ok', 'value': '1'}, {'status': 'pending', 'value': '5'}, {'status': 'approval', 'value': '3'}, {'status': 'rejected', 'value': '4'} ] description: 'text description' -
Python No such Device or Address in Heroku
How to avoid the error when I'm using "os.getlogin" in python django. If I use os.getlogin in my local machine works fine and the file that I downloaded save directly in Desktop but in Heroku app I got the error [Errno 6] No such device or address. Any work around to save the file directly to user Desktop? I'm using Heroku for my app. Thank You! import os def report_detail(request): username = os.getlogin() ....................... some codes ...................... wb.save(f"/Users/{username}/Desktop/Report.xlsx") -
Django question: regarding Foreign Keys on two separate tables
Clear here to view diagram Hello, based on a diagram on left: class Course(models.Model): ... ... ... class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) ... ... class Question(models.Model): question_text = models.CharField(max_length=500) grade = models.IntegerField(default=20) # Foreign KEY TO LESSON lesson_id = models.ForeingKey(Course, on_delete_models.CASCADE) ---> HOW???? How should I assign the 'lesson_id' in Question model to Lesson model when the common for both is Course model? Really need help on this I'm new to Programming. Thanks so much in advance -
Can you help me to fix this bug?
I am testing djangorestframework and there is an error. Can anybody help me? python version: 3.9.1 django version: 2.2.13