Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting module not found "ModuleNotFoundError at /" Herokuapp Django
I and getting the below on Heroku Sub domain - https://icoder-django.herokuapp.com/ ModuleNotFoundError at / No module named 'blog.urls' requirements.txt asgiref==3.3.4 dj-database-url==0.5.0 Django==3.2 django-cors-headers==3.7.0 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.8.6 python-decouple==3.4 pytz==2021.1 sqlparse==0.4.1 whhitenoise==5.2.0 Error in web page ModuleNotFoundError at / No module named 'blog.urls' Request Method: GET Request URL: https://icoder-django.herokuapp.com/ Django Version: 3.2 Exception Type: ModuleNotFoundError Exception Value: No module named 'blog.urls' Exception Location: <frozen importlib._bootstrap>, line 984, in _find_and_load_unlocked Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] and this as well /app/iCoder/urls.py, line 26, in <module> admin.site.site_header = "iCoder Admin" admin.site.site_title = "iCoder Admin Panel" admin.site.index_title = "Welcome to iCoder Admin Panel" urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), … ] ▶ Local vars -
Django/Local Library. How to assign current user to field?
I've started learning Django and im doing a local library. I have a problem. I've created a model Book, which has a borrower. When I want to save current user as a borrower value changes only on page, but not in admin panel. It also changes every single books' value, not just the specific one. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=60) ISBN = models.CharField(max_length=13,unique=True) genre = models.ForeignKey(Gatunek,related_name='Books',on_delete=models.PROTECT) borrower = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default='') def __str__(self): return self.nazwa class BookRent(ListView): model = Book template_name = "Books/Book_rent.html" def get_queryset(self): user = self.request.user Book.borrower = user -
Is it possible to customize django.auth error message appropriate for certain registration errors?
I'm trying to display an error message for a certain error that user makes while registering, for now I've only covered an error regarding password and conf_passowrd not matching, but only that scenario works, whenever there is an error regarding, for example, too short password entered, it still displays the error regarding password mismatch. What I've tried so far: view.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def indexsignup(request): form = UserCreationForm() if request.method == 'POST': regForm = UserCreationForm(request.POST) if regForm.is_valid(): regForm.save() return redirect('login') else: for msg in form.error_messages: if len('password1') < 6: messages.error(request, f"PAss short") print(msg) else: messages.error(request, f"Two passwords don't match.") print(msg) return render(request, 'registration/register.html', {'form':form}) register.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Forum - SignUp</title> <link rel="stylesheet" href="{% static 'signup/style.css' %}"> </head> <body> <div class="signin-box"> <h1> Sign Up</h1> <form method="post" action=""> {% csrf_token %} <div class="textbox"> <input type="text" name="username" placeholder="Username" maxlength="10" autocapitalize="none" autocomplete="username" autofocus="" required="" id="id_username"> </div> <div class="textbox"> <input type="password" name="password1" placeholder="Password" autocomplete="new-password" required="" id="id_password1"> <script type="text/javascript"> function reveal() { if (document.getElementById('box').checked) { document.getElementById("id_password1").type = 'text'; } else document.getElementById("id_password1").type = 'password'; } </script> <div class="check"> <input title="Reveal password" type="checkbox" id="box" onclick="reveal()"> </div> </div> <div class="textbox"> <input … -
How to save videos and files as udemy, only those who bought the course can access and download the course videos and files
How to save videos and files as udemy, only those who bought the course can access and download the course videos and files in django i mean save my viedos and files private -
TypeError: a bytes-like object is required, not '_io.BytesIO' | Django | Pillow
I have been working one a Django project and I need to save an image file manually. So, I tried using PIL. Here's the code in my Django view that breaks- import PIL.Image as PilImage image_file = request.FILES.get("pic").file image = PilImage.open(io.BytesIO(image_file)) I don't understand it because io.BytesIO is a byte-like object, right? I couldn't find any solution anywhere so I'd appreciate any help. The full error is below - Traceback (most recent call last): File "G:\Workspace\Rabo\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "G:\Workspace\Rabo\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Workspace\Rabo\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "G:\Workspace\Rabo\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "G:\Workspace\Rabo\App\utils\login_required.py", line 25, in wrapper return f(self, request, user_id) File "G:\Workspace\Rabo\App\views\user_views.py", line 125, in post image = PilImage.open(io.BytesIO(image_file)) TypeError: a bytes-like object is required, not '_io.BytesIO' -
how to create new tag or select from current tags using Django forms
I have 3 tables, Products, Articles, and tags products and articles both have a "tags" field which has ManyToMany relation with the "tags" table I want to be able to reference multiple tags or create new tags while adding a product or an article (in one field)(using Django forms) for example, "test1" and "test2" are already in the tags table, I want the field to be like this: 1.I type "te" in the tags field 2.A drop down with "test1" and "test2" is opened which I can choose each one of them to be added in the field 3.I type "test3" (which isn't already in the tags table)and hit enter and "test3" is added to the field products and articles both have a "tags" field which has ManyToMany relation with the "tags" table (just like tags in a post in StackOverflow) I think Django built-in forms can handle this but I'm overwhelmed by the documentation and lost in the configuration of my Django forms. what kind of fields and widgets should I use for this purpose? Excuse me if the question is vague I'm new to Django and I would appreciate any kind of help. -
Django UpdateView returns a blank rendered template
I am using django allauth for user authentication, in my adapter I have modified the get_login_redirect_url to redirect new users to an ONBOARD_URL so they can complete registration process while regular users get the expected LOGIN_REDIRECT_URL class UserAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): if request.user.is_authenticated and (not request.user.name or not request.user.avatar or not request.user.mobile): url = settings.ONBOARD_URL else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) I have two functions handling the view and they both inherit from UpdateView and DetailView respectively. class UpdateUserAfterSignupView(LoginRequiredMixin, UpdateView): model = User form_class = UpdateUserAfterSignupForm template_name = 'users/user_form.html' context_object_name = 'user' success_url = reverse_lazy('users:detail') class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = 'username' slug_url_kwarg = 'username' template_name = 'users/user_detail.html' context_object_name = 'user' def get_object(self, queryset=None): return get_object_or_404(self.model, username=self.request.user.username) In my DetailView, if i leave out the get_object it returns a PageNotFound 404, but when its present as is, I get a blank page in the rendered template. This is the template: <p>welcome {{user}}</p> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" value="submit">submit</button> </form> and my url conf looks like this [ path('<str:username>/', views.UserDetailView.as_view(), name='detail'), path('complete-signup/', views.UpdateUserAfterSignupView.as_view(), name='complete_signup'), ] Again, all of these results in a blank rendered template, nothing at all. Could you please suggest things … -
Django queryset to string does not return the string in a test
I'm trying to write a unit test for this model: ADMIN = 1 FULL_USER = 2 LIMITED_USER = 3 class Role(models.Model): """ The class stores the model to store the different role which will be used to assign permissions to the users. """ ROLE_CHOICES = ( (ADMIN, 'admin'), (FULL_USER, 'full_user'), (LIMITED_USER, 'limited_user') ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) name = models.CharField('name', max_length=30) def __str__(self): """String for representing the Model object.""" if self.name: return self.name return self.id So I wrote this test: from example.models import Role from rest_framework.test import APITestCase class RoleModel(APITestCase): fixtures = ["initial_data/role.json"] def test_get_admin_role(self): role = Role.objects.filter(id=1) self.assertEqual(str(role), 'admin') But I'm not able to understand why it fails with this: AssertionError: '<QuerySet [<Role: admin>]>' != 'admin' - <QuerySet [<Role: admin>]> + admin I have read similar questions on how to get the string of the queryset and it should be the one defined in __str__. but I don't know why it is surrounded by <QuerySet [<Role: HERE_IS_MY_STRING]> if I'm asking for the string representation of the object. -
I need help. I am hosting site first time in my life. I want to deploy my Django site on AWS
when I will deploy the website at that time virtual env folder will helpful or only the requirement.txt file will enough. -
Dajngo: Get the ID of a clicked button
I am using django. In my views I want to know which button was pressed. My template.html looks like: {% for post in posts %} <button name="{{ post.pk }}" type="submit">{{ post.title }}</button> {% endfor %} I know that in my views.py I can check if button x was pressed by just: if '12345' in request.POST: # do something elif '23456' in request.POST: #do something else But is there a way to get the primary key without checking every key possible? I would love something like this: #PSEUDOCODE post_primary_key = request.POST.get_name() If my approach is fundamentally bad, I am also open to alternative ways of solving my problem. -
How to debug django-select2 dropdown
Id like to create a text search field based on dropdown options from a model. I chose on django-select2 but it isn't working. This is the output html <form class="add_new container" method="post"> <h3 class="text-center">Issue Book</h3><hr><br> {% csrf_token %} <h4> Choose the student to issue book to</h4><br> {% for field in form %} {{ field }} {% endfor %}<hr><br> <input type="submit" value="Issue" class="btn btn-dark text-right" style="float:right"> </form> This is the form class NewIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['borrower_id'].queryset = Student.objects.filter(school=school) self.fields['book_id'].initial = pk #Sets the field with the pk and it's hidden again class Meta: model = Issue fields = ['issuer','book_id','borrower_id'] widgets = { } widgets = { 'book_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'borrower_id': Select2Widget, } Settings.py hs the following CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } -
Digital Ocean Forbidden You don't have permission to access this resource
I am using Django I do not know how to setup config file ''' Alias /static root/pixlfy/googlesheet/static <Directory root/pixlfy/googlesheet/static> Require all granted <Directory root/pixlfy/googlesheet/googlesheet> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess pixlfy python-home=root/pixlfy/projectenv python-path=root/pixlfy/googlesheet WSGIProcessGroup pixlfy WSGIScriptAlias / root/pixlfy/googlesheet/googlesheet/wsgi.py <Directory root/pixlfy/googlesheet/googlesheet> Order allow,deny Allow from all </Directory> ''' -
Django template variable not rendering
So I am trying to render a django template variable, but for some reason it is not rendering out. I have the following code: Views.py ... def get_search(request, *args, **kwargs): context = {} context = {"test":"abcde"} return render(request, 'search.html', context) ... Urls.py urlpatterns = [ path("", home_view), path("articles/", include("papers.urls")), path("admin/", admin.site.urls), path("search/", search_view), path("submit/", submit_article_view, name="submit"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) search.html {extends 'base.html'} {% block content %} <p> {{ test }} hi </p> ... {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>Title</title> <link rel="stylesheet" type ="text/css" href="{% static 'css/stylesheet.css' %}"> </head> <header> {% include 'navbar.html' %} </header> <body> {% block content %} {% endblock %} </body> <footer> {% include 'footer.html' %} </footer> </html> Now, whenever I run the server and go to the search page, everything else gets rendered out, but the {{ test }} doesn't. The 'hi' does get rendered out. I have followed every tutorial and StackOverflow question out there, to no avail. Anyone has any idea what might be going on? Also, StackOverflow newbie, let me know if I did something wrong regarding that :). -
how do I take files from local file system (django) and render it to the frontend (react)
I am currently working on a web application which will only run on my machine. I want django to access my local file system using a python script and then send it to the react front-end in which it can be shown to the user. Is this possible? I can find no information on this except that django can access files from the media and static directories only. -
creating sidebar in django using CSS but appears nothing
i was trying to create sidebar base on codewithtim however it appears that it didn't read any of the css code below is my home.html: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <style type="text/css"> .sideenv a{ padding: 6px 8px 6px 18px; text-decoration: none; font-size: 25px; color: : #818181; display: block; } </style> <title>{% block title %}home{% endblock %}</title> </head> <body> <div class="sidenav"> <a href="">home</a> <a href="/vendor">vendor</a> <a href="/search">search</a> </div> </body> {% endblock %} and here is my base.html: <!doctype html> <html> <head> <title>{% block title %}prototype{% endblock %}</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> </head> <body> <!--{% include 'navbar.html' %}--> {% block content %} replace me {% endblock %} </body> </html> The only thing different from my code than codewithtime is i am trying to use block content to override some bolck. it might be wrong here, but i have no idea how to correct it ================================================================== And i have another question about using css in django when i google "css in django" usually the doc shows code below <head> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Linguist</title> </head> why did codewithtim can ignore the implementation and just include css might … -
ModuleNotFoundError: No module named 'xxxx.yyy'
I am very new to python programing and django.. I have not found any resources addressing this issue on web hence reaching out community. I have a django rest api with following code MyApi.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class MyOwnView(APIView): def get(self, request): return Response({'some': 'data'}) My module is not found in the url.py file, below is url.py file And urls.py file is here: from django.contrib import admin from django.urls import path from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User from jpbapi.api.MyApi import MyOwnView urlpatterns = [ path('admin/', admin.site.urls), ] This fails loading my module please see my project structure below, not sure where i am wrong. -
Is there a way in Django to unlock the resources before the transaction is over or to auto restart the transaction if the deadlock is found?
I have a model Orders in my Django rest-framework app. I am retrieving a list of orders based on some filter parameters and at the same time I am also locking orders using select_for_update(). Each order in the Orders model has a status and it could be OPEN, PARTIALLY_COMPLETED, COMPLETED or CANCELLED. However, one of my filter parameters will only consider the order with status OPEN or PARTIALLY_COMPLETED. So the retrieved list will have order with OPEN or PARTIALLY_COMPLETED status only. Furthermore, each order in Orders model also has the parameter units. This represents the units at which the order was created. If the order is in OPEN state then all the units are unsold or if the order is in PARTIALLY_COMPLETED then unsold_units = units - sold_units. Deriving the unsold units for PARTIALLY_COMPLETED orders is done after retrieving the list of orders. Now, let's assume the retrieved order list has 10 order and the total of unsold_units of the list is 1000. However, I just need 100 units so if the unsold_units of the first 3 orders is equal or over 100 units than the remaining orders must be unlocked immediately so that the other transaction can use it. … -
'int' object has no attribute 'user_list'. (Django Rest Framework)
I have a feature where user can remove an item from a list. The code below does successfully remove (delete) the item from the list but also returns the following error (and my AJAX call doesn't complete successfully): Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'user_list'. I am not sure how to debug this/why this error is being thrown. Here is my serializers: class UserVenueSerializer(serializers.ModelSerializer): venue = mapCafesSerializer() class Meta: model = UserVenue fields = ['user_list', 'venue'] Here is my views class RemoveVenueViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserVenueSerializer authentication_classes = [CsrfExemptSession] def get_queryset(self): user_list = self.request.GET.get('user_list', None) venue = self.request.GET.get('venue', None) data = UserVenue.objects.filter(user_list = user_list, venue= venue) print(data) return data.delete() Here is the traceback: <QuerySet [<UserVenue: UserVenue object (142)>]> Internal Server Error: /api/removevenue/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'int' object has no attribute 'user_list' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Order a queryset by a field in another queryset
In my django blog app, I have a model for Bookmark, which includes fields pointing to Post and User, and a field for when the bookmark was created. # models class Post(models.Model): # ... title = models.CharField(max_length=70) body = RichTextField() author = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name='posts') created_on = models.DateTimeField(default=timezone.now) # ... class Meta: ordering = ['created_on'] class Bookmark(models.Model): post = models.ForeignKey( Post, on_delete=CASCADE, related_name="bookmarked_post" ) user = models.ForeignKey( User, on_delete=CASCADE, related_name="bookmarks" ) created_on = models.DateTimeField(default=timezone.now) class Meta: ordering = ['created_on'] I have a view to display my users' bookmarks. I want to order the posts queryset in the order they were bookmarked, with the recently bookmarked posts first. # views.py @login_required def bookmarks_view(request): bookmarks = Bookmark.objects.filter(user=request.user) bookmarked_posts = Post.objects.filter( bookmarked_post__in=bookmarks).order_by(???) return render(request, 'bookmarks.html', posts=bookmarked_posts) I'm struggling to figure out how to order my Posts queryset by the created_on field in the Bookmark model. To add additional complexity, both the Post and Bookmark model have a created_on field. Can anyone point me in the right direction with this? I've scoured the django documentation and SO and not finding what I need, possibly I just don't know the right keywords... Or have I set up my models incorrectly to achieve what I … -
How to get individual users data after login in django?
iam new to django.Can anyone send me the code of signup and login page to get particular details of the username (i.e if we login with some usename then it should only give details of that username not remaining). -
django ajax like button with css classes
hello I have a post model which has a like(m2m) and user(forgeinkey) model field and Im trying to check if the request.user has liked the post and if they have, I should show them a red heart button else a blue heart should be shown, now since there are multiple posts and likes, Im looping through each like object to check if the request.user has liked it or not. Unfortunately for some reason, I couldn't implement a good logic and I see like button for every user. Some help would be appreciated. Here's my model: class post(models.Model): user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE) caption = models.CharField(max_length=100) image = models.FileField(upload_to='images/', null=True, blank=True) video = models.FileField(upload_to='videos/', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, null=True, blank=True, default='') The View: @login_required def usersfeed(request): users = User.objects.all() posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created') comments = Comment.objects.all() status_form = StatusForm(request.POST) friend_requests = FriendRequest.objects.filter(to_user=request.user) friends = request.user.profile.friend.all() for i in posts: likes = i.like.all() print(likes) for like in likes: if like.username == request.user.username: if request.user: Hasliked = True print('liked') else: Hasnotliked = True print('not liked') context = { 'Post':posts, 'User':users, 'form':PostForm(), 'Profile':profile, 'Form':CommentForm(), 'Comment':comments, 'Status':status_form, 'fr':friend_requests, 'friend':friends, 'Hasliked':Hasliked, 'Hasnotliked':Hasnotliked, } return render(request, 'social_media/feed.html', context=context) The view for … -
NoReverseMatch at / Reverse for 'url' with arguments '('',)' not found
I am trying to pass URL as a parameter in dynamic URL. The URL contains ? which is making django search for the keys. How do I make Django ignore '?' that are present in my URL. Custom URL: https://www.amazon.in/Samsung-Galaxy-M12-Storage-Processor/dp/B08XGDN3TZ/ref=sr_1_1_sspa?dchild=1&keywords=redmi+9&qid=1622011804&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFZSlE5U0lEUzBFUVQmZW prd.Url is passed as a parameter {% for prd in prds %} {{ prd.name }} <a href="{% url 'url' prd.Url %}">Click</a> {% endfor %} urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('create/', createProfile.as_view(), name='create_profile'), path('update/<pk>', UpdateProfile.as_view(), name='update_profile'), path('url/<my_url>', url, name='url') ] -
Django filter and paginate not working. (Using AJAX)
I have a table for tracking job applications and im trying to implement a filter feature. On choosing a filter for instance closing date, the jobs are sorted by closing date and displayed in table. The query is working fine. I have printed the results. Is there a way I update the page without refresh and paginate the new results? Please help.... Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { //I want the page to not refresh here }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) if filter_cat == "Alphabetical Order (A-Z)": int_applications = InternshipApplication.objects.filter(student=student). order_by('internship__internship_title') if filter_cat == "Application Date (Ascending)": int_applications = InternshipApplication.objects.filter(student=student). order_by('application_date') if filter_cat == "Application Date (Descending)": int_applications = InternshipApplication.objects.filter(student=student). order_by('-application_date') if filter_cat == "Closing Date": int_applications = InternshipApplication.objects.filter(student=student). order_by('-internship__internship_deadline') applications = [] for app in int_applications: internship = Internship.objects.get(id=app.internship.id) recruiter = Recruiter.objects.get(id=internship.recruiter.id) applications.append((internship,recruiter,app)) for internship, recruiter, app in applications: print(internship) print(recruiter) … -
how to create a decorator/ wrapper class in python to pass the attributes of error logs as a single parameter?
@api_view(['GET']) def test_api_method(self): print('This is Test API') db_logger = logging.getLogger('db') try: 1 / 0 except Exception as e: db_logger.exception(e, extra={'user': self.user.username, 'class_name': self.__class__.__name__,'method_name':sys._getframe().f_code.co_name, 'module_name':__package__,'ip_address': socket.gethostbyname(socket.gethostname())}) return Response({'data': True}, status=status.HTTP_200_OK) I want to create a decorator or a wrapper class to pass the parameters in the db_logger.exception() as a sin single parameter. Mainly, I wanted to replace this dictionary---> extra={............} with a single parameter so that this error logging method can be used to log errors across all classes and methods. -
Change Django Database : SQLITE3 to MARIADB
I am new to Django and python! I made a project on Django with the default database which is sqlite3. I want to now transfer the database from sqlite3 to Mariadb. There is no data which is present in current sqlite3. I just want to know how can I transfer the default database. I have followed the following documentation: And added, this to my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Altiostar', 'USER': 'satharkar', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '', } } I am not sure, how things will work with this now. I am looking if someone can help me with this. So what I did is by now : I deleted the db.sqlite3 from my project folder. Tried to run python manage.py makemigrations but it is throwing error that mysql client is not installed. I have followed the documentation and installed everything mentioned their. How will things work after this ? So whenever I will try to submit the form in my django project, database, table will be created and data will be then stored under the mariadb? I am new to all this, looking for a resolution in this case or any suggestions on …