Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Why is only the'view' permission authenticated, and the rest of the permissions are not? (DjangoModelPermissions)
First of all, I can't speak English well. test1 account permissions.py (DjangoModelPermissions) class CustomPermissions(permissions.BasePermission): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def _queryset(self, view): assert hasattr(view, 'get_queryset') \ or getattr(view, 'queryset', None) is not None, ( 'Cannot apply {} on a view that does not set ' '`.queryset` or have a `.get_queryset()` method.' ).format(self.__class__.__name__) if hasattr(view, 'get_queryset'): queryset = view.get_queryset() assert queryset is not None, ( '{}.get_queryset() returned None'.format(view.__class__.__name__) ) return queryset return view.queryset def has_permission(self, request, view): if getattr(view, '_ignore_model_permissions', False): return True if not request.user or ( not request.user.is_authenticated and self.authenticated_users_only): return False queryset = self._queryset(view) perms = self.get_required_permissions(request.method, queryset.model) return request.user.has_perms(perms) view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import CustomPermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer … -
How can i convert from IntgerField(Timestamp) to python datetime
unban_date = models.IntegerField() This Output = All the timestamps from the database I need it to convert to DateTime I came up with this but it does not work as it does not take IntegarField intToParser = datetime.datetime.fromtimestamp(unban_date) parserToDate = intToParser.strftime('%Y-%b-%d %H:%M:%S') print(parserToDate) This is dJango Models -
How to implement models for Branch wise permission management in DJango?
I was trying to implement CRM application in Django. The company will have multiple branches, and staff also work for one more branches in different roles. For example, they may work in branch-A as a sales manager and branch -b as a Branch Manager, I was trying to implement that by Django Group and Permission, But that is not efficient way, it will be very help full if somebody help me to do this.Please see my code from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from branch.models import Branch from django.contrib.auth.models import Group from django.contrib.auth.models import Permission class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) … -
How to pass multiple instances to Django forms
I have a user profile which contains data about the user's education details as a table.The user need to edit his educational details by using a form.I need to edit the multiple education objects from the db. How can i do this ? I'm a beginner in django. Please help views.py// @method_decorator(login_required, name='dispatch') class EditTutorEducation(TemplateView): template_name = 'account/edit-education.html' def get_context_data(self, **kwargs): context = super(EditTutorEducation, self).get_context_data(**kwargs) education_object = Education.objects.filter(user = self.request.user) context['form'] = EducationEditForm(instance=education_object) ---// need help here return context def post(self, request, *args, **kwargs): education_object = Education.objects.filter(user = self.request.user) form = EducationEditForm(request.POST, instance=education_object) if form.is_valid(): form.save() else: print(form.errors) if form.errors: return TemplateResponse(request, self.template_name, {'form': form}) return redirect('/profile/') edit-education.html// <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <table class=""> {{form}} </table> <div class="profile-btn mt-5 row justify-content-center"> <button class="btn btn-block btn-outline-primary white-hover my-3 my-sm-0" type="submit">Submit</button> </div> </form> forms.py// class EducationEditForm(forms.ModelForm): class Meta: model = Education fields = ['course','university','year'] -
Django 'Unable to configure handler 'logfile' error
I faced some errors while running the Django project. This project is using the default configurations. I checked the setting object but it was normal {'version': 1, 'disable_existing_loggers': false, 'formatters': {'standard': {'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s', 'datefmt': '%Y-%m-%d %I:%M:%S %p US/Central'}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard'}, 'logfile': {'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/django.log', 'maxBytes': 1000000, 'backupCount': 10, 'formatter': 'standard'}}, 'loggers': {'django': {'handlers': ['console', 'logfile'], 'propagate': true}}} Please help me with this issue. Thank you -
how can i return tcp in django to confuse nmap?
nmap scan send with the request 0 headers, so if not request.headers: print("nmap scan me") than django send him http response back and nmap know this is http and start http scan but if i send him back tcp connection he cant say that this is a http scan and he wont scan my website however if i do something like return b"hi i return bytes" i get an error so how can i return tcp response instead of http response -
cannot get image to upload to folder in django
I am making a personal training website and am having trouble getting the profile pic to upload my form looks like this: <form class="form-horizontal" action="updateProfile" method="post" enctype= "multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label col-sm-2" for="gym">Main Gym</label> <div class="col-sm-10"> <input type="text" class="form-control" id="gym" placeholder="Enter gym name" name="gym" id="gym"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="last name">Qualifications</label> <div class="col-sm-10"> <textarea name="qualifications" rows="10" cols="130" name="qualifications" id="qualifications"></textarea> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="last name">About Me</label> <div class="col-sm-10"> <textarea name="aboutme" rows="10" cols="130" id="aboutme"></textarea> </div> <div class="form-group"> <label class="control-label col-sm-2" for="servicedetails">Service Details</label> <div class="col-sm-10"> <textarea name="servicedetails" rows="10" cols="130" id="servicedetails"></textarea> </div> <div class="form-group"> <label for="avatar">Choose a profile picture:</label> <div class="form-group"> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> </div> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> models.py: class trainerabout(models.Model): userID = models.IntegerField() gym = models.TextField(max_length=30) qualifications = models.TextField() aboutme = models.TextField() servicedetails = models.TextField() profilepic = models.ImageField(upload_to='images/') added this to urls.py urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: def updateProfile(request): if request.method == 'POST': gym = request.POST['gym'] qualifications = request.POST['qualifications'] aboutme = request.POST['aboutme'] servicedetails = request.POST['servicedetails'] avatar = request.POST['avatar'] trainer = trainerabout(gym=gym, qualifications=qualifications, aboutme=aboutme, servicedetails=servicedetails, profilepic=avatar, userID=request.user.id) trainer.save() return render(request, 'updateProfile.html') added this to settings.py MEDIA_URL = '/media/' MEDIA_ROOT = … -
Unable to run python file
I have been trying to run a python script, but I keep on getting the following error. Error: Traceback (most recent call last): File "cloud_copasi/background_daemon/cloud_copasi_daemon.py", line 18, in <module> django.setup() File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'web_interface' The script file which I am trying to run (cloud_copasi_daemon) is: import sys, time import django django.setup() from tools.daemon import Daemon import tools.background_script from tools.response import RemoteLoggingResponse from cloud_copasi import settings import logging log=logging.getLogger(__name__) class MyDaemon(Daemon): #Set the level we wish to log at. Logs are sent back to the central server #Choices are all, debug, info, error, none def __init__(self, *args, **kwargs): return super(MyDaemon, self).__init__(*args, **kwargs) def stop(self, *args, **kwargs): return super(MyDaemon, self).stop(*args, **kwargs) def run(self): log.debug('Daemon running') while True: min_repeat_time = settings.DAEMON_POLL_TYME #Seconds start_time = time.time() try: tools.background_script.run() log.debug('Background script finished') except Exception as e: log.exception(e) finish_time = time.time() difference = finish_time - start_time if difference < … -
Recieving plain Js code File in the axios GET Response in react while trying tp get data Using DRF
I have this problem while i was making Get request from my React Frontend to Drf Backend, It was suppose to get the User Details and set it to State when i dispatch using Redux, But the Reponse from backend is a Pure Js code File or index.html file that we suppose to have in build folder while running React With Django . export const load_user = () => async dispatch => { if (localStorage.getItem('access')) { console.log('True') const config = { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${localStorage.getItem('access')}`, } }; try { const res = await axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config); const user_type = res.data.type_of_user.toLowerCase() const id = res.data.id const res1 = await axios.get(`${process.env.REACT_APP_API_URL}/app/${user_type}/${id}`, config) console.log(res1.data) dispatch({ type: USER_LOADED_SUCCESS, payload: res1.data }); } catch (err) { dispatch({ type: USER_LOADED_FAIL }); } } else { dispatch({ type: USER_LOADED_FAIL }); } }; Here is the URLs.py Template view setup for Django to load build file's index.html from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from app.views import index urlpatterns=[ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('app/', include('app.urls')), path("", index ) ] urlpatterns+=[re_path("", TemplateView.as_view(template_name='index.html'))] here is app's urls.py from django.urls import path from .views import PatientView, DoctorView, VitalView, UserView, send_mail_to_doctor, … -
How can I Fix this SQL Syntax error 1064, Where It says to look at the MySQL server version for the right syntax to use?
ERROR : django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':'STRICT_TRANS_TABLES'' at line 1") Code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'REDACTED', 'USER': 'REDACTED', 'PASSWORD': 'REDACTED', 'HOST': 'REDACTED', 'PORT': 'REDACTED', 'OPTIONS': { 'init_command': "SET sql_mode:'STRICT_TRANS_TABLES'" } } } MySQL Version = mysqlclient : 1.4.6 Server version: 5.7.31 - Gentoo Linux mysql-5.7.31 Protocol version: 10 Help is very appreciated -
Can't connect Django and PostgreSQL (EC2)
I have two servers "App Server" with IP y.y.y.y in which I have a Django Project that I'm trying to connect with another server called "Data Server" with private IP x.x.x.x, I'm getting this error every time I want to make migration: FATAL: no pg_hba.conf entry for host "y.y.y.y", user "usuario1", database "redesproyecto1", SSL off This is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'redesproyecto1', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'x.x.x.x', 'PORT': '5432', } } And this is my pg_hba.conf: # Database administrative login by Unix domain socket local all postgres ident # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all md5 # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege.l host all all y.y.y.y trust host all postgres 127.0.0.1/32 md5 host all all ::1/128 md5 Am I missing something? -
"Lost connection to MySQL server during query" with venv
I don’t know why. When I don’t use the virtual environment, everything is normal, and the error "Lost connection to MySQL server during query" appears when I use the virtual environment. Python3.6.9 Django2.2 mysql 5.7 Internal Server Error: /sap/base/v1/token_by_code/get_token/ Traceback (most recent call last): File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/python3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/usr/local/python3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/usr/local/python3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/transaction.py", line 240, in __exit__ connection.commit() File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 262, in commit self._commit() File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/jay/fs_work_django_dev/lib/python3.6/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') -
Creating a modal popup in django_tables2
I am trying to add an edit button that brings up a modal in django_tables2. The first entry in the table behaves correctly but the subsequent entries do no result in a modal popup. When I inspect the buttons, the first shows an event while the rest do not. Any ideas why the behavior isn't repeating. tables.py import django_tables2 as tables from .models import expenseModel from django_tables2 import TemplateColumn class expenseTable(tables.Table): class Meta: model = expenseModel template_name = "django_tables2/bootstrap.html" fields = ('vendor', 'date', 'amount', 'category', 'description') edit = TemplateColumn(template_name = 'edit_button.html') edit_button.html <!DOCTYPE html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> </head> <body> <button id='editBtn'>Edit</button> <div id='myModal' class='modal'> <div class='modal-content'> <span class='close'>&times;</span> <p>Some Text in the modal</p> <form action="/summary/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="submit"> </form> </div> </div> <script> let modal = document.getElementById("myModal"); let btn = document.getElementById("editBtn"); let span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display="block"; } span.onclick = function() { modal.style.display="none"; } window.onclick = function() { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> The first button shows this: Button 1 The second button shows this: Button 2 -
How do I fix overlarge button (or over-small panel header) in django-bootstrap3?
I have been working on a django project recently and am having problems with one of the templates. I am revising a dashboard to use bootstrap3 drop-down panels, but the toggle buttons are larger than the panel headers. I have tried the advice from a few other answers with no luck. This is my first time using bootstrap so I'm running from mostly basic django tutorials and a W3Schools series. I've tried advice from a few other answers and sites but only succeeded in getting myself confused. I did manage to get the panel header to expand, but that left my title right at the top of the header (instead of centered) and me completely confused, so I backtracked to the code I have here. My code looks like this: <div class="panel panel-default"> <div class="panel-heading"> <div class="pull-right"> <button data-toggle="collapse" data-target="#orders" class="btn btn-primary">+</button> </div> <h3 class="panel-title my-auto">Orders</h3> </div> <div class="panel-body collapse" id="orders"> {% for order in orders %} <p>{{order}} <a href="{% url 'view_order' order.id %}">View</a></p> {% empty %} <p>No outstanding orders. Time to get more business!</p> {% endfor %} </div> </div> And here is a screenshot of how it comes out: screenshot -
How to Style The Django Forms?
So, I am making a project, and I need a couple of settings, in the form of BooleanFields. so, class SettingsForm(forms.ModelForm): notifications = forms.BooleanField(label="", required=False) email_notifications = forms.BooleanField(label="", required=False) restricted_mode = forms.BooleanField(label="", required=False) hide_subscriber_count = forms.BooleanField(label="", required=False) private_channel = forms.BooleanField(label="", required=False) playlists_private = forms.BooleanField(label="", required=False) class Meta: model = Settings fields = ['notifications', 'email_notifications', 'restricted_mode', 'hide_subscriber_count', 'private_channel', 'playlists_private'] How to use widget=forms.BooleanField(attrs={"id":"notifications", "class":"notifications"})? How to stick an id to the notifications field or email_notifications field? -
How to keep Django 2.2 migrations on Kubernets while developing?
I have a rather complex K8s environment that one of the Deployments is a Django application. Currently we are having a very hard time whenever I need to update a model that has already been migrated to a PostgreSQL database. Let's say for instance that I create an application named Sample, that has a simple table on the models.py. My development process (skaffold) builds the docker and apply it locally on the minikube, after this is done I connect to the pod via kubectl exec and execute the python manage.py makemigrations and python manage.py migrate, so far so good. After some time, let's say I need to create a new table on the models.py file of the Sample application, the skaffold builds the docker, kills the old pod, and create the new pod. So I connect as usual via kubectl exec and try to execute the makemigrations and migrate command, lo and behold, there's no migration to apply. And of course no change is made on the PostgreSQL. Upon further searching this, I believe that the reason for this is that since the docker is built without the Sample/migrations folder, and there's already a table (the original one) on the … -
Using Python 3.9 and Django 3.1.3 server crashes when re-launched
this is my first question at Stack overflow. I have been learning Python for about a month and Django for two weeks. I tried to run a second server on my MacBook Pro and then had these problems.(the error messages from my terminal below) The second server included some other applications including Pihole. I deleted the second server files and re-booted, problem solved! The next thing was that I tried editing my Views.py file in Django and then the same error message came back when I re-booted my Django server in the virtual environment folder. See errors below: mymac@michaels-MacBook-Pro mfdw_root % python manage.py runserver Traceback (most recent call last): File "/Users/mymac/Desktop/mfdw_project/mfdw_root/manage.py", line 22, in <module> main() File "/Users/mymac/Desktop/mfdw_project/mfdw_root/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked … -
How to Preventing duplicate signals by using dispatch_uid
I am using a signal to send a notification to the Authors when a new activity such as a User clicking a like button to a post. I am having a side effect of using the signal which is when a user creates a new post and a user likes the post, the author receives 2 notifications instead of just 1. I have searched for several answers but they affected other sides of the project so I found on the Django documentation that using a dispatch_uid="my_unique_identifier" will fix these problem. https://docs.djangoproject.com/en/3.1/topics/signals/#preventing-duplicate-signals I have made a trial but it didn't work out. So here it is: Here is the Like model.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, **kwargs): like = instance if like.value=='Like': post = like.post sender = like.user dispatch_uid = "my_unique_identifier" notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() def user_unlike_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification.objects.filter(post=post, sender=sender, user=post.author, notification_type=1) notify.delete() def like_progress(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user dispatch_uid = "my_unique_identifier" if … -
Deleting a Previously sent Notification in a Django Project
I am going to try to be as descriptive as possible to explain my issue. First I have a Like button in my Django Blog Project which is working fine. My issue is I have a Like Model and I have created signal where when a user clicks to like on a post a signal is sent and a notification is created, but I am struggling with the logic that if the same user Unlike the post (clicking the like button for the second time), I want a signal to be sent to delete the created notification So currently here is what is happening: A User clicks the Like button. The value of the Like button is Like Notification sent to the Author of the Post The same user clicks the Like button again. The value of the Like button is Unike Nothing happens What I want is the previously sent notification to be deleted Here is my Models.py related to the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" def get_context_data(self, … -
docker log don't show python print output
I have a Django Proj running in Docker Container My Debug=True but docker up logging doesn't show any print('') output. Is there a way to fix it? thanks! -
Django url dispatch error - AttributeError: 'WSGIRequest' object has no attribute 'data'
I am dispatching based on the path to my methods in the class. The problem arises when I have to pass it to a post method. Else I can wrap it over a Request using the process_request method. How do I pass the correct request to the methods which is not HttpRequest but the DRF 3 Request I suppose. class AddInvoice(APIView): @staticmethod def process_request(request, *args, **kwargs): if isinstance(request, HttpRequest): return Request(request,parsers=[MultiPartParser, FormParser, JSONParser, DjangoMultiPartParser]) return request parser_classes = (MultiPartParser, FormParser, JSONParser, DjangoMultiPartParser, FileUploadParser) def dispatch(self, request, *args, **kwargs): response = None #request = AddInvoice.process_request(request, *args, **kwargs) if request.method == 'PUT': if request.path.rstrip('/') == '/invoice/digitize': response = self.digitize(request,*args, **kwargs) elif request.method == 'GET': if request.path.startswith('/invoice/isdigitized/'): response = self.isdigitized(request, *args, **kwargs) elif request.path.startswith('/invoice/get/'): response = self.get(request, *args, **kwargs) elif request.method == 'POST': if request.path.rstrip('/') == '/invoice': response = self.post(request, *args, **kwargs) if not response: response = Response(status=status.HTTP_406_NOT_ACCEPTABLE) if not getattr(request, 'accepted_renderer', None): neg = self.perform_content_negotiation(request, force=True) request.accepted_renderer, request.accepted_media_type = neg response.accepted_renderer = request.accepted_renderer response.accepted_media_type = request.accepted_media_type response.renderer_context = self.get_renderer_context() return response -
Django - ensure there is only one ACTIVE product per user
Having this model class Product(models.Model): user = models.ForeignKey(...) STATUS_ACTIVE = 'active' STATUS_CANCELLED = 'cancelled' STATUS_DRAFT = 'draft' STATUS_CHOICES = ( (STATUS_ACTIVE,'Active'), ... ) status = models.CharField(..., choices=STATUS_CHOICES) I'm trying to figure out how to make User model having only one product that is ACTIVE. User is allowed to have any number of CANCELLED and DRAFT products, but only one can be ACTIVE. I'm thinking about CheckConstraint but I can't figure out such query. -
How do I get images to show on my django app?
On my Django app, I am trying to make an eBay type of site that lets people post listings with pictures and bid on them. Everything works except posting an image. The image won't show and I do not know if it's the HTML or the python. If you have any questions let me know. Html code: {% extends "auctions/layout.html" %} {% block body %} <div class="container"> <h2>Create listing</h2> </div> <div class="container"> <form action="{% url 'submit' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Title</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Title of the lisiting..." name="title" required> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Description</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="5" placeholder="Description..." name="description" required></textarea> </div> <div class="form-group"> <label for="exampleFormControlSelect1">Category</label> <select class="form-control" id="exampleFormControlSelect1" name="category" required> <option>Fashion</option> <option>Tools</option> <option>Toys</option> <option>Electronics</option> <option>Home accessories</option> <option>Books</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Initial Bid</label> <input type="number" class="form-control" id="exampleFormControlInput1" placeholder="Starting bid..." name="price" required> </div> <div class="form-group"> <label for="exampleFormControlInput1">Image link (optional)</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="https://blah-blah.jpg..." name="link"> </div> <button class="btn btn-outline-info" type="submit">Submit</button> </form> </div> {% endblock %} This is the python function for making listings: def create(request): try: w = Watchlist.objects.filter(user=request.user.username) wcount=len(w) except: wcount=None return render(request,"auctions/create.html",{ "wcount":wcount }) -
Shared configuration across python threads/modules
Something very simple (python!) gone very very bad: I have a Django service app - main thread create a selenium service and keeps its parameters (for all that it matters a string) in a global variable. Another thread that handles a request is required to access this global string with the shared service address (and actually pass it to another thread, but let's leave that for now). There seem to be no sane way to do that. Not without using shared memory or database. I suspect python has better means of sharing data across threads/modules? -
How do I get object in JavaScript/HTML from Django by ID?
I'm doing a small clinic project using Django. In one page of all html pages I would like to create big buttons in which I have data of specific appointment(id, title, doctor, patient, start hour, end hour). It looks like: APPOINTMENT BUTTON There are the fundamental files: models.py class Appointment(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100, default=defaultTitle) description = models.CharField(max_length=480, null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True, default=datetime.date.today) end_date = models.DateTimeField(null=True, blank=True, default=datetime.date.today) doctor = models.ForeignKey(User, on_delete=models.CASCADE) patient = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='+', blank=True) def __str__(self): return self.title views.py def doctortoday(request): today = datetime.date.today().strftime("%d.%m.%Y") today_appointments = None if request.method == 'GET': today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min) today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max) try: today_appointments = Appointment.objects.filter(doctor=request.user, start_date__range=(today_min, today_max)) except: today_appointments = None context = { 'today': today, 'appointments': today_appointments } return render(request, 'doctortoday.html', context) If we click the appointment button then will show popup modal. At the moment there is only QuerySet - {{ appointments }}. POPUP MODAL And the my major problem - how can I display in the popup modal the specific appointment's data without refreshing page? I just want, if we click the button with Appointment 2 then in the popup modal will be data of the Appointment 2. The same …