Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError ,while Django - AWS S3 image file resizing
The Django website have media files on AWS S3, when Admin upload new image, model layer supposed to resize image and save. MODELS.PY class News(models.Model): photo=models.ImageField(upload_to='newsimage') def save(self, *args, **kwargs): img1 = Image.open(self.photo.name) if img1.height > 400 or img1.width > 400: output_size = (845,440) img1.thumbnail(output_size) img1.save(self.photo.name) def __str__(self): return self.title def get_absolute_url(self): return reverse('Newsdetail', kwargs={'slug': self.slug}) The code work fine when media stored in local storage. If the same in S3 , it makes error. However if I dont resize image and save directly , it works fine with AWS S3. -
What's the cleanest way of counting the iteration of a queryset loop?
I need to loop through a queryset and put the objects into a dictionary along with the sequence number, i, in which they appear in the queryset. However a Python for loop doesn't seem to provide a sequence number. Therefore I've had to create my own variable i and increment it with each loop. I've done something similar to this, is this the cleanest solution? ledgers = Ledger.objects.all() i = 0 for ledger in ledgers: print('Ledger no '+str(i)+' is '+ledger.name) i += 1 -
How to achieve database data persistence using factories in pyTest in Django?
I know that when we create a record in the test database inside 1st test case, it is not available from inside 2nd test case. If we use a fixture then the fixture will run before each test case and a new db record will be generated and provided to each test case. I have a factory defined as: import factory from faker import Faker fake = Faker() from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = fake.name() which is used by a fixture, defined as: import pytest from django.contrib.auth.models import User from pytest_factoryboy import register from tests.factories import UserFactory register(UserFactory) @pytest.fixture def user_creation_through_fixture(db, user_factory): user = user_factory.create(username="persist") return user and 2 test cases defined as: import pytest def test1(user_creation_through_fixture): print(user_creation_through_fixture) assert True def test2(user_creation_through_fixture): print(user_creation_through_fixture) assert True how can i apply something like @pytest.fixture(scope="session") to the fixture ? so that at the time of 1st test case when fixture is run a new user record is created in db and then at the time of 2nd test case when fixture is run the same user record is provided to 2nd test case. -
How does a socketio server running separately interact with Djangos Models
I am new to Django and Socketio. I tried to deploy a Socketio server based on message queues using Python-Socketio, Eventlet, and RabbitMQ, but I ran into trouble. I wanted to verify that Django's user token was valid in Socketio and wrote the following code, but Socketio couldn't accept events from the client, as if the Socketio server wasn't listening for any events # shij事件处理函数 import json import os,sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.extend([BASE_DIR,]) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "background_app.settings") # 设置环境变量中的 DJANGO_SETTINGS_MODULE 设置为 django 配置 # 启动 django 配置、注册 app 等等初始化操作 import django django.setup() from django.core.handlers.wsgi import WSGIRequest from server import sio import time, os from rest_framework_simplejwt.authentication import JWTAuthentication '''客户端连接过后执行''' @sio.on('connect') def on_connect(sid, environ): request = WSGIRequest(environ) """ 在客户端连接之后被执行 :param sid:string 客户端设置的用户id :environ :http请求数据 :return: """ token = request.headers.get("token") print(token) user = JWTAuthentication().get_user(token) print(user.username) print('sid={}'.format(sid)) # 向客户端发送事件消息 msg_data = { 'msg': 'hello', 'timestamp': round(time.time() * 1000) } print("已经发送消息") sio.emit('message', msg_data, room=sid) # 多事件名称为message则可以直接调用 sio.send(msg_data, room=sid) # 聊天时使用message事件 传输的聊天格式为json @sio.on("mymessage") def mymessage(sid, data): print(data) print("执行mymessage函数") msg_data = { "message": "信息已收到", "sendtime": time.time() } sio.enter_room(sid=sid, room="we") print(sio.rooms(sid)) sio.emit("mymessage", data=msg_data, room=sid) @sio.on("enter_room") def enter_room(sid, data): data_obj = data print(data_obj) sio.enter_room(sid, room=data_obj["room"]) sio.emit("message", data={"msg": "进入房间成功"}, room=sid) @sio.on("roo_msg") def room_msg(sid, data): room = data["room"] sio.emit(event="roo_msg", data=data, room=room) def call_back(): … -
Deploy Django application to Strato
Hello I have issues with deploying Django APP to STRATO web hosting (strato.de) I have some limitations on the server: no sudo access no package manager From good things: python 3 with pip is installed I have installed all django dependencies, migrated database with mysqlclient (they use MySQL). I have also installed npm via nvm (I am using React frontend). STRATO uses apache web server but installing mod_python throws an error ERROR: Command errored out with exit status 1: command: /bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2p2rabqz/mod-wsgi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2p2rabqz/mod-wsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-c28fym1d cwd: /tmp/pip-install-2p2rabqz/mod-wsgi/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-2p2rabqz/mod-wsgi/setup.py", line 88, in <module> raise RuntimeError('The %r command appears not to be installed or ' RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages. ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. When I run gunicorn for wsgi or daphne for asgi, nothing happens, it just listening but … -
permission didn't take effect with my custom roles (group)
so, I'm trying to make my own custom group that linked to original group with OneToOneField and then linked to my custom user with OneToOneField too. my custom user work perfectly, the problem is that the permission didn't take effect at all even though I make a group with all permissions allowed and linked to my custom group. here's my model my custom group model class Roles(models.Model): id = models.CharField(max_length=255, blank=True, primary_key=True) name = models.CharField(max_length=255, blank=True) label = models.CharField(max_length=255, blank=True) desc = models.TextField(blank=True, null=True) group = models.OneToOneField(Group, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=255, default='system') updated_by = models.CharField(max_length=255, default='system') My custom user model class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True) label = models.CharField(max_length=255, blank=True) roles_id = models.OneToOneField(Roles, on_delete=models.CASCADE, blank=True, null=True) desc = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=255, default='system') updated_by = models.CharField(max_length=255, default='system') Am I already on the right way just need a few correction here and there? or there is a cleaner or better way to make custom group? -
Is it possible to delete last n records of a django model in one/minimum database query?
I'm trying to delete last 10 records of Task table/model in django but I'm unable to do that in one query. Task.objects.filter(type='Active').order_by('-id')[:10].delete() Above code gives me error AttributeError : 'list' object has no attribute 'delete'. If I make a loop and then use .delete() on each object of that list then it will call db n times which I don't want, is there any other way? -
How to connect to Azure SQL Server using Managed Service Identity from Django application in my local laptop
I have a Django application which connects to an Azure SQL Server through traditional username and password combination and it works fine. The library I am using for this is mssql-django. Here is the link to it. https://github.com/microsoft/mssql-django This is the extract from the settings.py DATABASES = { "default": { "ENGINE": "mssql", "NAME": "db_name", "USER": "foo", "PASSWORD": "password", "HOST": "foo.database.windows.net", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } However, I want to connect to the Azure SQL Server using Managed Identities. The library I am using talks about this in this link: https://github.com/microsoft/mssql-django/wiki/Azure-AD-Authentication Towards the bottom of the above link they suggest to use this setting: DATABASES = { "default": { "ENGINE": "mssql", "NAME": "db_name", "HOST": "foo.windows.net", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", "extra_params": "Authentication=ActiveDirectoryMsi", }, }, } But how do I set up the managed identity in my local laptop, so that it can authenticate with Azure? I understand that this would work for an App Service or an Azure VM, but how to set this up for local laptop? -
Django, how to add zoom in/zoom out functionality into preview function in javascript?(js)
i have a js function that previews the image on button click before uploading. I want to add the functionality of zoom in and zoom out to that preview. How can I do that? Following is the code I am using: <tr> <th><label style="display: inline;" for="id_image">Image:</label></th> <td> <input type="file" name="image" accept="image/*" id="id_image" onchange="showPreview(event)" {{form.image}} </td> </tr> And function to preview before uploading: <script> function showPreview(event){ if(event.target.files.length > 0){ var src = URL.createObjectURL(event.target.files[0]); var preview = document.getElementById("file-ip-1-preview"); preview.src = src; preview.style.display = "block"; } } </script> -
I want to change api response json in fastapi | pydantic
I am new in fastapi and please help me! I got an validation error when I change the default API response comes when I use response_model in fastAPI. The default API response is simple json like object from response_model. user.py from fastapi import FastAPI, Response, status, HTTPException, Depends from sqlalchemy.orm.session import Session import models import schemas from database import get_db app = FastAPI() @app.post('/', response_model=schemas.UserOut) def UserCreate(users:schemas.UserBase, db:Session = Depends(get_db)): # print(db.query(models.User).filter(models.User.username == users.username).first().username) if db.query(models.User).filter(models.User.email == users.email).first() != None: if users.email == db.query(models.User).filter(models.User.email == users.email).first().email: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="email already exist") hashed_password = hash(users.password) users.password =hashed_password new_user = models.User(**users.dict()) db.add(new_user) db.commit() db.refresh(new_user) # return new_user #if i uncomment this code then it will give default response which i don't want return {"status":True,"data":new_user, "message":"User Created Successfully"} schemas.py from pydantic import BaseModel, validator, ValidationError from datetime import datetime from typing import Optional, Text from pydantic.networks import EmailStr from pydantic.types import constr, conint class UserBase(BaseModel): name : str email : EmailStr country: str city: str state : str address: str phone: constr(min_length=10, max_length=10) password: str class UserOut(BaseModel): name : str email : EmailStr country: str city: str state : str address: str phone: str class Config: orm_mode = True Now, when I run this … -
I want to select record with tow condation ,this message apparse "'Albums' object has no attribute 'get'",how to solve it?
I try to select record with tow condation ,this message apparse "'Albums' object has no attribute 'get'",how to solve it? def upload(request,id): prod = uploadf(request.POST or None, request.FILES or None) if request.method == 'GET': context = { 'form': prod, } return render(request, 'upload.html', context) else: user=request.user s = user.id All = get_object_or_404(models.Albums, user_id=s, id=id) return All form=uploadf(instance=All) context={'form':'form'} return render(request, 'All_Albums.html', context) -
Getting Error with django - Field 'id' expected a number but got '{}'
I'm coding a book store and on the single product page above the title of the book I have a link that directs the customer to the author profile page. The link is showing fine but when I click on it i get this error: ValueError at /book_details/{} Field 'id' expected a number but got '{}'. Request Method: GET Request URL: http://127.0.0.1:8001/book_details/%7B%7D Django Version: 4.0.1 Exception Type: ValueError Exception Value: Field 'id' expected a number but got '{}'. Exception Location: /Users/ariethan/Documents/django_apps/ibdb/virt/lib/python3.8/site-packages/django/db/models/fields/init.py, line 1824, in get_prep_value Python Executable: /Users/ariethan/Documents/django_apps/ibdb/virt/bin/python Python Version: 3.8.9 Python Path: ['/Users/ariethan/Documents/django_apps/ibdb/ibdb', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python38.zip', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/ariethan/Documents/django_apps/ibdb/virt/lib/python3.8/site-packages'] Server time: Thu, 13 Jan 2022 09:43:37 +0000 /Users/ariethan/Documents/django_apps/ibdb/ibdb/ibdb_app/views.py, line 53, in book_details book_details = Book.objects.get(pk=book_id) view.py models.py from django.db import models class BookAuthor(models.Model): book_authors_first_name = models.CharField('Author First Name', max_length=200) book_authors_last_name = models.CharField('Last Name', max_length=200) book_authors_biography = models.TextField('Biography', max_length=3000,null=True) book_authors_photograph = models.ImageField(null=True,blank=True,upload_to='images/authors') def __str__(self): return self.book_authors_first_name + ' ' + self.book_authors_last_name class BookGenre(models.Model): book_genre_title = models.CharField('Book Genres:', max_length=200) def __str__(self): return self.book_genre_title class Book(models.Model): book_title = models.CharField('Book Title:', max_length=300) book_publication_date = models.DateTimeField('Publication Date:') book_description = models.TextField('Description:', max_length=1000) book_ISBN = models.CharField('ISBN:', max_length=100,null=True) book_genre = models.ManyToManyField(BookGenre, max_length=100) book_amazon_link = models.URLField('Amazon page link',null=True) book_cover_image = models.ImageField(null=True,blank=True,upload_to='images/') book_author = models.ForeignKey(BookAuthor, null=True, related_name='authorwriter', on_delete=models.CASCADE) def __str__(self): return … -
Why do I get NONE when comparing two booleans?
I have a model with a method that compares the test argument with either self.yes_no, self.value or self.tag in the model. The field to be tested is determined by the self.condition in the model. It works beautifully for me until I put a "bool" condition scenario. I returned a print statement to make sure the booleans persist : print(test,self.condition) >> (True, True) However, when comparing them in the "bool" if statement, i get "NONE". can anyone shed light on this? class Referral(models.Model): condition_choices = ( ("greater", "Greater Than"), ("less", "Less Than"), ("bool", "Yes or No"), ("contains", "Contains")) tag = models.ManyToManyField(Keyword, blank=True) condition = models.CharField(max_length=50, choices=condition_choices, blank=True) yes_no = models.BooleanField(null=True, default=True) value = models.PositiveBigIntegerField(null=True, blank=True) def trigger(self, test): print(test,self.condition) match self.condition: case "greater": print("greater") if test>self.value: return True case "less": print("less") if test<self.value: return True case "bool": print(test, self.yes_no) if test == self.yes_no: return True case "contains": print("contains") words = test[0].split() keywords = Keyword.objects.filter(tag__contains = words) print(keywords.values()) if keywords.exists(): return True case _: print("nothing") return False -
getting cannot convert to male error in django?
I am trying to export the list of customers using django. class Gender(models.IntegerChoices): FEMALE = 1, female_label MALE = 2, male_label gender = models.PositiveSmallIntegerField( db_column="Gender", verbose_name=gender_label, choices=Gender.choices, blank=True, null=True, ) and I am calling in the export row like this: customer.gender_label and I am getting such an error Cannot convert 'Male' to Excel do you have any idea why this error is showing up? -
CSS file not found when trying to load with django
My CSS file i'snt being found I try to load it in and ive tried so many different solutions online in order to fix it and cant seem to figure out why and I also have my static and templates both in the same file as the project along with my manage.py file. For my Setting file 'django.contrib.staticfiles' STATIC_URL = '/static/' Inside my base html I have {% load static %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The css file can be modified for every template if required --> {% block style_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> {% endblock %} <title>Website Homepage Design Prototype #1</title> -
How to use wavesurfer.js with django
I would like to know how to create multiple wavesurfer audio tracks with django. I created one audio track with wavesurfer and I would like to know how to integrate it with django to create multiple tracks dinamically. Thanks in advance for any tips or helped provided. Here is the audio player in the HTML file: <div class="container"> <div class="row"> <div class="col-lg-6"> <div class="container-audio"> <img src="static/assets/img/perfil.png" alt="" /> <div class="track-name"> <h2>O nome da música</h2> <p>O nome do álbum</p> <div id="audio1" class="audio-track"></div> <div class="controls"> <img class="icones" id="playBtn" src="static/assets/img/play.png" alt="" /> <img class="icones" id="stopBtn" src="static/assets/img/stop.png" alt="" /> <img class="icones" id="volumeBtn" src="static/assets/img/volume-up.png" alt="" /> </div> </div> </div> <!--col--> </div> <!--row--> </div> <!--container--> Here is the wavesurfer code in javascript: var audioTrack = WaveSurfer.create({ container: '.audio-track', waveColor: '#dde5ec', progressColor: '#03cebf', height: 90, responsive: true, hideScrollbar: true, fillParent: false, minPxPerSec: 1.5, }); audioTrack.load('../static/assets/audio/acontecer.mp3'); const playBtn = document.getElementById('playBtn'); const stopBtn = document.getElementById('stopBtn'); const volumeBtn = document.getElementById('volumeBtn'); playBtn.onclick = function (){ audioTrack.playPause(); if(playBtn.src.includes('play.png')){ playBtn.src = 'static/assets/img/pause.png'; } else { playBtn.src = 'static/assets/img/play.png'; } } stopBtn.onclick = function (){ audioTrack.stop(); playBtn.src = 'static/assets/img/play.png'; } volumeBtn.onclick = function (){ audioTrack.toggleMute(); if(volumeBtn.src.includes('volume-up.png')){ volumeBtn.src = 'static/assets/img/mute.png'; } else { volumeBtn.src = 'static/assets/img/volume-up.png'; } } audioTrack.on('finish', function () { playBtn.src = 'static/assets/img/play.png'; … -
Django testing class of models.py contain error
I am testing the testing the models.py file which contain two class one is Farm and another one is Batch and Batch has a foreign key related to farm while testing the batch I have tested all the other columns but not sure how should I test the foreign key column of batch class models.py file lopoks like import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id … -
Insert data Into Another Table on post_save in model updated field Django
I am using ModelForms to update data. I need to track which user has updated the fields in "MyModel" by saving username, field name, and DateTime of update in the UpdateFieldLog table. I learned that it can be done by signals, but don't know how to do it. Can someone help Model class MyModel(models.Model): a = models.CharField(max_length=20, null=True) b = models.CharField(max_length=25, null=True) c = models.CharField(max_length=10, null=True) d = models.CharField(max_length=20, null=True) e = models.BigIntegerField(null=True) f = models.CharField(max_length=15, null=True) g = models.DateField(null=True) class UpdateFieldLog(models.Model): field_name = models.CharField(max_length=20, null=False) updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) updated_on = models.DateTimeField(auto_now_add=True) @receiver(post_save, sender=MyModel) def post_save_MyModel(sender, instance, **kwargs): if not instance._state.adding: for item in iter(kwargs.get('update_fields')): if item == 'field_name' and instance.field_name == "some_value": print(item) print(instance.field_name) else: print ('this is an insert') -
How do I resolve a Bad Request 400 error using send_mail function?
I'm using a React frontend to send data from a react rendered contact form to a Django backend; which sends the data as an email. However, I keep getting a 400 Bad Request error. I tried to use the send_mail function in a shell, but I get this error: "socket.gaierror: [Errno 11001] getaddrinfo failed" Contact.js const sendEmail = () => { const csrfCookie = Cookies.get('csrftoken'); console.log(formValue); axios.post("contact/", formValue, { headers: { 'X-CSRFTOKEN': csrfCookie, }, }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); }; const handleSubmit = (event) => { event.preventDefault(); sendEmail(); setFormValue({ name: "", email: "", message: "", }); }; urls.py from django.urls import path from django.views.generic import TemplateView from .views import Contact app_name = "core" urlpatterns = [ path("", TemplateView.as_view(template_name="core/home.html"), name="home"), path("contact/", Contact.as_view(), name="contact"), ] views.py class Contact(APIView): def post(self, request): serializer = ContactSerializer(data=request.data) if serializer.is_valid(): form = serializer.data subject = "Website Inquiry" body = { "name": form["name"], "email": form["email"], "message": form["message"], } message = "\n".join(body.values()) try: send_mail( subject, message, settings.EMAIL_HOST_USER, [settings.RECIPIENT_ADDRESS], ) return Response(serializer.data, status=status.HTTP_201_CREATED) except: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) settings.py env = environ.Env() environ.Env.read_env() EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "EMAIL_HOST" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = env("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD") RECIPIENT_ADDRESS = env("RECIPIENT_ADDRESS") -
How to get user id in the serializer for the token authenticated user in DRF
How can I get the user from token in serializer? I am getting the id in views but I need in serializer for applying a filter in queryset of nested queryset. views.py class UserListAPIView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated, jwtPermissions.IsSSOAdminOrReadOnly,) queryset = userModels.User.objects.all() serializer_class = serializers.UserSerializers def get_queryset(self): return self.queryset.filter(id=self.request.user.id) serializers.py class UserSerializers(serializers.ModelSerializer): class Meta: model = userModel.User fields = ('id','email','name','contact_no','address','is_active','solutions') def to_representation(self, instance): rep = super().to_representation(instance) rep['component'] = ComponentUserSerializers(instance.component.all(), many=True).data return rep class ComponentUserSerializers(serializers.ModelSerializer): user_devices = serializers.SerializerMethodField() def get_user_devices(self, obj): #self.context['request'].user.id <-- getting null user_devices_queryset = sensorModel.UserSensorDevice.objects.filter(sensor_type=obj.id, user = self.context['request'].user.id) user_devices_serializer = sensorSerializers.UserSensorDeviceSerializer(user_devices_queryset, many=True) return user_devices_serializer.data class Meta: model = coreModel.Component fields = ('id','comp_code','part_no', 'user_devices') I need to apply a filter in ComponentUserSerializer in get_user_devices API. And I am not getting user_id of the token authenticated user. -
Django - Update one fields value automatically after a value change
I am new to django and I have a simple question. I have two model: Model RegisterLogin and Model OtpEmailVerify. I wanna make 'is_verified' field of Model OtpEmailVerify 'True' as long as 'otp_no' provided matches with the 'otp' field of model LoginRegister. models.py class RegisterLogin(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now_add=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) phone_regex = RegexValidator(regex=r'\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999-999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=False, unique=True) sign_up_for_newspaper = models.BooleanField(default=False) allow_remote_shopping_assistance = models.BooleanField(default=False) otp = models.CharField(null=False, unique=False, max_length=5) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'phone_number'] def __str__(self): return self.email def save(self, *args, **kwargs): otp_choice = '1234567890' for i in range(5): self.otp += str(random.choice(otp_choice)) super(RegisterLogin, self).save() class OtpEmailVerify(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) otp_no = models.IntegerField(default=0, help_text='Please enter the Otp that has been sent for ' 'verification ') user = models.OneToOneField(RegisterLogin, null=False, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False, help_text='if it is true, that means can now validate otp for verification') def __str__(self): return self.otp_no def save(self, *args, **kwargs): if self.otp_no == self.user.otp: return not self.is_verified else: return ValidationError('Wrong Otp Provided.') views.py class OtpVerifyView(generics.CreateAPIView): queryset = OtpEmailVerify.objects.all() serializer_class = … -
Unable to install Misaka
I tried installing wheels and again ran pip install misaka but I'm ending up with the same error. Misaka installation error! -
How to access the dictionary keys and values in django templates
I have created a dictionary of message senders which is updating dynamically. If I print the dictionary keys in the python console window, I am getting the expected output but when I try to access the values in the Django template, I am getting nothing here is my python code; views.py def home(request): senders = {} chatting =Message.objects.filter(seen=False) for msg in chatting: user = User.objects.get(id=msg.sender.id) if user != request.user and user not in senders.values(): senders.update({user.id : user}) return render(request, 'home.html', senders) template Home.html <div> {% for key, val in senders %} <div> <a href="#">{{val}}</a> </div> {% endfor %} </div> -
Auto generate classes in python
I want to create a new subclass of a base class after creating an object in my django admin project. Auto creation of class that I want is something like django migration when createmigration is execute. How can I do it? -
How to pass serializer.data into create function in views django
views.py def productslist(request): products = Products.objects.all() context = {'products':products} return render(request,'productslist.html',context) def productsform(request): return render(request,'productscreate.html') @api_view(['GET','POST']) def products_list(request): if request.method == 'GET': product = Products.objects.all() serializer = Productserialize(product,many=True) return Response(serializer.data) elif request.method == 'POST': serializer = Productserialize(data=request.data) if serializer.is_valid(): def create(serializer): return Products.objects.create(serializer) return Response(serializer.data) return Response(serializer.errors) @api_view(['GET','PUT']) def products_detail(request, pk): products = Products.objects.get(pk=pk) if request.method == 'GET': serializer = Productserialize(products) return Response(serializer.data) elif request.method == 'PUT': serializer = Productserialize(products, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) In views.py I have done create function but it is not working not saving data I want to save serializer data using create function I want to pass serializer.data into create function in post method api Please help me to solve this Thanks in advance serializer.py from rest_framework import serializers from .models import Products class Productserialize(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) description = serializers.CharField(required=False, allow_blank=True, max_length=100) image = serializers.FileField() def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Products.objects.create(**validated_data)