Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django authentication on home page
How can i compare the name of the logged in user on a django home page template with any other string this is what i tried -
Error in running Plotly Dash Plot in Django with UWSGI and NGINX
I have a Django project with UWSGI and NGINX. There are multiple pages and the page with Interactive Plotly Dash Plot cannot work. For the other pages, they work fine. When I go to some of the Interactive Plotly Dash Plot, some of them can only loads the frame only. enter image description here Some of them simply get a Server Error(500) I check the log and get the following: Traceback (most recent call last): File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/utils/deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/contrib/sessions/middleware.py", line 63, in process_response raise SessionInterrupted( django.contrib.sessions.exceptions.SessionInterrupted: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example.: /django_plotly_dash/app/vis1/_dash-update-component Traceback (most recent call last): File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: attempt to write a readonly database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/python-virtual-env/web_project/lib64/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 87, in save obj.save(force_insert=must_create, … -
How to get null for rows where data doesn't exist in Postgres while performing joins
I have 2 tables. Items and Rates. All the items are stored in items table and rates are stored daily in rates table. Items and rates are linked using FK on rates table. When the rates are stored if it is not preset then row is not stored. Like for item 5 if no rate is present on 1st jan, there wont be a record for item 5. When getting the data I want item 5 rate as null (as shown in example pic). How can I proceed? I tried left joins, left Join is not working, sometimes depending on the data I get the date as null, sometimes everything except item pk is null. I dont know how to proceed furthur with this. -
Error while passing Variable from View to Form in Django
I try to send a variable form View to Form in Django. I find a solution and it's working but the problem is that I have to call the fonction form = DonneeForm(variable=variable) but it seems to just send me the entire HTML code. So I would like to find a way for the DonneeForm() to behave as DonneeForm which work but doesn't allow me to send a variable. Thanks Form.py class DonneeForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.boitier = kwargs.pop("boitier", 1) # client is the parameter passed from views.py super().__init__(*args, **kwargs) boitier = get_object_or_404(Boitier, pk=int(self.boitier)) self.fields['connexion_donnee'].queryset = boitier.donnee class Meta: model = Donnee fields = ['utilise', 'connexion_donnee', 'nom', 'type_donnee', 'valeur_min', 'valeur_max', 'tolerance', 'afficher_valeur', 'inverse'] labels = { } widgets = { 'type_donnee': forms.Select(attrs={"readonly": "True"}) } View.py type_capteur = get_object_or_404(TypeCapteur, pk=pk) capteur = get_object_or_404(Capteur, pk=article) type_capteur_donnees = type_capteur.donnee.all().count() print(DonneeForm(boitier=boitier.pk)) form = DonneeForm(boitier=boitier.pk) donnee_form_set = formset_factory(form, extra=type_capteur_donnees, max_num=type_capteur_donnees, absolute_max=type_capteur_donnees) formset_donnee = donnee_form_set if request.method == 'POST': formset = donnee_form_set(request.POST, request.FILES) if formset.is_valid(): for form in formset: if form.cleaned_data: donnee = form.save(commit=False) donnee.capteur = capteur donnee.save() capteur.save() return redirect("smart_workshop_app:configuration_capteurs") else: initial = [] for type_donnee in type_capteur.donnee.all(): initial.append({'type_donnee': type_donnee, 'nom': type_donnee.nom}) formset = formset_donnee(initial=initial) print(formset_donnee) context = {"formset": formset, "instance_id": pk, "instance_article": article} … -
Django : Fix admin link to website ressources when apps are in subfolders
Here is the architecture of my django project : project/ apps/ app1/ app2/ ... core/ management/ settings.py ... static/ templates/ utils/ It is not a conventional tree, but it works pretty well. Problem I have is with reverse admin urls. Django admin provide direct links to resources which are broken, giving me the following error : Reverse for 'pattern_name' not found. 'pattern_name' is not a valid view function or pattern name. pattern_name does exists indeed, but is behind app app1, and should be called app1:pattern_name. I don't find any documentation about this. Is there a way to fix it ? -
Django auth crash
Need help from someone experienced with Django: I'm using Django Test Client to create a request to test instance of API running in docker. Running through custom auth backend successfully, the authenticate method returns a user generated from get_user_model() and then this crash happens with following stack trace: Traceback (most recent call last): File "/my/repo/api/v1/tests/system/test_auth.py", line 29, in test_auth response = self.client.post( File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 852, in post response = super().post( File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 441, in post return self.generic( File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 541, in generic return self.request(**r) File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 810, in request self.check_exception(response) File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line 663, in check_exception raise exc_value File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 414, in initial self.perform_authentication(request) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 387, in … -
How to implement auto-refresh jwt token in server side (DRF)?
I want to refresh my jwt access token automatically when the access token expires. (only in server-side, I'm using Django) Also, I am storing tokens in HttpOnly Cookie. This is my DEFAULT_AUTHENTICATION_CLASSES in my settings.py. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'account.authenticate.CustomAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), I checked that authentication works everytime I get URL. So I tried to add code about Refreshing token in my custom Authentication class which overrides JWTAuthentication. ( JWTAuthentication document ) authenticate.py class CustomAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) # if access_token expires if raw_token is None: refresh_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_REFRESH']) or None serializer = TokenRefreshSerializer(data={'refresh': refresh_token}) # if refresh_token is valid if serializer.is_valid(): raw_token = serializer.validated_data['access'] # set cookie about access_token response = HttpResponse() response.set_cookie( key=settings.SIMPLE_JWT['AUTH_COOKIE'], value=raw_token, max_age=3600, # 1 hour secure=settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly=settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite=settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token And these are the problems. It can't return response. So, the cookie(access_token) can't be set in the request.header. Explanation about authenticate in simplejwt-document authenticate(request) Authenticate the request and return a two-tuple of (user, token). The Cookie (access_token) is not in the request.header. So it always generate new access_token. Cookie's max age doesn't work after access_token … -
django - ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)
I'm trying to send an email in django, but I can't. I keep getting an SSLError (With the code below) or I get timed out (When I use port 465) EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = config['EMAIL'] EMAIL_HOST_PASSWORD = config['PASSWORD'] DEFAULT_FROM_EMAIL = config['EMAIL'] EMAIL_USE_SSL = False EMAIL_USE_TLS = False EMAIL_USE_STARTTLS = True How do I fix this? Thanks :) -
JSON string passed from frontend with AJAX POST to Django view results in strange characters added
I am trying to pass a GeoJson with AJAX call to backend. I printed to console before sending the whole string and no error was there. Printing in the view the request.POST shown this error. The error occurred on the 'streetWeb' variable. This variale comes from a textfile. Its content comes from a GeoJson stringified. The call $.ajax({ type: 'POST', url: $('#confImp').data('url'), contentType: "application/x-www-form-urlencoded; charset=utf-8", data: { "csrfmiddlewaretoken": csrftoken, 'streetWeb': toExpwe, 'int_points': toExpip}, success: function(res){ ......... } }) This error occurs a couple of times always identical. The following image shows the error I got. -
Saving data has no effect but data is there and request is sent
I have this product model and I am trying to update it and I can see all the data from the form sent to the backend and in the backend I can see all the data coming from the front end. When I save nothing happens and the request is sent and the response is the object but none of the fields I updated is correct. Nothing changed and the values remain the same. Here is the Product model: class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" ordering = ["title"] def __str__(self): return self.title and here is the view I use for updating: class UpdateProductView(generics.UpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UpdateProductSerializer def get_queryset(self): id = self.kwargs["pk"] return Product.objects.all().filter(id=id) and the serializer … -
How to send DELETE method without PK in tests? Django Rest Framework
My DELETE method have a format like: DELETE /albums and IDs for deletion are passed in the body of the request. ids: [1, 2, 3...] My urls: router = SimpleRouter(trailing_slash=False) router.register(r'albums', AlbumViewSet, basename='albums') I can easily send this request from the Postman and it works correctly. But I can't replicate it using tests url = reverse('albums-detail') This pattern wants pk for the request, but my request does not include it. How can i send the DELETE request from the tests without PK? -
How to check User status is available or not in django orm?
How to check user status available or not and between start date and end date if same user status canceled and another is approved create timesheet status rejected and another is canceled create timesheet status canceled and another is canceled create timesheet IF User is status is pedning Dont create Timesheet Below is my code def submit_attendance(request, approval_status=None): if request.method == "POST": month = request.POST.get("month") year = request.POST.get("year") now = datetime.date.today() first, last = calendar.monthrange(int(year), int(month)) month_first_date = datetime.date(int(year), int(month), 1) month_last_day = datetime.date(int(year), int(month), last) two_digit_month = month if len(month) > 1 else "0" + month attendance_objects = Attendance.objects.filter(employee=request.user, date__month=month, date__year=year) leave_data = EmployeeLeaves.objects.filter(~Q(approval_status='Approved'),~Q(approval_status='Cancelled'),~Q(approval_status='Rejected'), from_date__gte=month_first_date, to_date__lte=month_last_day, employee=request.user).exists() leaves_data = EmployeeLeaves.objects.filter(~Q(approval_status='Pending'), from_date__gte=month_first_date, to_date__lte=month_last_day, employee=request.user).exists() print(leaves_data) for att in attendance_objects: try: print('test1') time_sheet_obj = Timesheet.objects.get(employee=request.user, date=att.date, status=1) time_sheet_obj.employee = User.objects.get(id=att.employee_id) time_sheet_obj.date = att.date time_sheet_obj.workingday_holiday = att.workingday_holiday time_sheet_obj.in_time = att.in_time time_sheet_obj.out_time = att.out_time time_sheet_obj.shift = att.shift time_sheet_obj.working_hours = att.working_hours time_sheet_obj.remarks = att.remarks time_sheet_obj.status = 1 time_sheet_obj.save() att.status = 1 att.save() except Timesheet.DoesNotExist: time_sheet_obj = Timesheet.objects.create( employee=request.user, date=att.date, workingday_holiday=att.workingday_holiday, in_time=att.in_time, out_time=att.out_time, shift=att.shift, working_hours=att.working_hours, remarks=att.remarks, status=1 ) print(time_sheet_obj,'comming') time_sheet_obj.save() att.status = 0 att.save() -
Django template6
TemplateDoesNotExist at / todo_list_templates/list.html Request Method: GET Request URL: http://127.0.0.1:8001/ Django Version: 4.1.2 Exception Type: TemplateDoesNotExist Exception Value: todo_list_templates/list.html Exception Location: C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: todo_list.views.index Python Executable: C:\Users\sachi\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Python Path: ['C:\Users\sachi\Todo_app', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310', 'C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages'] Server time: Fri, 24 Feb 2023 07:00:37 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\sachi\Todo_app\Templates\todo_list_templates\list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\templates\todo_list_templates\list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sachi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\templates\todo_list_templates\list.html (Source does not exist) i tried everything but couldnot work for me -
AWS s3 bucket Referer returns 403
I want to allow access to specific folder in the bucket from the admin page only. The s3 bucket is accessed by a mobile app so CORS is useless. here's my statment { "Sid": "Stmt1234567890", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::exampleBucket/id/*", "Condition": { "StringLike": { "aws:Referer": "https://example.me/*" } } } I still get 403 on loading the image on the site using tag I made sure the referer in the request using javascript document.referrer I've no idea what I'm doing wrong -
Battling to update an object in Django
I am trying to update a product and really having a hard time understanding the process of what happens when you use the UpdateAPIView from Django Rest Framework Here is the product model: class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) discount_price = models.DecimalField( max_digits=20, decimal_places=2, blank=True, null=True ) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) color = models.CharField(max_length=3, choices=COLORS, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) stock = models.DecimalField(max_digits=30, decimal_places=0) is_published = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" ordering = ["title"] def __str__(self): return self.title def get_absolute_url(self): return self.slug Here is the view I use to update the object: class UpdateProductView(generics.UpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UpdateProductSerializer def get_queryset(self): id = self.kwargs["pk"] return Product.objects.all().filter(id=id) and here is the serializer: class UpdateProductSerializer(ModelSerializer): class Meta: model = Product fields = '__all__' … -
Is overriding the Django model's save function okay in this scenario?
So, I have a model, whose save function has some side effects like this: from django.db import models class Customer(models.Model): customer_name = models.CharField(max_length=255) customer_email = models.EmailField() customer_phone = models.CharField(max_length=20) customer_address = models.CharField(max_length=255) class Product(models.Model): product_name = models.CharField(max_length=255) product_description = models.TextField() product_price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_date = models.DateField() order_total = models.DecimalField(max_digits=10, decimal_places=2) class Order_Item(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() item_price = models.DecimalField(max_digits=10, decimal_places=2) class User(models.Model): username = models.CharField(max_length=255) email = models.EmailField() password = models.CharField(max_length=255) class OrderFolder(models.Model): REASON_ARCHIVED = 'ARCHIVED' REASON_REVIEW = 'REVIEW' REASON_CHOICES = [ (REASON_ARCHIVED, 'Archived'), (REASON_REVIEW, 'Review'), ] order = models.ForeignKey(Order, on_delete=models.CASCADE) reason = models.CharField(max_length=10, choices=REASON_CHOICES) user = models.ForeignKey(User, on_delete=models.CASCADE) class Payment(models.Model): payment_date = models.DateField() payment_amount = models.DecimalField(max_digits=10, decimal_places=2) payment_method = models.CharField(max_length=50) order = models.ForeignKey('Order', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Payment, self).save(*args, **kwargs) # If order is paid and order is not in review, move it to the ARCHIVED folder if self.order.order_total == self.payment_amount: of = OrderFolder.objects.get(pk = self.order.id) if of.reason != 'Review': of.reason = 'ARCHIVED' of.save() In the above code, I override the Payment's save method to have a side effect in another table. Django allows overriding save method, but is this approach acceptable considering: Potentially … -
Django QuerySet incorrectly has size 0 but has an element
When I make a query on a model with a Model.objects.filter(filters) call, it returns a queryset with all the elements that satisfy the filters passed present in it. as expected. However, in this particular case, Django returned a queryset that looks like this: which should already be impossible. As you can see, the size of the queryset is 0, Model.objects.filter(filters).count() returns 0, as does len(list(Model.objects.filter())), which is supposed to force evaluate the query, and should have returned a queryset of size 1 with the element. I know that the size of the queryset should have been 1 because Model.objects.get(filters) returns the object as expected in the debugger evaluation window. One thing that might be of interest is that this behaviour is corrected when a previous filter call is removed. The Case: Initial state: There is a table that corresponds to a django.models.Model in Django, and has 0 rows and 0 constraints. Steps to replicate: Evaluate a query using Model.objects.filter(a=x,b=y) where a and b are columns in Model and x and y are valid values, and neither a nor b are primary keys. Since the table is empty, the result will be an empty queryset. Create an object with a=x and … -
How to give start time to django-apscheduler?
I want to create a scheduler that will start counting the interval from the time that I give as starting time. I know that this is the format: from apscheduler.schedulers.background import BackgroundScheduler def start(): scheduler = BackgroundScheduler() scheduler.add_job(schedule_api, 'interval', minutes=5) scheduler.start() I want this scheduler to count minutes from the datettime that I give, is there a way to do that? -
Datatble datetime field is sorted as string
I have a Datatble for my django web app, the backend sends date for the field updated as 'Feb. 14, 2023, 3:58 p.m.'. when I use the sorting feature, it always sorts as alphabetical order, where 'April 24, 2023, 10:04 a.m.' comes before Feb because A is bigger than F in alphabetical order, so how to solve this? I tries some from datatble jquery documentation and some StackOverflow answers but it didn't gave me the desired output -
Django POST API id become null when password hashed
Hi im new to django and python, i want to make API to add user and it worked but when i try login with it but the result is i cant login, seems like it must hash password for system can read the user, and i try to hash my password in model. heres my model : from django.contrib.auth.hashers import make_password class MyUser(AbstractUser): pass password = models.CharField(max_length=128, null=False) def save(self, *args, **kwargs): self.password = make_password(self.password) but its make id become null heres the screenshot of result when i use make_passwod and not: screenshot when make_password not added screenshot when make_password added im following this tutorial with a bit modification heres the link django-rest-framework-create-api cause the id null the data not saved to database. So the question how to add the id ? why the id become null when i add make_password ? or maybe i am missing something ? thank you in advance -
Unable to authenticate my login details with custom backend authentication
For some reason, even when I enter the right details, it does not refer me to the home page and instead just acts like i keyed in wrong details. Would appreciate some help, thanks! views.py def login_view(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('index.html') else: return render(request, 'login.html', {'error': 'Invalid credentials'}) else: return render(request, 'login.html') auth_backend.py class EmailAuthBackend: def authenticate(self, request, username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None -
Problem on Python Django Application When I execute a Number of Input Values
I'm developing an application using Python Django, these app there are some codes in JavaScript because it needs to run in a web browser. When I execute the application with a certain number of input values Django's terminal (I'm using PyCharm) shows these things: Signal received: -250068120, errno: 32607 ################################################################################ Stack trace: ################################################################################ /usr/local/lib/python3.8/dist-packages/_awscrt.cpython-38-x86_64-linux-gnu.so(aws_backtrace_print+0x4f) [0x7f5ff65c392f] /usr/local/lib/python3.8/dist-packages/_awscrt.cpython-38-x86_64-linux-gnu.so(+0x726c3) [0x7f5ff65316c3] /lib/x86_64-linux-gnu/libc.so.6(+0x43090) [0x7f6046e9b090] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(tabu_search+0x475) [0x7f5ff1cc8c35] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(solve+0x990) [0x7f5ff1cca4b0] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(+0x17915) [0x7f5ff1cd6915] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(+0x1af96) [0x7f5ff1cd9f96] /usr/bin/python3(PyCFunction_Call+0x59) [0x5f5b39] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x62cd) [0x57165d] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(PyObject_Call+0x62) [0x5f52b2] /usr/bin/python3(_PyEval_EvalFrameDefault+0x1f2c) [0x56d2bc] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3() [0x50b32c] /usr/bin/python3(PyObject_Call+0x62) [0x5f52b2] /usr/bin/python3(_PyEval_EvalFrameDefault+0x1f2c) [0x56d2bc] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x851) [0x56bbe1] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3(_PyEval_EvalFrameDefault+0x726) [0x56bab6] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3(PyObject_Call+0x62) [0x5f52b2] /usr/bin/python3(_PyEval_EvalFrameDefault+0x1f2c) [0x56d2bc] /usr/bin/python3() [0x50b22e] /usr/bin/python3(_PyEval_EvalFrameDefault+0x726) [0x56bab6] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) … -
Include additional details in Django error log for improved debugging?
Let's say I have a simple django view like so # views.py def view1(request): val = 5 / 0 return JsonResponse({"val": val}) and I have the following config for logging with debugging intentionally set to False # settings.py DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': f'{BASE_DIR}/logs/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } If I were to call the view, I would see the following statement in my logs Internal Server Error: /view1/ Traceback (most recent call last): File "/opt/pyenv/versions/3.10.8/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/pyenv/versions/3.10.8/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/code/app1/views.py", line 14, in view1 val = 5 / 0 ZeroDivisionError: division by zero I can easily enable monitoring alerts to be notified of such errors like these when they occur. And I can inspect the log to see what line failed with what exception. But I am lacking other vital information in order to fully debug the issue. How can I include additional details into this log? Details such as the URL that was called, query parameters, the incoming payload, … -
Getting 500 Internal Server Error when Deploying Django Project in Linux Server using ubunto 18.04 Apache
I have deployed a Django Project using 18.04 and before using Apache I was testing using Portal:8000 and it worked perfectly fine when I added Apache and made the required changes I am getting 500 Internal Server Error and in the log I am getting the following error [Fri Feb 24 02:22:13.453312 2023] [wsgi:error] [pid 7610:tid 140621178033920] Traceback (most recent call last): [Fri Feb 24 02:22:13.453355 2023] [wsgi:error] [pid 7610:tid 140621178033920] File "/home/user/project/project/wsgi.py", line 12, in <module> [Fri Feb 24 02:22:13.453364 2023] [wsgi:error] [pid 7610:tid 140621178033920] from django.core.wsgi import get_wsgi_application [Fri Feb 24 02:22:13.453388 2023] [wsgi:error] [pid 7610:tid 140621178033920] ModuleNotFoundError: No module named 'django' [Fri Feb 24 02:25:31.905130 2023] [wsgi:error] [pid 7610:tid 140621161248512] mod_wsgi (pid=7610): Target WSGI script '/home/user/project/project/wsgi.py' cannot be loaded as Python module. [Fri Feb 24 02:25:31.906124 2023] [wsgi:error] [pid 7610:tid 140621161248512] mod_wsgi (pid=7610): Exception occurred processing WSGI script '/home/user/project/project/wsgi.py'. [Fri Feb 24 02:25:31.906647 2023] [wsgi:error] [pid 7610:tid 140621161248512] Traceback (most recent call last): [Fri Feb 24 02:25:31.906871 2023] [wsgi:error] [pid 7610:tid 140621161248512] File "/home/user/project/project/wsgi.py", line 12, in <module> [Fri Feb 24 02:25:31.906979 2023] [wsgi:error] [pid 7610:tid 140621161248512] from django.core.wsgi import get_wsgi_application [Fri Feb 24 02:25:31.907098 2023] [wsgi:error] [pid 7610:tid 140621161248512] ModuleNotFoundError: No module named 'django' Here is … -
Why am I getting an attribute error with object has no attribute get, in django?
Models.py: class WeeklyPlan(models.Model): title = models.CharField(max_length=255, verbose_name="Weekly Plan Name") monday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="monday_plans") tuesday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="tuesday_plans") wednesday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="wednesday_plans") thursday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="thursday_plans") friday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="friday_plans") def __str__(self): return self.title Views.py: from django.shortcuts import render from .models import WeeklyPlan, Extra, Meal # Create your views here. def homepage(request): plans = WeeklyPlan.objects.all() print(plans) context = {"plans": plans} return render(request, template_name='food/index.html', context=context) I would've expected this to output all the weekly plan objects but instead got the error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Rayyan Admin\Documents\GitHub\food_delivery\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Rayyan Admin\Documents\GitHub\food_delivery\venv\lib\site-packages\django\utils\deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "C:\Users\Rayyan Admin\Documents\GitHub\food_delivery\venv\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'WeeklyPlan' object has no attribute 'get' Can anyone assist me on this?