Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use SQL VIEWS in Django
Is there any way to use the SQL Command CREATE VIEW in Django? If I Try To use regular syntax, or use from django.db import connection ... with connection.cursor() ... I get an Error. -
How to store http error response in Django
I'm getting name and age and storing in the database through DRF and creating middleware that checks errors and response errors and status_code and when the middleware errors occur like 404 "Page not found, invalid URL" etc. I want to store that 'error and status_code' in the database. so how I can go through it. Model: class Userdata(models.Model): name = models.CharField(max_length=150) age = models.IntegerField() class Errorcode(models.Model): status_code = models.CharField(max_length=150) message = models.CharField(max_length=300) views: class UserdataList(generics.ListCreateAPIView): queryset = Userdata.objects.all() serializer_class = UserdataSerializer class UserdataDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Userdata serializer_class = UserdataSerializer class ErrorcodeList(generics.ListCreateAPIView): queryset = Errorcode.objects.all() serializer_class = ErrorcodeSerializer class ErrorcodeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Errorcode serializer_class = ErrorcodeSerializer Middleware: def get_response(message="", status_code=200): return { "status_code" : status_code, "error" : message, } class ExceptionMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if response.status_code == 500: response = get_response( message="Internal server error, please try again later", status_code=response.status_code ) return JsonResponse(response, status=response['status_code']) if response.status_code == 404 and "Page not found" in str(response.content): response = get_response( message="Page not found, invalid url", status_code=response.status_code ) return JsonResponse(response, status=response['status_code']) return response -
Installing django with python error on widows 10?
I seem to get errors when installing django with the following commands. I follow the instructions form the book i am using exactly but get errors. First installing pipenv gave me errors about path and updating the paths in windows manually fixed that. pip3 install pipenv <---- executes correlty with no errors pipenv install django ~=3.1.0 <----- get the following errors below Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\Scripts\pipenv.exe_main.py", line 7, in File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1128, in call return self.main(*args, **kwargs) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1053, in main rv = self.invoke(ctx) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\cli\command.py", line 194, in install do_install( File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\core.py", line 2046, in do_install pkg_requirement = Requirement.from_line(pkg_line) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 2674, in from_line parsed_line = Line(line) File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 171, in init self.parse() File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 1304, in parse self.parse_name() File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 1027, in … -
Django RadioSelect horizontal
I have multiple choices field and I use Django forms to turn that field into RadioSelect. Problem is, all fields are vertical and I want them to be horizontal. My forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'pripadnost'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['pripadnost'].widget = forms.RadioSelect(choices=self.fields['pripadnost'].widget.choices, attrs={'class': 'form-check-inline', 'id': 'myFIELD'}) So far I tried (other then the one in forms.py): self.fields['pripadnost'].widget.attrs.update({'class': 'inline', 'id': 'myFIELD'}) self.fields['pripadnost'].widget = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple(choices=self.fields['pripadnost'].widget.choices, attrs={'class': 'form-check-inline'})) Tried on .html <script type="text/javascript"> function on_load(){ document.getElementById('div_id_pripadnost').style.display = 'inline-block'; } on_load(); </script> My html from web page: <div id="div_id_pripadnost" class="form-group" style="display: inline-block;"> <label for="myFIELD_0" class=" requiredField">Pripadnost<span class="asteriskField">*</span> </label> <div class=""> <div class="form-check"> <input type="radio" class="form-check-input" checked="checked" name="pripadnost" id="id_pripadnost_1" value="1"> <label for="id_pripadnost_1" class="form-check-label">1</label> </div> <div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_2" value="2"> <label for="id_pripadnost_2" class="form-check-label"> 2</label> </div> <div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_3" value="3"> <label for="id_pripadnost_3" class="form-check-label">3</label> </div> </div> </div> Does not work (because of render/too older for current version, I guess): https://stackoverflow.com/questions/5935546/align-radio-buttons-horizontally-in-django-forms -
How does Django Rest Framework knows the difference between POST or GET methods in class-based views?
so I've been looking at the Django Rest Framework APIView class and I couldn't find in which method or how does the framework knows that I'm using a get or post method. Example:- class GETAPI(APIView): def get(self, request): data = { "name": "hello-world" } return Response(data) In this example, I'm creating a GETAPI class extending it from APIView class ,and I'm creating a method called get. I know that I need to define my method according to the HTTP methods allowed for it to work, but how does DRF calls that methods according to its verb? -
Fetch in Django returns 403 error with different account
I'm trying to create a login functionality on my website using django. The problem that I'm facing is that when I try to login using my main account, it works just fine, it returns code 200. But when I try to use a different account, I get a 403 error. Here is the code where I'm trying to fetch POST request fetch("/login/", { method: "POST", headers: { "X-CSRFToken": getCookie("csrftoken"), 'Content-Type': 'application/json' }, body: JSON.stringify(data), credentials: 'include', redirect: 'follow' }).then(res => { console.log("Request complete! response:", res); //direct user to response url if response is 200 if (res.status == 200) { window.location.replace(res.url); } }); And here is the code for the login def login(request): if request.method == "POST": data = json.loads(request.body) token = data['aud'] try: # Check if the token is valid from client idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) except: return HttpResponse("Unallowed") new_user, created = User.objects.get_or_create( username=str(idinfo['sub']), first_name=idinfo['given_name'], last_name=idinfo['family_name'], email=idinfo['email'] ) if created: new_user.save() return HttpResponseRedirect(reverse('register')) else: request.session['username'] = new_user.username request.session['first_name'] = new_user.first_name return HttpResponseRedirect(reverse('user-dashboard')) elif request.method == "GET": return HttpResponse(render(request, 'login.html')) I've been looking at: 403 Forbidden and request.method showing GET in django and csrf error in django In which both seems to address on CSRF and the URL. But both … -
Django STATIC FILES not loading in actual Production
I have tried many things to solve this like adding whitenoise middleware, also added STATICFILES_DIRS = [], added mimetypes for css in settings.py file CSS/JS Won't load. Here is my settings.py from pathlib import Path import environ import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env() STRIPE_PUB_KEY = env('STRIPE_PUB_KEY') DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'addresses', 'orders', 'feedback', 'message', 'gifts_coupons', 'core', 'product', 'fulfillment', 'cart', 'discounts', 'stripe_pay', 'rest_framework', 'rest_framework.authtoken', 'phonenumber_field', 'django_filters', 'creditcards', 'mptt', 'corsheaders', 'import_export', 'django_inlinecss', ] IMPORT_EXPORT_USE_TRANSACTIONS = True AUTH_USER_MODEL = 'users.User' # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect CORS_ALLOW_ALL_ORIGINS = True # TODO: Change urls while going online CORS_ALLOWED_ORIGINS = [ 'https://estreetmart.in', 'https://estreetmart.sg', 'https://ims.estreetmart.in', 'http://localhost:8000', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'orders.middlewares.cart_middleware', ] ROOT_URLCONF = 'estreetmart.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'estreetmart.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', … -
Django celery executes some task twice
Question 1. Some tasks executed twice task logic settings.CELERYBEAT_SCHEDULE crontab -> create_course_reports -> create_course_report_pdf.apply_async (inside for-loop call multiple tasks) -> email/save pdf problems (celery log below) f6cf7468-bec3-466c-877e-89d9064472b0 task: executed 1 time. no problem 8812805b-65aa-4d28-8f71-490a655a1672 task: executed 2 times. received 1 -> received 2 -> run 1 -> run 2 c1931609-69c1-43c0-934c-97264f9afa82 task: exectued 2 times. received 1 -> run 1 -> received 2 -> run 2 settings.CELERYBEAT_SCHEDULE { ... # create report "create-course-reports": { "task": "hrd.emonitoring.tasks.create_course_reports", "schedule": crontab(hour="7", minute="0"), }, ... } create_course_reports @shared_task(bind=True) def create_course_reports(self): ...... ...... # create report for _, course_id, email_time in filtered_courses: # eta eta = datetime.combine(today_min.date(), email_time, today_min.tzinfo) create_course_report_pdf.apply_async( eta=eta, kwargs={ "course": str(course_id), "mode": "email", "user": celerybeat_worker.id, }, ) # end create_course_report_pdf @shared_task @transaction.atomic def create_course_report_pdf(course, mode="preview", user=None): ..... # 10s ~ 3m job ..... return report_pdf, pdf.report_title worker environment signlebeat django celery beat celery 4.4.7 redis-server 5.0.7 worker singlebeat worker: single-beat celery beat ... celery worker: celery --app=lms.celery:APP worker --loglevel=info --queues=edx.lms.core.default --hostname=edx.lms.core.default.%%h --concurrency=1 -O default celery transport options { 'fanout_patterns': True, 'fanout_prefix': True, 'visibility_timeout': 36000 } singlebeat log 2022-01-27 00:00:00,072 INFO 25624 [celery.beat] [user None] [ip None] beat.py:271 - Scheduler: Sending due task course-rerun-schedules (hrd.emonitoring.tasks.cours e_rerun_schedules) 2022-01-27 04:00:00,091 INFO 25624 [celery.beat] [user None] [ip … -
I could not figure out why the url pattern cannot be matched in Django
urls.py tmp_urlpatterns = [ path('',MsgList.as_view(),name='user_inbox'), path('outbox/',MsgOutbox.as_view(),name='user_outbox'), path('<int:mid>/',MsgRead.as_view(),name='user_msgread'), path('<int:mid>/reply/',MsgReply.as_view(),name='user_msgreply'), path('send/<int:mid>/',MsgSend.as_view(),name='user_msgsend'), ] views.py class MsgReply(LoginRequiredMixin,CreateView): extra_context = {'title':'回覆訊息'} model = Message fields = ['title','body'] def get_initial(self): self.msg = Message.objects.get(id=self.kwargs['mid']) return { 'title':'Re: '+self.message.title, 'body':'{}({}) 於 {} 寫道:\n> {}'.format( self.msg.sender.username, self.msg.sender.first_name, self.msg.created, '\n> '.join(self.msg.body.split('\n')) ), } message_detail.html <a href="{% url 'user_msgreply' message.id %}" class="btn btn-sm btn-secondary"> <i class="fas fa-reply"></i> 回覆 </a> Error: NoReverseMatch at /user/msg/1/ Reverse for 'user_msgreply' with arguments '('',)' not found. 1 pattern(s) tried: ['user/msg/(?P<mid>[0-9]+)/reply/$'] For the url patterns, I had added the route user_msgreply and when I try to click into the hyperlink, the error message appears and I could not figure out where is the problem since in the html template I had put the parameter like {% url 'user_msgreply' message.id %}. So can anyone help me to find out what I am missing? -
Django/python handle TCP IP Connections with 3rd party server
I need a way to set up a permanent tcp/ip connection to an external server. Since I don't have much experience in web development, I would like to inquire how to build this setup. until recently we still had desktop applications where we made the TCP/IP connection directly from the client to the ISP using TCPSockets. That worked perfectly. Now we need the same setup for a web environment, I made a rough sketch of what the setup looks like. It is important that we need a permanent connection to the ISP, where data is exchanged permanently. setup we use the following setup for the web environment: -Django Server: Windows Server with IIS (if more information is needed please let me know) Does anyone already have experience with such a setup and can you please give me a way or a way of thinking. I read something about Django channels and websockets, is it possible to set up this setup with these technologies? Since the ISP is not in our hands, we can only use the setup as specified, so a rest Api or something else is not possible. Thank you for your help in advance. -
Hide InlineModelAdmin with no instances
I have a ModelAdmin with a little high number of inlines. At any time, the parent object (so this is happening in the change view) will only have one inline that has a value. For a better user experience, I would like to filter out the inlines that do not have values. I got stuck as I didn't find a way to retrieve the instance of an inline. def get_inlines(self, request, obj): inlines = super().get_inlines(request, obj) select_inlines = [] for inline in inlines: pass # TODO: How do I know that this inline has an instance # if inline has obj: # select_inlines.append(inline) return select_inlines OR here def get_formsets_with_inlines(self, request, obj=None): for inline in self.get_inline_instances(request, obj): pass # if obj is not None and inline has instance: # yield inline.get_formset(request, obj), inline -
How to insert models with ManyToOne relationship using Rest framework Django
i'm learning Django rest framework and i'm looking to implement the following if it's possible, for example if it is the first time a get a parking ticket i would like to create an account for that plate number along with the Violation and if the account with the plate number exists i want to add the Violation to that account. Result: { "id": 12, "account_number": "0350a6ec6", "pin_number": "54fe8e", "plate_number": "963874", "plate_state": "AL", "created": "2022-01-28T16:07:26Z", "violations": [ { "id": 3, "violation_number": "bd48668bdbf8", "violation_description": "bad place to park", "ticket_location": "ma", "violation_date": "2022-01-28T21:10:25Z", "violation_fine": "966.00", "violation_due": "2022-01-28T21:10:35Z" } my Models.py from datetime import datetime, timedelta from django.db import models from .utils import generate_account_number, generate_account_pin, generate_violation_number class Account(models.Model): account_number = models.CharField(max_length=9, unique=True, blank=True, null=True, editable=False) pin_number = models.CharField(max_length=6, blank=True, null=True, editable=False) plate_number = models.CharField(max_length=8, blank=False, null=False) plate_state = models.CharField(max_length=2,blank=False, null=False) created = models.DateTimeField(default=datetime.now()) class Meta: ordering = ('-created',) def __str__(self): return self.account_number def get_absolute_url(self): return f'/{self.account_number}/' def save(self, *args, **kwargs): self.account_number = generate_account_number() self.pin_number = generate_account_pin() super(Account, self).save(*args, **kwargs) class Violation(models.Model): violation_number = models.CharField(max_length=12, unique=True,blank=True, null=True, editable=False) violation_description = models.CharField(max_length=250) ticket_location = models.CharField(max_length=250) violation_date = models.DateTimeField(default=datetime.now()) violation_fine = models.DecimalField(max_digits=6, decimal_places=2) violation_due = models.DateTimeField(default=datetime.now()) account = models.ForeignKey(Account, related_name='violations', on_delete=models.CASCADE) class Meta: ordering = ('-violation_date',) … -
How to update CELERY_BEAT_SCHEDULE time values in docker container?
The site is deployed on Django. Docker is used. I decided to change the time for tasks, but unfortunately their execution itself does not work according to the new time. Only the old time works. I decided to install a nano editor in the container, looked at what was in the settings, and everything was as it should be, ran the docker-compose up --build command, which did not help either. Celery-Beat launched, Celery too. Redis works. I also deleted the celerybeat-schedule. Most importantly, I see that it changes at given new intervals of time settings.py CELERY_BEAT_SCHEDULE = { "controller": { "task": "modules.parser.tasks.parser_driver_task", "schedule": crontab(minute=5), }, "updater": { "task": "modules.parser.tasks.updater_driver_task", "schedule": crontab(minute=10), }, "clean_hits": { "task": "modules.core.tasks.clean_hits", "schedule": crontab(minute=0, hour=0), }, "clean_loads": { "task": "modules.core.tasks.clean_loads", "schedule": crontab(minute=1, hour=0, day_of_month='1'), }, "clean_sessions": { "task": "modules.core.tasks.clean_sessions", "schedule": crontab(minute=2, hour=0, day_of_month='1'), }, "db_backup": { "task": "modules.core.tasks.db_backup", "schedule": crontab(minute=5, hour=0), }, } -
get db utilization of a mysql query
Is there any way/command to get DB utilization of a query i.e.., how much memory of DB it used, how much time it took to execute.. and all. so, that I can plan and further optimize the query I tried to google it but I can only find ways to get CPU utilization (application level memory usage) but didn't find anything related to DB utilization I'm using Mysql DB and Django -
How can I set JWT at the Frontend with bootstrap html not with react whilst the API is created with Django?
Recently I am studying and building API with Django. I successfully set up the API of authentication system with Django API. I am curious to know that is there any solution to add this JWT with frontend whilst the frontend only with bootstrap designed login form. I don't want to use react or anything like that. Only through Django views is it possible to do? It will be really helpful if there is any way to do. Or if it's required only js I will love to accept but I just want to call the templates login.html file not want to add any react or nodejs. I searched online but everywhere either react or nodejs. Here I am adding the features I am using of JWT in my code #settings.py from datetime import timedelta # for JWT REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', # 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=360), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', # 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': … -
Django annotate with Subquery, OuterRef and group by parent in table
I want to get summary data from Items to categories(Ctg) Has 3 inherit`s models: class Ctg(models.Model): tt = models.Charfield() parent = models.ForeignKey('self') # inherit categories sort = models.IntegerField() class Common(models.Model): ctg = models.ForeignKey(Ctg) # independent of ctg in Items recd = models.DateField() class Items(models.Model): common = models.ForeignKey(Common) ctg = models.ForeignKey(Ctg) coin = models.DecimalField() Filter data by month/years/ctg then summary 'coin's. items_recd = Items.objects.filter(common__recd__year=2022, common__recd__month=1) items_qs = items_recd.filter(ctg=OuterRef('pk')).values('ctg').annotate(total=Sum('coin')).values('total') items_qs_parent = items_recd.filter(ctg__parent=OuterRef('pk')).values('ctg__parent').annotate(tota=Sum('coin')).values('total') Create subqueries with condition, if has parent in Ctg this row will be summary childrens. I`ll got here items_qs_parent, but items_qs is None total = Subquery(items_qs.values('total')) if F('parent') is None else Subquery(items_qs_parent.values('total')) Data of table objs = Ctg.objects.order_by('sort').annotate(total=total, tax=F('total') * 0.2).values('tt', 'total', 'parent', 'tax) -
django orm how to optimize query?
class Category(MPTTModel): name = models.CharField(max_length=500, verbose_name="Название категории") external_id = models.CharField(max_length=9, default='', verbose_name="Внешний ключ") parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Course(models.Model): name = models.CharField(max_length=500, verbose_name="Название курса") category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, blank=True, related_name="get_courses") category_list = Category.objects.filter(external_id='00000001').get_descendants(include_self=True) list_category_course = [] for category in category_list: courses = [course.name for course in category.get_courses.all()] list_category_course.append({'category': category, 'courses': courses}) how to optimize query? -
TroubleShooting: Related Field got invalid lookup - icountain
class Job_type(models.model): created_by = UserForeignKey(auto_user_add=True, verbose_name="The user that is automatically assigned", related_name="Job_type_created_by") and in admin.py @admin.register(Job_type) class Job_type_Admin(admin.ModelAdmin): list_display = ('id','job_type','is_deleted','is_active','created_by', 'created_on','last_modified_by','last_modified_on') list_display_links = ['id','job_type','created_by'] list_filter = ('job_type','created_by') search_fields= ('id','job_type','created_by','created_on', 'last_modified_by','last_modified_on') list_per_page = 20 please help me ,i want created by in search field but it is throwing error as Related Field got invalid lookup - icountain -
DRF-How to update single field in create method of model serializer
I want to create all the field except image field.then, I want to update image from that field. How to do this in create method??? serializers.py def create(self, validated_data): loc_id = validated_data.pop("location")["id"] currency_id = validated_data.pop("base_currency")["id"] try: loc_obj = get_object_or_404(Location, id=loc_id) validated_data["location"] = loc_obj currency_object = get_object_or_404(Currency, id=currency_id) validated_data["base_currency"] = currency_object image_data = validated_data.pop('logo_filename') organization = Organization.objects.create(**validated_data) return organization except Exception as e: raise serializers.ValidationError(e) its my create method how can i update logo_filename field??? -
Login URL redirecting issue
When I log into my web application, it doesn't redirect to the custom redirect page created instead it redirects to the default accounts/profile url in Django. Below are my codes : Views.py def student_dashboard(request): if request.user.is_authenticated and request.user.is_student: render(request,'student/s_dashboard.html') elif request.user.is_authenticated and request.user.is_client: return redirect('client_dashboard') elif request.user.is_authenticated and request.user.is_supervisor: return redirect('supervisor_dashboard') else: return redirect('signin') def supervisor_dashboard(request): if request.user.is_authenticated and request.user.is_student: return render(request,'student/s_dashboard.html') elif request.user.is_authenticated and request.user.is_client: return redirect('client_dashboard') elif request.user.is_authenticated and request.user.is_supervisor: return redirect('supervisor_dashboard') else: return redirect('signin') def client_dashboard(request): if request.user.is_authenticated and request.user.is_student: return render(request,'student/s_dashboard.html') elif request.user.is_authenticated and request.user.is_client: return redirect('client_dashboard') elif request.user.is_authenticated and request.user.is_supervisor: return redirect('supervisor_dashboard') else: return redirect('signin') def signin(request): if request.user.is_authenticated: if request.user.is_student: return redirect('student_dashboard') if request.user.is_cleint: return redirect('client_dashboard') if request.user.is_supervisor: return redirect('supervisor_dashboard') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username =username, password = password) print(user) if user is not None: login(request,user) if user.is_authenticated and user.is_student: return redirect('student_dashboard') #Go to student home elif user.is_authenticated and user.is_client: return redirect('client_dashboard') #Go to teacher home elif user.is_authenticated and user.is_supervisor: return redirect('supervisor_dashboard') else: form = AuthenticationForm() return render(request,'registration/login.html',{'form':form}) else: form = AuthenticationForm() return render(request, 'registration/login.html', {'form':form}) urls.py from django.contrib import admin from django.urls import path, include from CPRS_admin.views import * from CPRS_admin.HOD_views import * urlpatterns … -
Django and uploading Media files to AWS S3 for users in app to view
this might be a vague question but I am developing an app where users can upload files (mainly videos and pictures). Users can create groups and upload their images to the group and anyone in the group can view these files. I have the AWS S3 configured and working however, Aws recommends to keep the bucket Private. if the bucket is private, is the only way to allow access for users to view content (maybe uploaded by friends VIA pre-signed urls?) is it necessary to even make the bucket private. I see tutorials and they usually have the bucket settings to public. this means that any person that has a hold of the url can access an image. Lets say user 1 uploads to group xyz. only members of xyz should be able to access that image. implementing unique identifiers for images will make it tough for someone to get access to that image but not impossible. would this be the better approach or having django generate signed URLS everytime a user wants to view a certain image? I feel like this is overkill for a photosharing app. are there any other ways to add security? -
'Geometry SRID (0) does not match column SRID (4326)' error when adding a point in a Django web-app
I have this Django webapp that allows adding a point via Django's OSMGeoAdmin. The database is Postgresql with Postgis installed. When I add a point and save it, it results to this error mysite/app/models.py from django.contrib.gis.db import models class shop(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=50, default='') location = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) mysite/mysite/settings.py INSTALLED_APPS = [ 'website', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'app', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'djangodb', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } C:\Users\imper\miniconda3\envs\django\Lib\site-packages\django\db\backends\utils.py _execute() method def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) The app's table in my djangodb Postgis database -
What will be the problems with Django app for image processing when deploying?
I am new bee to Django. Never deployed any projects to server. Always worked in localhost. I made Django app, with simple functionalities like: User can add images (CRUD) User can download all the uploaded images with a frame(PNG Frame are already stored, basically I am just masking(merging 2 images) it on user's image will pillow library) I saw many videos on how to deploy your project on server and I already bought domain and VPS(basic one which has 1CPU core, 1GB ram and 20GB SSD) hosting on godaddy. What I am afraid of? Is this server enough for my project(ram and 1cpu core)? Let's say if 100 users request at same time(for image and my code will merge 2 image and serve back) is my server enough to handle all this? I am using Postgresql database. Is postgresql good for such project? I am sorry if this is duplicate question, I honestly don't know what to search for? I am using nginx and Django rest framework for some basic features. -
Django form.is_valid() returning false
I am trying to update an instance from Author table, But form.is_valid returning false always. I have added enctype="multipart/form-data" in the template form, In the views im getting files also, but form is not validating. Am I missing anything? This is views section. def update(request,something,id): something=str(something).lower() if something=='author': author=Author_model.objects.get(id=id) if request.method=='GET': return render(request,'update_author.html',{'author':author}) else: form = Author_form(request.POST, request.FILES,instance=author) print('form.is_valid()',form.is_valid()) if form.is_valid(): image_path = author.image_document.path if os.path.exists(image_path): os.remove(image_path) form.save() return redirect('http://127.0.0.1:8000/bookdb/author/') This is a template. <form action="" method="post" enctype="multipart/form-data"> <center> <h2>Update Author</h2><hr> <table> <tr> <td>Solutation </td> <td>: <select name="" id=""> <option value="{{author.solutaion}}">{{author.solutaion}}</option> <option value="Mr">Mr</option> <option value="Ms">Ms</option> <option value="Dr">Dr</option> </select></td> </tr> <tr><td >Name </td> <td>: <input type="text" value="{{author.name}}"></td></tr> <tr> <td>Email </td> <td>: <input type="email" value="{{author.email}}"></td> </tr> <tr> <td>Headshot {{author.headshot}}</td> <td><img src="{{author.headshot.url}}" alt="Image not found" width="100" height="60"></td> <td>: <input type="file"></td> </tr> </table><br> <button type="submit">Submit</button> </center> {%csrf_token%} </form> -
How can I have my previous code through rollback on Heroku?
I have a problem with my app when I uploaded it on heroku, I used the rollback to go back to a previous version without errors and it seems to be fine when I give it open app. However, the code in pycharm shows the same errors, and if I commit, I get the errors of the latest version as if the code does not have the previous version, can I do something to recover that code?