Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to send extra data from BasePermission to Queryset in ModelVIewSet DRF
Here is My Seller Model which has User as OneToOneField #models.py . . class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") company = models.CharField(max_length=255) pincode = models.IntegerField() city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.TextField() profileActive = models.BooleanField(default=False) . . Purchase Model #models.py class PurchaseOrder(models.Model): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE) message = models.TextField(blank=True, null=True) expectedDelivery = models.DateField(blank=True, null=True) isCancel = models.BooleanField(default=False)) updated_at = models.DateTimeField(auto_now=True) #Custom permission_classes class SellerCompanyActive(BasePermission): message = 'Only Seller with activated company account is allowed' def has_permission(self, request, view): user = AuthUser.objects.get(id=request.user.id) if user.is_seller: try: company = CompanyProfile.objects.get(user=user) if company.profileActive: return True else: self.message = "Company profile is not active" except CompanyProfile.DoesNotExist: self.message = "Company not found first create company" return False In ModelViewSet #views.py class SellerPurchaseOrder(viewsets.ModelViewSet): queryset = PurchaseOrder.objects.all() serializer_class = PurchaseOrderSerializer authorization_classes = [TokenAuthentication] permission_classes = [IsAuthenticated, SellerCompanyActive] def get_queryset(self): user = self.request.user company = CompanyProfile.objects.get(user=user) return self.queryset.filter(company=company) Now here I always had to use this user = self.request.user company = CompanyProfile.objects.get(user=user) As their are lot of other views also, Is their any other way to send data from my custom permission_classes i.e from SellerCompanyActive to direct SellerPurchaseOrder->get_queryset -
How to modify url in a django get request
I have a web page which displays some data (with get parameters to filter in the view) and I use a pagination. To go through the data i use a link to change the page in the paginator : <li class="paginator-data"><a href="{{ request.get_full_path }}?page={{ page_obj.next_page_number }}">Next</a></li> Here is the problem : url looks like that after browsing a few pages : http://127.0.0.1:8000/?page=2&page=3&page=4&page=5&page=6 The view is working well (It displays me the last page) but I got this ugly link. I tried something like that : request.GET.get = querydict (with querydict a QueryDict object with only one page data) But It didn't work. I also thought of parsing data in the template but maybe there is a better way. -
How to add data in Django?
This is the Memo text where User can submit their Memo form. I need to add(update) new message this record via Update button in DJANGO. by the way I used PK and FK db table. How can I modify it? Tks. Error Message : IntegrityError at /addshowmemo/72/ (1048, "Column 'software_id' cannot be null") Request Method: POST Request URL:/127.0.0.1/addshowmemo/72/ Django Version: 3.1.5 Exception Type: IntegrityError Exception Value: (1048, "Column 'software_id' cannot be null") Exception Location: d:\project\python\it\venv\lib\site-packages\django\db\backends\mysql\base.py, line 78, in execute Python Executable: d:\project\python\it\venv\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\project\python\it', 'c:\Users\tou52\.vscode\extensions\ms-python.python-2022.4.1\pythonFiles\lib\python\debugpy\_vendored\pydevd', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310', 'd:\project\python\it\venv', 'd:\project\python\it\venv\lib\site-packages'] Models: class Memo(models.Model): notes = models.TextField() software = models.ForeignKey(Software, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return self.notes class Software(models.Model): STATUS_CHOICES = [ (0, 'Planning'), (1, 'Development'), (2, 'Using'), (3, 'Obsolete') ] name = models.CharField(max_length=100, verbose_name="SysName") url = models.CharField(max_length=100, verbose_name="SysAdd") status = models.PositiveIntegerField(default=0, choices=STATUS_CHOICES, verbose_name="Status") company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Company") team = models.ForeignKey(Team, on_delete=models.DO_NOTHING, verbose_name="Team") def __str__(self): return self.name Templates: <form method="POST" name="myform" action="." > {% csrf_token %} <table class="table table-striped"> <tr> <td align=right>Memo:</td> <td> <input type=text size=50 name="Cmemo" value='{{Nmemo.notes}}'> </td> </tr> <tr> <td> </td> <td> <input type=submit value="Confirm" class="btn btn-primary">||<a href='/showall/' class="btn btn-warning">Home</a> </td> <td></td> </tr> views: def add_showmemo(request,id=None,logmemo=None): memos = Memo.objects.all() if request.method=="POST": Cmemo … -
Nested quotes in html page
I have a button in my html code to reset password that have nested quotes <button type="" class="btn btn-primary" onclick="window.location.href='{% url 'password_reset' %}'">Forgot Password</button> The button work on site and doesn't seem to have any problem so far. But my VS Code give me the following problem ';' expected. Should I be concerned about this problem? -
showing error while writing heroku login in command line in Django framework in windows
**Made a project in Django framework, but when I tried to deploy on the internet using heroku login,This is the picture of the error. It's showing me this. Though I installed gunicorn and Django-heroku, It still shows me an Error. Please help me with this If anyone knows what is wrong happening behind the hood.I am using python 3.9.12 ** -
How to disable logging messages in Django shell?
I'm using pycharm to run my Django project and I did set some logging settings in my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, }, "formatters": { "verbose": { "format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}", "style": "{", }, }, "handlers": { "console": { "class": "logging.StreamHandler", "stream": "ext://sys.stdout", "formatter": "verbose", }, "mail_admins": { "level": "ERROR", "class": "django.utils.log.AdminEmailHandler", "filters": ["require_debug_false"], }, }, "loggers": { "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, }, "root": { "handlers": ["console"], "level": "DEBUG", }, } The problem is when I'm in the Django shell. In the Django shell when I press the tab button to auto-complete my code imports or calling methods,some logging messages just appear. PS D:\Django Projects\Company-Task\APITask> python .\manage.py shell DEBUG 2022-04-27 12:53:34,021 proactor_events 8988 5720 Using proactor: IocpProactor Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 8.2.0 -- An enhanced Interactive Python. Type '?' for help. DEBUG 2022-04-27 12:53:34,145 proactor_events 8988 5720 Using proactor: IocpProactor In 1: from task_auth.DEBUG 2022-04-27 12:53:49,375 diff 8988 5720 diff parser start DEBUG 2022-04-27 12:53:49,376 diff 8988 5720 line_lengths old: 1; new: 1 DEBUG 2022-04-27 … -
how do I show the real time value of cart without reloading the page
how do I show the real time value of cart when someone adds something to the cart without reloading the page, my function already handles the logic except it needs to reload, I'm trying to replace location.reload() in my javascript function with something that would just show the {{cartItems}} real time value on nav without reloading the page when someone hits the "add-to-cart" button, right now everything has to reload to work. I would really appreciate it if someone can help, thx! views.py def shop(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {"products": products, "cartItems": cartItems} #the nav is able to access home context def home(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } … -
Send messages from Django to Ajax while processing the request
I'm making an AJAX call to a Django POST view. It's reading X files locally, and then sending back to the front-end (thanks to ajax), so the user can download them. Everything is working fine on this part, but i'd like to have some sort of "intermediate response", which would tell Ajax that the server has read one file. That way, i could create a loading bar on the front end while the server is processing the request. Is there any way to do it, using only Ajax and Django ? Here is my code, quite simplified, so you can understand better what I'd like it to do: Django: def downloadFiles_API(request): if request.is_ajax and request.method == "POST": requested_files = json.loads(request.body)['files'] for file in requested_files: # Handle file reading (this part works) # Here i'd like to tell the front end "File X has been loaded..." # Zip-ing all files, and send it as response return FileResponse(myZipFile) AJAX: $.ajax({ url: "/api/downloadFiles/", type: 'POST', contentType: "application/json; charset=utf-8", data: JSON.stringify({ "files" : filesThatTheUserWants, }), xhrFields:{ responseType: 'blob' }, success: function (response){ // Download the file in response (this works) }, // And what i'd like to add (it's NOT in my code): onProgress: … -
How to display value on fields based on queryset?
i have a case like this : Models class Car(models.Model): description = models.CharField(max_length=200) is_available = models.BooleanField(default=False) class Rental(models.Model): car = models.ManyToManyField(Car) My question is, how to display Car on Rental models with is_available = True. On django admin ? Thank you -
OperationalError at /admin/Master/profile/ no such table: Master_profile
When I click on Users in admin site, it is showing errors. I am not getting points here. Please help me out what to do here. Errors: OperationalError at /admin/Master/profile/ no such table: Master_profile Request Method: GET Request URL: http://localhost:8000/admin/Master/profile/ Django Version: 4.0.4 Exception Type: OperationalError Exception Value: no such table: Master_profile Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Python Executable: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['E:\\Project\\S3_project', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Manoj\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Wed, 27 Apr 2022 06:36:44 +0000 models.py: class Profile(User): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') address = models.TextField(max_length=200,null=False) contact_number = models.PositiveIntegerField(null=False) ut=(('Admin','Admin'),('Operator','Operator'),('Ticket generator User','Ticket generator User'),('Inspector','Inspector'),('User 80','User 80'),('Final Inspection','Final Inspection'),('Maintenance','Maintenance'),('Ticket Admin','Ticket Admin'),) user_type = models.CharField(max_length=200, null=False, choices=ut) def __str__(self): return f'{self.user.username} profile' admin.py: admin.site.register(Profile) -
Does psycopg2-binary support pypy?
I wanted to create a django application using the pypy jit compiler, but db engines have a problem i.e. I can't connect to the postgres database -
How to Update this form data in Django?
This is the complain file where User can submit their complain form. I need to update this record via Update button in DJANGO. complain.html file: <form method='POST' enctype="multipart/form-data"> {% csrf_token %} Email: &nbsp; <input type="email" name="email" required/> <br /><br /> What is the complain: &nbsp; <input type="text" name="complain" required/><br /><br /> Who's against the complain (Enter Userame): &nbsp; <input type="text" name="against" required/><br/><br/> Position of the person you are complaining against: &nbsp; <input type="text" name="position" required/><br/> <br/> <div class="mb-3"> <label class="form-label">Evidence</label> <input class="form-control-file" type="file" name="image" required /> </div> </div> <div class="mt-1" style="text-align: center"> <button class="btn btn-danger type="submit"> Submit </button> <button class="btn btn-danger type="submit"> Update </button> </form> I need to update this record via Update button in DJANGO views.py : def complain(request): if request.method=='POST': email = request.POST['email'] complain = request.POST['complain'] against = request.POST['against'] position = request.POST['position'] image = request.FILES.get('image') user = User.objects.filter(username = against) if user.first() is not None: if request.user == user.first(): messages.error(request, 'You are complaining against Yourself :o ') return redirect('complain') pass if User.objects.filter(username = against).exists(): complain = Complain(email = email, complain=complain, against = against, position = position, image=image) complain.save() messages.success(request, 'Complain Submit Successful') return redirect('complain') else: messages.error(request, 'You are complaining against Non-User (-,-)') return redirect('complain') else: return render(request,'complain.html') This … -
Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name
I keep having this error when I try to add a post. It says, "Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name." I know this is not a matter of adding "path('summernote/', include('django_summernote.urls')" because I've already done that. models.py from django.db import models from django.contrib.auth.models import User from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget CATEGORY = ( ("Beginner", "Beginner"), ("Intermediate", "Intermediate"), ("Advanced", "Advanced"), ) class Post(models.Model): title = models.CharField(max_length=300, unique=True) slug = models.SlugField(max_length=300, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_posts') content = models.TextField() # content = models.CharField(widget=SummernoteWidget()) category = models.CharField(max_length=25, choices=CATEGORY, default="Beginner") created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['-created_at'] def __str__(self): return self.title urls.py from . import views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static app_name = 'course_app' urlpatterns = [ path('course/', views.PostList.as_view(), name='course'), path('course/<slug:slug>/', views.PostDetail.as_view(), name='course_posts'), path('summernote/', include('django_summernote.urls')), path('editor/', include('django_summernote.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render from django.views import generic from .models import Post class PostList(generic.ListView): """ Return all posts that are with status 1 (published) and order from the latest one. """ queryset = Post.objects.order_by('-created_at') template_name = 'course.html' class PostDetail(generic.DetailView): model = Post template_name = 'course_post.html' def courses(request): return render(request, 'course.html', … -
How to use swagger_auto_schema in a class based view with no serializer_class and how to add custom authentication permission to it?
I have a class based view as: class ClassBasedView(GenericAPIView): @swagger_auto_schema(responses={201: 'Created'}) @authorize(myCustomPermission) def post(self, *args, **kwargs) -> Response: // code..... return Response(status=HTTPStatus.CREATED) First: The use of swagger_auto_schema without any serializer is throwing error as: AssertionError: DetailView should either include a serializer_class attribute, or override the get_serializer_class() method. And I don't want to use serializer for this endpoint as I don't need that. But the swagger_auto_schema keeps on throwing this error. I want to know whether there is any way to avoid the use of serializer and get the swagger documentation of this endpoint. Second: I want to add my custom authorisation permission of this endpoint in the doc. There is a security field in swagger_auto_schema, but don't know how to make it to use for my custom permission class ie myCustomPermission Thanks. -
Variable inside a function in views is not accessible outside in Django
I have created a function that would get query parameters from the request URL and I need the query parameters that I got inside the function accessible outside so that I can concadenate it with the APIcall URL **views.py** def getformdata(request): if request.method=="GET": baseurl = request.build_absolute_uri() queryparams=urlparse(baseurl).query print("requesturl",baseurl) print("urlparams",queryparams) return JsonResponse({"message":"Request handled","queryparams":queryparams}) print("urlparams",queryparameter) -
django custom abstractuser model authorization
I've user custom model and subModel Teacher and Student I want them to login in the same form: models.py: class User(AbstractUser): course = models.ManyToManyField(Course, related_name='student_course') is_student = models.BooleanField('Студент',default=False) is_teacher = models.BooleanField('Учитель',default=False) image = models.ImageField(verbose_name='Фото',upload_to='uploads/accounts/',blank=True) class Student(User): class Meta: verbose_name = 'Студент' verbose_name_plural = 'Студенты' def __str__(self): return super(Student, self).__str__() class Teacher(User): class Meta: verbose_name = 'Учитель' verbose_name_plural = 'Учителя' views.py: def user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect(home) else: return render(request,'login.html') else: return render(request,'login.html') but not authorization -
How can I paginate this view?
I am trying to convert this function-based view to a class-based view for the purpose of pagination. def tag(request, tag): posts = Post.objects.filter(approved=True, tags__name__in=[tag]).order_by('-date_posted') return render(request, 'blog/tag.html', {'tag': tag, 'posts': posts}) I wrote it like this: class TagView(ListView): model = Post template_name = 'blog/tag.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 3 def get_queryset(self): return Post.objects.filter(approved=True, tags__name__in=[tag]).order_by('-date_posted') But this does not display any posts when I load the page. Can anyone tell me why this is? Or if you know another way of paginating this view without converting it to a class-based view that would also be appreciated. Thank you in advance. -
AWS ElasticBeanstalk how to upload staticfiles with django
I tried uploading staticfiles: aws:elasticbeanstalk:enviroment:proxy:staticfiles: /static: /static got this error in 2022-04-27 03:34:07 ERROR "option_settings" in one of the configuration files failed validation. More details to follow. 2022-04-27 03:34:07 ERROR Invalid option specification (Namespace: 'aws:elasticbeanstalk:enviroment:proxy:staticfiles', OptionName: '/static'): Unknown configuration setting. 2022-04-27 03:34:07 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. I also tried only doing python manage.py collectstatic and it did not work I tried my settings.py in this way: STATIC_URL = '/static/' STATIC_ROOT = 'static' and this way(current way im utilizing): STATIC_URL = '/static/' STATIC_ROOT = 'static' STATICFILES_DIRS = [BASE_DIR / 'templates/static'] -
AttributeError in Django - object has no attribute 'get'
It is the code of my Room model class Room(models.Model): #host #topic name=models.CharField(max_length=200) desccription=models.TextField(null=True, blank=True) #participants= updated=models.DateTimeField(auto_now=True) created=models.DateTimeField(auto_now_add=True) and here in views.py , I'm trying to get id def room(request, pk): room=Room.objects.get(id=pk) context={'room':room} return render(request, 'base/room.html', context) but it shows error AttributeError at /room/1/ 'Room' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/room/1/ Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'Room' object has no attribute 'get' -
Sudden error with Django 'python manage.py runserver' [duplicate]
Recently I started a Django project, created a model, then registered it in admin.py in the same app file. I then got this strange error: (djangoEnv) C:\Users\*****\sample_project>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\*****\djangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\*****\djangoEnv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\*****\djangoEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\*****\djangoEnv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\*****\djangoEnv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\*****\djangoEnv\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Users\*****\djangoEnv\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\roanr\sample_project\projects\admin.py", line 6, in <module> admin.site.register(project) File "C:\Users\*****\djangoEnv\lib\site-packages\django\contrib\admin\sites.py", … -
How to Print celery worker details on windows and mac
I actually had issues printing mine on command prompt because I was using the wrong command but I found a link to a project which I forked Project (If on Mac ) celery -A Project worker --loglevel=info (If on Windows) celery -A Project worker -l info --pool=solo -
Django 3.2 ORM integrated in Tornado server
We're using django 2.2 before and can integrate django orm with our non-async tornado handlers but we're going to upgrade to django 3.2 where you can't run django orm(sync) in a tornado handler(non-async) due to it being async-unsafe unless we use djangos' sync_to_async and make the handler async Question: is there a way where we can still use django 3.2 orm in a tornado server non-async handler? or maybe what's the best way to integrate django orm in tornado handlers? -
Update status and select email recipients with a form - Django
I'm building a Django project where I have a model ('Notice') that has a 'draft' status by default . Its next step is to be "published", which means it is going to be sent by email to several receivers. To define who are going to receive this email, I want to let the user select from a series of checkboxes which people are going to receive this. This should be made from the detail view of the 'draft' Notice. I'm struggling to find the best strategy to build this: should this be a form that saves the selected options in the database in another model (SendNotice)? Should I just save a list of email receivers in the model Notice when updating its status? Maybe I'm complicating myself and there is a simpler approach to do this. Thank you in advance! -
Django Query-set Foreign Key in Pandas Dataframe Getting Duplicate Values
I have models like this. class Product(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) status = models.IntegerField(blank=True, null=True) sellerid = models.ForeignKey( "Seller", models.DO_NOTHING, db_column="sellerId", blank=True, null=True ) # Field name made lowercase. groupid = models.ForeignKey( Group, models.DO_NOTHING, db_column="groupId", blank=True, null=True ) # Field name made lowercase. createdat = models.DateTimeField( db_column="createdAt", blank=True, null=True ) # Field name made lowercase. updatedat = models.DateTimeField( db_column="updatedAt", blank=True, null=True ) # Field name made lowercase. class Meta: managed = False db_table = "product" class Group(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) status = models.IntegerField(blank=True, null=True) image = models.CharField(max_length=255, blank=True, null=True) createdat = models.DateTimeField( db_column="createdAt", blank=True, null=True ) # Field name made lowercase. updatedat = models.DateTimeField( db_column="updatedAt", blank=True, null=True ) # Field name made lowercase. class Meta: managed = False db_table = "group" class SubCategoryGroup(models.Model): id = models.UUIDField(primary_key=True) subcategoryid = models.ForeignKey( SubCategory, models.DO_NOTHING, db_column="subCategoryId", blank=True, null=True ) # Field name made lowercase. groupid = models.ForeignKey( Group, models.DO_NOTHING, db_column="groupId", blank=True, null=True ) # Field name made lowercase. class Meta: managed = False db_table = "sub_category_group" And then from sub category to category. Im querying from Products to get all including which category and subcategory they belong to into a … -
Understanding Django lazy querysets and how they work with function borrowing and Casting columns to integers
I have created a function that I use to apply filters sent from the frontend to query django's database. I include it in the get_queryset method of various ViewSet's. The main issue that arises is when I try to cast one of my model fields to an int to allow me to apply __gt queries to it. The field can contain normal character strings and string representations of integers, but I can easily filter non integer strings based on another field. I thought this would allow me to cast each item in a queryset without reciving an 'is not a valid integer' error when casting the field. But this isn't the case, and I believe the reason has to do with lazy querysets/queryset function borrowing rules. Example Viewset def get_queryset(self): queryset = MyModel.objects.all() # ... # ... other queries # ... filter_model = self.request.query_params.get('filter') if filter_model: queryset = apply_filter(queryset, filter_model) return queryset apply_filter def apply_filter(queryset, filter_model): for _filter in filter_model: # filter models to ensure only instances with valid integer strings are in the queryset field_qs = RelatedChildModel.objects.filter(data_field__name=_filter['name']) # cast integer field field_qs = field_qs.annotate("value_int"=Cast("value", output_field=IntegerField())) # solely to double check that every instance in the queryset has cast an …