Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Log Django shell operations to Google Cloud
We use Django shell (shell_plus to be specific) to do some operations with our data. We would like to log all the operations to comply with some regulations. For example, if we are in the shell now: >> user = User.objects.get(id=1) >> user.name >> Steve These 3 lines of code should be logged (ideally in our Google Cloud logging). What I've found so far, is using iPython and their logstart magic command. For this, I need to create a ipython-config.py file where I specify the log file: # ipython-config.py c = get_config() time_stamp = datetime.now().strftime("%Y-%m-%d-%H-%M") c.InteractiveShellApp.exec_lines = ["%%logstart -t -o /var/log/django/shell-%s.log"" % time_stamp] It now automatically will create a file and save everything (basically what we need). However, we need them to be in Google cloud logs. One option we could use google.cloud.logging lib for python, create a client and then if we run logging.info(msg) (from standard python lib) we will have them logged to GC. But iPython logstart magic function does not seem to even log to stdout, only to file. Is there anything we can do to achieve this? -
Assign 0 if the date doesn't exist in the records from the database
I'm trying to generate a list of values to plot on a dashboard. The list shows how many orders have been made per day for the last 7 days, and if there was no order recorded for that day, then return 0. For example, if we have this order tracker model: Order: {date_ordered (date), count_orders (int), restaurant (string)} If we want to list all the orders for the last seven days, I'd do something like: from datetime import datetime, timedelta from .models import Order last_seven_days = datetime.now()-timedelta(days=6) orders = Order.objects.filter(date_ordered__gte=last_seven_days).order_by('date_ordered') orders return something like this: [<19-05-2022, Restaurant1, 35>, <19-05-2022, Restaurant2, 30>, <22-05-2022, Restaurant1, 19>, <22-05-2022, Restaurant2, 10>, <23-05-2022, Restaurant1, 32>] The final result I would like to get is stretched over the last 7 days. If the last seven days are ['18-06-2022', '19-06-2022', '20-06-2022', '21-06-2022', '22-06-2022', '23-06-2022', '24-06-2022'] Then my output needs to be: [[0,35,0,0,19,32,0], [0,30,0,0,10,0,0]] The above array basically says 2 things: 1- there should be as many tuples as restaurants 2- if the date doesn't exist it means 0 orders were recorded. I feel this can be solved using a query rather than looping 3 times and many conditions. Can you please share some thoughts on this? Thanks -
Use JWT in Django - Automatic refresh token after 'ACCESS_TOKEN_LIFETIME' ends
I want to implement simpleJWT in API in such a way that generated token is send to API request and if the JWT lifetime expires then automatically refresh that token and from now the new token should be used in API request. my customrequest code is--> def _get_jwt(self): refresh = RefreshToken.for_user(self.user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } def _get_authorization_headers(self): """ This function returns authorization headers including token Which is to be passed in post method Returns: This function returns dictionary that contains Authorization (Token) and content-type """ if self.jwt: # access_token = headers = {"Authorization": "Bearer {}".format(self._get_jwt()["access"]), "content-type": "application/json"} else: headers = {"Authorization": "Token {}".format(self._get_token(self.token)), "content-type": "application/json"} return headers def post(self, url=None, data=None): """ This function sends post request to the url Params: url = endpoint where we want to send post request data = data to be sent on that endpoint """ url = self.url + url headers = self._get_authorization_headers() result = requests.post(url, data, headers=headers) return result.text currently I'm using this approach but problem is that, token which is generated first time same token is in headers even after JWT lifetime expires after 5 minute('ACCESS_TOKEN_LIFETIME': timedelta(minutes=5) ) and I want to use new token after every time token … -
ModuleNotFoundError: No module named 'app1'
Using VS Community 2022 I did create django project 'Project0' (I am learning). I've a folder named 'Project0' (which contains the settings.py file) in same line as that of manage.py . There is default 'app' folder in the same line created by VSCommunity 2022. runserver command also succeeded until here. I then right clicked the folder 'Project0' --> Add --> Django app Created new app named 'app1', which has got created within the folder 'Project0'. Structure is like below (not giving all the file names though) Project0 | Project0 |--app1 |-- app | manage.py | I did add the newly created app 'app1' within the Settings.py inside INSTALLED_APPS commands. But when I tried to run the server now, it is throwing error as No module named 'app1'. The server was successfully connected before the creation of the app 'app1'. But now it is not. Unable to fix this error. Request your help. -
Load datepickers created after page is ready
I have a Django template in which I use bootstrap-datepicker-plus. However, I made a form in which the user can click a button in order to display as many datetime field as needed. The issue I'm encountering is that bootstrap-datetime-picker only loads the datetime fields present when the page charges, but if I want to add new datetime fields, then those are not loaded. After searching in the source code, I found out that it indeed was only loading the field when the page is ready but doesn't look for other datetime fields after that. I tried some things and saw that by reimporting the js file with <script src="/static/bootstrap_datepicker_plus/js/datepicker-widget.js"></script> each time I make a change it's working, but I can't do that for each situation, and I guess that's not really a good practice. Is there a way to like refresh the bootstrap-datetime-picker's js file each time I create a new datetime field ? I don't know if that's useful, but here's bootstrap-datetime-picker's js file that loads the datetime pickers : (function (factory) { if (typeof define === 'function' && define.amd) define(['jquery'], factory) else if (typeof module === 'object' && module.exports) module.exports = factory(require('jquery')) else factory(jQuery) }(function ($) { … -
Django 4.0.4 doesn't reconnect to MySQL transparently?
I've read this question, but apparently the behaviour is still vague. I've a long running process which makes a round each second. During the round I make a request to the DB (select type), then have some processing, eventually saving objects. If the connection is broken for some reason, first of all I get this exception: django.db.utils.OperationalError: (2013, 'Lost connection to server during query') I then do nothing about the connection (no closing, no pinging), and on the next round I get this: django.db.utils.OperationalError: (2006, 'Server has gone away') The situation repeats ad infinitum, nothing rectifies itself. Therefore the question: the rumours of django reconnecting itself are not true? I've MAX_CONN_AGE set to 0, and MySQL wait_timeout is default 28800 (in any case since I have a DB request each second, I should never experience that timeout). I would expect django reestablishing the connection if the server is gone, why it's not happening? -
sitemap could not be read
the sitemap could not be read: <img src='https://i.stack.imgur.com/nUZih.jpg'> this is the error text: <img src='https://i.stack.imgur.com/nUZih.jpg'> sitemap validator said that my sitemap is correct https://www.xml-sitemaps.com/validate-xml-sitemap.html: <img src='https://i.stack.imgur.com/jcigy.jpg'> -
Why is my Django DRF RequestsClient request failing in tests?
I have a few Django Rest Framework API endpoints I want to test. They are behind an authenticated page. I'm trying to use the DRF RequestsClient to do that. My code looks like this: from rest_framework.test import APITestCase from rest_framework.test import RequestsClient from django.urls import reverse import requests URL_PREFIX="http://testserver" API_TOKEN="tfhgffhgf675h" class APITests(APITestCase): @staticmethod def _get_full_url(url, *args, **kwargs): return URL_PREFIX + reverse(url, *args, **kwargs) def setUp(self): self.client = RequestsClient() def test_stuff(self): url = self._get_full_url("ahs:agena_results-list") # Raw requests library - works fine # Note: Testing shows that the RequestsClient() seems to do some sort of magic to # be able to resolve http://testserver. A raw requests GET request must hit it at # 127.0.0.1, and specify the port response = requests.get("http://127.0.0.1:8000", headers={"Authorization": f"Token {API_TOKEN}"}) # RequestsClient() - doesn't work response = self.client.get(url, headers={"Authorization": f"Token {API_TOKEN}"}) My RequestsClient request doesn't work, but my raw requests request works fine. The exception raised when using the RequestsClient is pretty cryptic: Internal Server Error: /ahs/api/agena_results/ Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1361, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 83, in _execute self.db.validate_no_broken_transaction() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", … -
Is it possible to add an input field to Wagtails custom bulk actions?
Is it possible to add an input field to Wagtails custom bulk actions? In the template from the documentation example there is a block called form_section. Here I want to add a separate form to add another input field. Another position would be possible as well, of course. I would love to bulk select Image instances to add them to a Page. So I need to have a ChoiceField to select the Page. This would also require a customized View for the logic behind this "import". The latter is not the question. I am just wondering how I can add this input field and alter the view of a these marvelous bulk actions. -
How to store files inside directory for temporary and make a zip file?
Here I have a list of images that I want to make a zip and download. For this I tried to upload these images inside the project directory first and then trying to zip from this uploaded files. I am getting this error: IOError: [Errno 21] Is a directory: '/home/project/images' How can I send a zip file with these images ? images_list = [image_absolute_url1, image_absolute_url2] folder = os.path.join(BASE_DIR, "images") os.mkdir(folder) with open(folder, 'wb+') as f: for file in images_list: f.write(file) response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') for filename in images_list: zip_file.write(filename) response['Content-Disposition'] = 'attachment; zip_file' return response -
Django Rest Framework: while using generics APIview I'm not able to set permissions( permissions.py not working for individual users)
I want the admin user to access every user detail and the non-admin user to get access to its own detail only but I'm getting errors while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm not sure whether the problem is in permisions.py or models.py as I'm new to django. I'm using Postman for API testing and this is working fine for the admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS … -
How do you submit your sitemap with more than one model
I have 6 models in my app, it is necessary to provide all these models in the sitemap.py file, or i will just provided only one models in the sitemap.py file ? . Actually i don't know how this sitemap works, and this is my first time provided this sitemaps to Google search console, will you please shows me how do i submit these models to sitemap in django? my sitemap.py file: from django.contrib.sitemaps import Sitemap from .models import Category class CategorySitemap(Sitemap): def items(self): return Category.objects.all() my models: class Category(models.Model): name = models.CharField(max_length=100, blank=False, null=False) def get_absolute_url(self): return "/p/%i/" % self.id def __str__(self): return str(self.name) class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True, max_length=200) def __str__(self): return str(self.title) class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) class Notification(models.Model): is_read = models.BooleanField(default=False) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.ForeignKey(Answer, on_delete=models.CASCADE) def __str__(self): return str(self.user) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = CloudinaryField('image', blank=True, null=True, default='static/default.jpg') stories = RichTextField(blank=True, null=True) twitter = models.URLField(max_length=300, blank=True, null=True) website = … -
Using expressions inside tags
I'd like to capitalize a string variable and translate it at the same time, but i can't find how to do this in the api docs. i.e. this is throwing an error: {% trans {{ someString | capfirst }} %} -
Django Read Only Fields ,if there is any value
I wrote this code to make read only field, but i want to make an exception that if there is value then that row will only readonly , and if there is not any value the it will be editable, admin.py def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ("name", "id") return self.readonly_fields -
Django Rest Knox - 403 Forbidden CSRF verification failed
I am using Django Rest Knox for my login/logout views. however, when trying to use these views, I get the following error: Forbidden (403). CSRF verification failed. Request aborted. See an extract of my settings.py below: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'donations', "authentication", "knox", 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] if PRODUCTION: INSTALLED_APPS.insert(0, "whitenoise.runserver_nostatic") MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware") ROOT_URLCONF = 'system.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 = 'system.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases # Use PostgreSQL in production, otherwise SQLite DATABASES = ( { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": os.environ.get("DB_HOST"), "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASS"), } } if PRODUCTION else { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } ) if HEROKU: import dj_database_url db_url = os.environ.get("DATABASE_URL") db_from_env = dj_database_url.config( default=db_url, conn_max_age=500, ssl_require=True ) DATABASES["default"].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 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', }, ] # Custom user model AUTH_USER_MODEL = "authentication.User" # Django REST framework REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["knox.auth.TokenAuthentication"], "DEFAULT_PERMISSION_CLASSES": [ … -
django server not starting after configuring the project to run a sass file which I'm using to style my django app
I configured my django app named Eshop in my django project so that I can run the Sass file i have but after restarting the server in the terminal, it's bringing an error "ModuleNotFoundError: No module named 'Eshopcompressor'" I've looked through for the Eshopcompressor but its not there, what next? -
In Django, can I use context in redirect?
I am trying to use redirect with context but I get NoReverseMatch exception. Code snippet is as follows: return redirect(reverse('td:success', kwargs={ 'data': my_data })) However, when I use render, all goes well and I am able to access the context in the template. But I want redirect instead. enter image description here -
Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P<broadcastid>[0-9]+)\\Z']
I am getting following error: Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P[0-9]+)\Z'] Does anyone knows how to solve it? urls.py path('showuser/<int:broadcastid>', views.showuser, name="showuser") views.py def showuser(request, broadcastid): vrbrlstnm = BroadcastListSms.objects.get(id=broadcastid) showDepartment = AddContact.objects.values('dept_nm').distinct() if request.method == "GET": if request.GET.get('select') == "All": departmentData = AddContact.objects.all() else: departmentData = AddContact.objects.filter(dept_nm=request.GET.get('select')) return render(request, "showuser.html", {'adduser': vrbrlstnm, 'showDepartment': showDepartment, 'departmentData': departmentData}) return HttpResponseRedirect("showuser", {'showDepartment': showDepartment, 'departmentData': departmentData}) adduser.html <a href="{% url 'showuser' bid=adduser.id %}" class="btn btn-primary"> Add Existing User </a> Note: adduser.id is the foreign key value, from where we get broadcastid. I am stuck here from so many days. Not able to understand what to do now -
How to create authenticated by phone number django
i want to create authenticataion by phone number i don'i know to do it. I don't found any library for django, python. I have authentication by email and password: # models.py class User(AbstractUser): email = models.EmailField(_('email address'), blank=False,unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] How i can create authentication by phone number and verify code which send when user click the button ??? -
Django - Accessing static/media files from a remote url instead of local the one
I cannot find any answer to my question on the web so here it is with some context : I have a Django app running on a server and I would like to continue working on it locally with the "runserver" command. My problem concern the use of common static and media files. The media folder content changing frequently in production I have to download those media files from the server each time I want to dev locally and add those the MEDIA_ROOT path on my computer. The database is common to both dev and production environment since it is a MySQL host on my server. My question is simple, how can I tell Django in local mode to lookup static and media files on a remote url from my domain name instead of localhost ? Searching for media on : https://example.com/media/ instead of : https://127.0.0.1:8000/media/ Hoping this is possible without so much effort ! Thank you in advance for your help -
Refactoring: how to remove a model?
I have a model which is causing too much complexity, and so I want to do away with it and move to a simpler way of doing things. I don't immediately want to scrap the data in this database table, though. class PRSblock( models.Model): PRS = models.ForeignKey( 'jobs.PRS2', models.CASCADE, related_name='prs_blocks') # no other relational fields So, first, migrate the related name prs_blocks to obsolete_prs_blocks and then in the PRS model, add a @property prs_blocks that will assert that it is never called (to trap any bits of code which I failed to remove) Second, rename the model PRSblock to obsolete_PRSblock. IIRC Django makemigrations will ask whether I renamed it, and if I say yes, it will preserve the database table. Does this sound sensible or are there any gotchas I haven't though of? -
How can I add the following JSON to a new URL based on its "category": 2?
I have a JSON array in my server in Django rest framework, but I want to filter them by category , for example some of them have 'category':1 and some of them have 'category':2 like this: [ { "id": 667, "image": "https://ae0g", "description": "GRE", "price": "USD .11", "buy": "https://sn", "category": 1 }, { "image": "https://ae04.", "description": "10/13 ", "price": ".18", "buy": "https://", "category": 2 } ] How can I add the following JSON to a new URL based on its "category": 2? "image": "https://ae04.", "description": "10/13 ", "price": ".18", "buy": "https://", "category": 2 views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer pagination_class = None def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') urls: router = routers.DefaultRouter() router.register(r'product', productviewset,basename='product') # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('api/', include(router.urls)), -
VariableDoesNotExist at
I encountered a problem in django this the problem enter image description here this is my model enter image description here and this is my views.py enter image description here someone could help me? -
Django Template inclusion tags, supress trailing newline
Firstly I know about {% spaceless %}. I don't want to remove all spaces. I just would like the inclusion tag to only render the template, and not add its own trailing '\n' at it's own discretion. E.g. say I have the template tag: from django import template register = template.Library() @register.inclusion_tag(f'myemail/button.html') def myemail_button(href, title, color, background_color): return { 'href': href, 'title': title, 'color': color, 'background_color': background_color, } And this is the inclusion tag's template (myemail/button.html): <table><tbody><tr> <td style="background-color:{{ background_color }}; border-radius:5px; border:solid 1px {{ background_color }}; color:{{ color }}; padding:0px;"> <a href="{{ href }}" style="background-color:{{ background_color }}; border-radius:5px; border:solid 1px {{ background_color }}; color:{{ color }}; display:inline-block; font-weight:bold; padding:12px; text-align:center; text-decoration:none;" target="_blank">&nbsp; {{ title }} &nbsp;</a> </td> </tr></tbody></table> Then when one renders this template (there is no blank line at the start nor end of the file: {% load myemail %}{% myemail_button href="https://example.com" title="CLICK ME!" color="#123456" background_color="#abcdef" %} {% myemail_button href="https://example.com" title="CLICK ME!" color="#123456" background_color="#abcdef" %} It renders as (note the space between the two adjacent <table> elements (this is the new line I would not like auto inserted): <table><tbody><tr> <td style="background-color:#abcdef; border-radius:5px; border:solid 1px #abcdef; color:#123456; padding:0px;"> <a href="https://example.com" style="background-color:#abcdef; border-radius:5px; border:solid 1px #abcdef; color:#123456; display:inline-block; font-weight:bold; padding:12px; … -
Date defaults to Django webserver start date rather than to the default method parameter
I've stumbled on something unexpected, it is probably something basic I'm misunderstanding either in Python or Django. I have a static method in my model class to return the date provided by the user or alternatively return today's date: @staticmethod # By default return today's date or the date provided def get_start_date(**kwargs): startDate = kwargs.get('startDate', datetime.date.today()) return startDate I decided to rewrite it such that the method has the startDate as a default parameter. However, instead of defaulting to today's date it defaults to the date when the Django webserver was first started. Why would this be the case? The method is executed, I've confirmed that the startDate was not provided in the call, even when a variable which I know for certain isn't used anywhere else in the code is entered in the argument, it still returns the date Django was first ran. def get_start_date(startDate=datetime.date.today(), notUsed=datetime.date.today(), **kwargs): print(startDate, notUsed, datetime.date.today()) return startDate >>> 2022-06-23 2022-06-23 2022-06-24