Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get a history of user activities from an application made in django and persist it in postgresql
I am starting a development in Django, together with a legacy postgresql database and I want to record in a table the crud that each of the application users perform. Examples: user Diego logged in and saved a document; user Fernando logged in, canceled a document and then logged out, etc. I understand that in order to do what I need, first I must be able to register which user connects to the application, and then what operations it performs. Given the users already exist and I don't have them in the django admin, I can't think of how to do what I need. Other questions I have are: Which user connects to postgres, the one reported in the settings.py file? or the one who logs into the application? Eventually I can see in pgadmin all logged in users, so that I can see the open sessions? As you will see, there are some queries. I have read the Django and Postgresql documentation and neither mentions these aspects, perhaps more operational. Thanks a lot. -
Deploying telegram bot to Django Production server
Here are my bot.py scripts: import logging from telegram.ext import Updater, CommandHandler, MessageHandler, Filters # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. def start(update, context): update.message.reply_text("Start") def main(): updater = Updater(TOKEN, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) updater.start_polling() updater.idle() if __name__ == '__main__': main() I can run it locally by python bot.py However, I do not know how to deploy to django production server. how to make it work with view.py? do I have to create a view for it? Anyone can help?? -
Django app - Inject Docker environment variable into a JavaScript file?
I'm working on a Django app that is Dockerized. I implemented a 3rd party API in a JS file, making the call using Ajax and need to inject the API key into the url. I stored the API key in a .env file. I know using the API key on the server side I can just run a os.environ.get('API_KEY'). Now I've seen some previous posts that suggest calling the API in the Django view. But the call is being used in about 4 different places(address autofill api). I've seen some examples but most seem to use Webpack, or using Node for the backend. I'm really just trying to find the best, simple solution on how to inject a Docker environment variable into a JS script that will be rendered in the browser each time the api call is made. Is a custom shell script mandatory to be executed and thrown into the Dockerfile, or possibly a package that helps with this? Any help is greatly appreciated! -
Print the foreign key field in the serializer. Django rest
I have two models class Project(models.Model): name = models.CharField(max_length=16, verbose_name='название', blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) prototype = models.ForeignKey('Prototype', on_delete=models.CASCADE) colors = jsonfield.JSONField() class SharedProject(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='share_project') permission = jsonfield.JSONField() I want to make a request and display projects plus their rights class UserShareProjectsView(viewsets.ModelViewSet): serializer_class = OtherProjectSerializer queryset = SharedProject.objects.none() def list(self, request, *args, **kwargs): project = Project.objects.filter(Q(share_project__to_user=request.user.email) | Q(share_project__all_users=True)).all() serializer = self.get_serializer(project, many=True) for i in serializer.data: i['permissions'] = ????? return JsonResponse({"project": serializer.data}, status=status.HTTP_200_OK, safe=False) I would like to display them in one query. Without making a new request one every time to check the rights. How can permissions be displayed? -
Annotate query by existance in M2M
I have objects A and B with M2M between them. I have some queryset QS0 of A objects. Also, I have one exact instance of B object. How to annotate QS0 with True if B is connected with A through M2M and False if it is not? Thanks -
How can I use a 64-bit id in Django using Postgres as a backend?
I am trying to create a 64-bit id in Django (3.1), somewhat like this stackoverflow answer, and store it in Postgres (13.1). For reference, here is their proposed Django model: class MyClass(models.Model): id = models.BigIntegerField(default = fields.make_id, primary_key=True) with their make_id modified to return a 64-bit integer with the highest bit set: def make_id(): return 13528776667777991352 If I use this proposal, I get an error when trying instance.save(): django.db.utils.DataError: bigint out of range That seems correct to me. That number has the highest bit set: $ python -c "print(f'{13528776667777991352:>64b}')" 1011101110111111110111101011001101101000100000000000001010111000 It will be too large for a signed 64-bit int, but not too large for unsigned: $ python -c "print(13528776667777991352 > (2**63-1))" True $ python -c "print(13528776667777991352 < 2**64)" True Postgres docs say the range of bigint is -2**63 to 2**63-1. (The numbers in the docs are -9223372036854775808 to +9223372036854775807.) I am surprised that no one commented on that stackoverflow answer. Since time is shifted into the highest bit position, I feel like anyone would hit this right away. I may be missing something obvious. I've thought of a few options. Write a Django custom field (say "UnsignedBigIntegerField") that slides the number from [-2**63, 2**63-1] to [0, 2**64] by adding … -
How can I access a value from one model and pass to another model in Django?
I have one model called Weight (filled by User input/choice) and another called Enterprise. class Weight(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="weights") weight_of_history = models.IntegerField(null=True, blank=True) class Enterprise(models.Model): ... The weight is saved, one per user, and replaced everytime the user choose new one. Inside the Enterprise class, I am creating an property that must get the "weight_of_history" (depending on the user, who has chosen the weight) from Weight class, but the models have no Foreign key or related name between them. class Enterprise(models.Model): ... @property def ranking(self): weight_of_history = <-- HERE I NEED TO TAKE WEIGHT_HISTORY FROM THE FIRST MODEL THEN I COULD CALCULATE How could I do that? Thank you! -
django store field as a tuple of form (ManyToMany Existing Model, DateField Expiration Date)
Im building a database to manage locks. Essentially there will be a model Locks that describe locks on a door and users who have access to said locks. There will be Users who have identification info and locks they have access to. Many locks can have many users with access to them and many users can have access to many locks I want the Users Locks to have an optional expiration date. The obvious implementation that I would think would be to store locks owned by the users as a tuple of the form (locks, expiration) Im curious if this is the django way of doing things and if it is possible to store as a tuple. from django.db import models # Create your models here. # The first element in each tuple is the actual value to be set on the model, # and the second element is the human-readable name. LOCK_CHOICES = ( ('LOCKED', 'locked'), ('UNLOCKED', 'unlocked'), ('ERROR', 'error') ) # Locks: # # name = name of door, also name of lock # owners = list of tuples containing (user, accessdate) # disciption = a text field describing the lock # status = Unlocked, Locked, Error class … -
Constant pop-up of print screen on clicking a particular button
I am getting a print screen option on clicking a button. I made no changes to the js or HTML file of my webpage to change the onclick() behavior for the botton, I wrote some kind of a print command in the chrome debugger console and since then the pop-up is coming. I don't exactly remember the command. How do I undo this change? On pushing the code to GitHub, this behavior was repeated in the production environment. -
Which Exception should I throw when I receive a 400 response from an external API?
I'm writing a simple Django app that integrates with a third party API. It fetches some JSON from the third party and displays it in a basic web app. I'm using the OAuth2 Authorization code flow to authenticate with the authentication server. Any direct communication with the external API happens in functions that are separated from my views - so none of the views call the API directly. They instead will import and call these "service" functions as needed. As part of the Authorization code flow I need to use the refresh token to get a new access token to continue to fetch resources from the third party. Here is the function that refreshes the access token: import requests import environ ### Globals env = environ.Env() AUTH_URL = 'https://example.com/oauth/access_token.php' CLIENT_ID = env('CLIENT_ID') CLIENT_SECRET = env('CLIENT_SECRET') ... def refresh_access_token(refresh_token): """ uses refresh_token to request another access token returns the access token """ payload = { 'refresh_token': refresh_token, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'refresh_token', } response = requests.request('POST', AUTH_URL, data=payload) return response.json()['access_token'] Here's my question - and forgive me if I'm overthinking - but let's say that my refresh token has been revoked by the user. I'll get a 400 Bad Request … -
Django ForeignKey on_delete = SET_NULL not working
I'm writing tests for several object models and the following test isn't giving the expected result: def test_image_on_delete(self): image = Image(id=self.TEST_IMAGE_ID, name=self.TEST_IMAGE_NAME, src=self.TEST_IMAGE_SRC) image.save() category = Category.objects.get(id=self.TEST_ID) category.image = Image.objects.get(id=self.TEST_IMAGE_ID) Image.objects.get(id=self.TEST_IMAGE_ID).delete() self.assertIsNone(category.image) Here is the image field in Category: image = ForeignKey(Image, on_delete=SET_NULL, null=True) I've confirmed that the Image is being deleted, but the assertIsNone fails because the Category's image field doesn't get cleared. Is there something wrong with the way I've written this test or the ForeignKey field? Note: I'm using TestCase from django.test -
Search a list of comma separated strings on elasticsearch
I have elasticsearch configured for my django project. Elasticsearch index has two fields user_id and address, my goal is to search a list of comma separated addresses on elasticsearch. Example: i have this list of addresses ["abc", "def","ghi","jkl","mno"] and i want to search them on elasticsearch in one hit, the result i'm expecting for the above list is ["abc", "def","ghi"] if these three addresses "abc", "def" and "ghi" (individually) exist on elasticsearch in address field. -
Cannot use Redis as django channels channel layer backend
I am trying to use django_redis's RedisChannelLayer as django channels's channel layer backend. Which results in the websocket opening and closing instantly. But it work fine with In memory channel layer. django_redis: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } In Memory Channel Layer: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } Consumer: class MessageConsumer(AsyncWebsocketConsumer): def __init__(self): super().__init__() self.channel = None self.group_name = None async def connect(self): self.channel = await self.get_channel() self.group_name = f"group_{self.channel.id}" await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() -
Anotate queryset counting not related objects
I want to do something like this qs.annotate(referrals_qty=Subquery(User.objects.filter(host_username=OuterRef('username'))).count()) I tried many variations, therefore the example above is just to explain what I want. I need to count rows where the attribute 'host_username' equals the attribute 'username' of the current row and annotate the current row with the result of Count. (obviously, it returns error 'Subquery' object has no attribute 'count') Thanks -
How to dynamically add custom class variables without a constructor in Python
How can class variables be dynamically be added to a Python class without calling its constructor? This is required when adding custom query fields in a custom Django Graphene Relay Node filter. In the example code below, the is_controller class variable is defined statically. How can the name of the variable and the parameters for the BooleanFilter be dynamically generated without using a constructor or code outside the class? This is needed to run GraphQL queries such as allSiteEntities(is_controller: true) { ... } class SiteEntityFilter(FilterSet): """Filter for SiteEntityNode that includes component filters""" is_controller = BooleanFilter( field_name=controller_component, lookup_expr="isnull", exclude=True ) class Meta: model = SiteEntity fields = { "site": ["exact"], "name": ["exact", "icontains", "istartswith"], "modified_at": ["exact", "gt", "lt"], } class SiteEntityNode(DjangoObjectType): class Meta: model = SiteEntity filterset_class = SiteEntityFilter fields = [ "id", "site", "name", "controller_component", "created_at", "modified_at", ] interfaces = (relay.Node,) -
Why _thread doesnt work on the remote server?
This code works on my local server, but doesnt work on the hosting. What could be the problem? import _thread def email_index(*args): server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('ki@gmail.com', 'pas') try: server.sendmail('ki@gmail.com', 'so@gmail.com', body_mes.encode('utf-8')) print('ok') except: print('An error occurred when trying to send an email') try: _thread.start_new_thread( email_index, ("Thread-1", 2, ) ) except: print ("Error: unable to start thread") -
Django REST and React - JWT Cookie not getting set in browser but working with postman
Hey guys I am stuck trying to solve the issue with django set_cookie, I can't find the cookie in the browser and it doesn't work but works with postman. I went through some of the SO answers and found that I had to provide withCredentials:true in the frontend and I have done that, but still it doesn't work. This is the code I have, can someone tell me the error in this? I want to have the cookies set at login, as of now I am storing the token in local storage and I came to know it is not a safe option. def post(self, request, format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) csrf.get_token(request) response.data = {"Response": "Login Successful", "data":data,} return response else: return Response({"error": "User is not active"}, status=status.HTTP_404_NOT_FOUND) else: return Response({"error": "Invalid credentials"}, status=status.HTTP_404_NOT_FOUND) react front-end const handleSubmit = (e) => { e.preventDefault(); axiosInstance .post(url, { username: formData.username, password: formData.password, }) // .then((res) => { // … -
Issue with Django Static Files 3.1
Django is looking for my static files in the wrong place and I dont understand why Not Found: /account/login/style.css [26/Feb/2021 19:27:16] "GET /account/login/style.css HTTP/1.1" 404 2434 but my file should be in /static/css/style.css This is the code in my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] I use staticfiles folder to place my static files afterwards I do py src\manage.py collectstatic to transfer my files in static folder This is my layout of the project: In my template I am using {% load static %} and I try to load the style.css with {% static 'css/style.css' %} Here is the urls.py in core: from django.contrib import admin from django.urls import path, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('accounts.urls', namespace='accounts')), ] if settings.DEBUG: # test mode from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py in accounts: app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="registration/login.html", authentication_form=UserLoginForm), name='login'), ] Login page is the one that I have the problem with http://127.0.0.1:8000/account/login/ DEBUG is true in settings Do you have any idea what could be the problem? -
How to join two related models in one serializer in django
I was trying to create an API for the Product model in which I want to include multiple images for a single product but don't want to use ManytoMany relation as I want Admin to add separate Images for all products but I am stuck at this point that how can I create a serializer for the same so that I can get expected JSON output from that. my models code and expected JSON is given below. Thanks in advance! MODELS: class Product(models.Model): title = models.CharField(blank=True,null=False,max_length=100) class ProductImage(models.Model): product = models.ForeignKey(to='products.Product', on_delete=models.CASCADE, default=None) image = models.ImageField(upload_to='images/product_inmages', null=False, blank=False) def __str__(self): return self.product.title EXPECTED RESULT FROM PRODUCT SERIALIZER: [ { title:"title 1", product_images:[ "media/image1.png", "media/image2.png", "media/image3.png" ] }, { title:"title 2", product_images:[ "media/image4.png", "media/image5.png", "media/image6.png" ] } ] -
How to create a Django reverse url with a parameter
I am having problems constructing a reverse url with a parameter I have tried the answers to this question but with no luck urls.py urlpatterns = [ path('publication-item/<str:publication_title>', PublicationItemView.as_view(), name='publication-item'), ] xxx.html <a href="{% url 'publication-item {{ publication.publication_title | urlencode }}' %}"> gives the error Reverse for 'publication-item {{ publication.publication_title | urlencode }}' not found. 'publication-item {{ publication.publication_title | urlencode }}' is not a valid view function or pattern name. Whereas xxx.html <a href="{% url 'publication-item' %}?publication_title={{ publication.publication_title | urlencode }}"> produces Reverse for 'publication-item' with no arguments not found. 1 pattern(s) tried: ['publicationspublication\-item/(?P<publication_title>[^/]+)$'] The following works, but of course it doesn't pass the parameter urls.py urlpatterns = [ path('publication-item', PublicationItemView.as_view(), name='publication-item'), ] xxx.html <a href="{% url 'publication-item' %}" class="btn btn-primary"> Where am I going wrong? -
Show/hide a table row based on nested class
I have a button on a page that I want to only show rows that have a certain class (target-class in my example) within them. If you press the button again, then all rows are shown. I'm not sure how to check if target-class is within <tr class="show-hide-this-one"> <button id="btn-toggle_target" type="button">Show Targets Only</button> <table> <tbody> {% for item in first_list %} <tr class="show-hide-this-one"> <td> {{ item.title }} </td> <td> <table><tbody> {% for subitem in item.sublist %} <tr> <td> {{ subitem.value }} {% if value == 0 %} <span class="target-class"> Looking for this one </span> {% endif %} </td> </tr> {% endfor %} </tbody></table> </td> </tr> {% endfor %} </tbody> </table> <script type="text/javascript"> function toggleTarget() { $btnToggle = $("#btn-toggle_target") var showTargetOnly = $btnToggle.hasClass("target-only") if (showTargetOnly) { $btnToggle.html("Show Targets Only").removeClass("target-only"); $().show(); } else { $btnToggle.html("Show All Records").addClass("target-only"); $().hide(); } } (function () { $("#btn-toggle_target").on('click', function() { toggleTarget(); }); }()); </script> -
Call django view from another template
I would like to display view rendered content on another template part, for example, i have a django class base list and detail view, detail view are prepared to render same content on differents html templates as preview.html or extended.html, so on this way could reuse preview detail view on list view. The essence and idea is same as {% include 'some.html' %} but passing content. Could i approach this situation from ?: django templatetag: @register.simple_tag def call_view(): return app_views.GenericListView.as_view(model=app_models.Company, template='preview.html') ajax call: var content = $.get... $('#element_id').html(content); Anybody could help me please? Thanks in advance. -
how to return a calculation in django rest framework and let a user filter it
hi i think i asked a similar question before which was to print it but i wasn't able to get any answer which worked. So how do i show a calculation and filter it, here is my code below of which i am getting a users co-ordinates and i am getting the list of sellers co-ordinates and then putting them into this calculation below def calc_distance(self, lat_a, long_a, lat_b, long_b): EARTH_RADIUS_IN_MILES = 3958.761 """all angles in degrees, result in miles""" lat_ab = radians(lat_a) lat_b = radians(lat_b) delta_long = radians(long_a - long_b) cos_x = ( sin(lat_ab) * sin(lat_b) + cos(lat_ab) * cos(lat_b) * cos(delta_long) ) return acos(cos_x) * EARTH_RADIUS_IN_MILES then i want to return all the sellers with the distance of each one. And if possible let the user filter the distance here is my code so far def calc_distance(self, lat_a, long_a, lat_b, long_b): EARTH_RADIUS_IN_MILES = 3958.761 """all angles in degrees, result in miles""" lat_ab = radians(lat_a) lat_b = radians(lat_b) delta_long = radians(long_a - long_b) cos_x = ( sin(lat_ab) * sin(lat_b) + cos(lat_ab) * cos(lat_b) * cos(delta_long) ) return acos(cos_x) * EARTH_RADIUS_IN_MILES class Listsellers(generics.ListAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication] queryset = Seller_account.objects.all() serializer_class = SellerAccountSerializer filter_backends = [DjangoFilterBackend] def calc_distance(self, lat_a, long_a, … -
how can I get the sum of all expense based on current logged user in django?
I am using to sum all the expense values which are assigned to an user. I am not able to display it in my webpage. How can i do that? The models.py code is as follows: class expense(models.Model): Expensecat=(('food','Food'), ('transportation','Transportation'), ('education','Education'), ('health','Health'), ('clothes','Clothes'), ('beauty','Beauty'), ('hosuehold','Household'), ) ExpenseAmount=models.FloatField(max_length=100) Category=models.CharField(max_length=200,choices= Expensecat) Description=models.TextField(max_length=200) Date=models.DateTimeField(default=timezone.now) user=models.ForeignKey(User,on_delete=models.CASCADE) Views.py def home(request): try: expense_total = expense.objects.filter(user=request.user).aggregate(expenses=Sum('ExpenseAmount')) except TypeError: print('No data') data = { 'Expense':expense_total['expenses'], } return render(request, 'budget/home.html', data ) HTML CODE: <div class="col-lg-3 col-md-6 d-flex stat my-3"> <div class="mx-auto"> <h6 class="text-muted">Expense</h6> <h3 class="font-weight-bold">{{ Expense.expenses }}</h3> <h6 class="text-success"></h6> </div> -
Django - apps.py not recognized
Django version 1.11.7 Trying to execute signals.py for a post_save execution my code works if i put it in my models.py file but i want to separate my signals from my models in app_1 but seems that even my apps.py isn't executed. The project structure my_project ├──docs ├──src │ ├── __init__.py │ ├── apps │ │ ├── app_1 │ │ │ ├── __init__.py │ │ │ ├── admin.py │ │ │ ├── apps.py │ │ │ ├── constants.py │ │ │ ├── forms.py │ │ │ ├── managers.py │ │ │ ├── migrations │ │ │ ├── models.py │ │ │ ├── signals.py │ │ │ ├── tests.py │ │ │ ├── urls.py │ │ │ ├── utils.py │ │ │ └── views.py │ │ ├── ... │ │ └── app_x │ ├── fabfile.py │ ├── manage.py │ ├── media │ │ └── files │ ├── requirements.txt │ ├── settings.py │ ├── static │ │ ├── file_1.html │ │ ├── ... │ │ └── file_x.html │ ├── templates │ │ ├── app_1 │ │ ├── .... │ │ └── app_x │ ├── urls.py │ └── wsgi.py apps.py from django.apps import AppConfig class AppOneConfig(AppConfig): name = 'app_1' def ready(self): print("test") from …