Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to integrate Ireport with Django App (python)?
I'm currently developing a Django App (python) and i want to use iReport with my app, are there any other python library or something to fix this problem ? -
How can I customize self.ordering of ListVIew
I have ListMyView which has override ListView, it It has the get_ordering function. I can set the ordering key as sort_by class ListMyView(ListView): model = TestUserGroup def get_ordering(self): return self.request.GET.get("sort_by", self.ordering) in model class TestUserGroup(BaseModel): name = m.CharField() test_users = m.ManyToManyField(TestUser) def get_current_users(self): return self.test_users.all() In this case I can use key name as sort_by, however when using get_current_users as sort_by show this error. Cannot resolve keyword 'get_current_users' into field. Choices are: created_at, created_by, name, id Is there any way to use get_current_users() as sorting key? -
Django: How to access database item from custom template tag
I am trying to register a simple template tag that will return the percentage of a value by dividing the value within the template by a value stored in the database (total cost), currently I have the following template tag: @register.filter() def percentage(value): total_cost = Project.total_cost return value / total_cost * 100 in this case, 'Project' is the field name defined in the project. However, how does Django know which 'total cost' is the relevant one? Is this the best way to go about solving this issue? -
DJANGO 'int' object has no attribute '_meta'
I have been trying to update and add + 1 in the database model (sessions) field whenever a button is being clicked. I am trying to be able to add +1 in a database field whenever a user clicks on a button and have that +1 record and time when the button was clicked in an HTML table, Thank You All, Much Appreciate Views.py @admin_only @api_view(['POST']) def swimmersUpdate(request, pk): swimmers = Swimmers.objects.get(id=pk) cs = swimmers.sessions swimmers.sessions = cs + 1 serializer = SubSerializer(instance=cs, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py class SubSerializer(serializers.ModelSerializer): class Meta: model = Swimmers fields ='__all__' Urls.py path('apiurls/', views.apiurls, name='apiurls'), path('swimmers-list/', views.swimmersList, name='swimmers-list'), path('swimmers-details/<int:pk>', views.swimmersDetails, name='swimmers-details'), path('swimmers-create/', views.swimmersCreate, name='swimmers-create'), path('swimmers-update/<int:pk>', views.swimmersUpdate, name='swimmers-update'), path('swimmers-delete/<int:pk>', views.swimmersDelete, name='swimmers-delete'), Models.py class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.CharField(max_length=200, blank=True ) dateofpayment = models.CharField(max_length=200, blank=True) phone = models.CharField(max_length=30, blank=False, null=True) date_from = models.DateField(null=True) date_to = models.DateField(null=True) type_choice = ( ("basic", "Basic"), ("3x1 week", "3x1 Week"), ("1 session", "1 Session"), ("2x1", "2x1"), ) type = models.CharField(max_length=200, blank=False, null=True, choices=type_choice, default=type_choice) ammount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=True) registration = models.DateField(default=timezone.now) keenphone = models.CharField(max_length=30, blank=False, null=True) def __str__(self): … -
which mysql client is good for db connection in django [closed]
I have been using mysqlclient package for MySQL DB connection in Django and recently realized mysqlclient is in GPL license. Is it fine to use mysqlclient package in a private repo for a commercial product? What I understand is that it's fine to use LGPL libraries while GPL one is not. I asked the package maintainer about this and he replied to check it on StackOverflow. :) I am curious what MySQL client other developers use for commercial applications. -
How can I add a ingredient to a list of ingredients before database in python Django
I am try to make a recipe card.. but want to be able to add many ingredients to it before it goes to database. I am not sure how many will be added.. is there a way to do this in Django?? -
Django / File not found when adding a new app
I have 2 apps. I have added a third one called Verge3D Main urls.py path('verge3D/',include('verge3D.urls')), In my urls.py / Verge3D app : urlpatterns = [ path('home3D',views.myFirst3D,name="home3D"), ] In my views.py / Verge 3D app def myFirst3D(request): return render(request,'3Dfiles/earth.html') The problem is : Django searches this 3Dfiles/earth.html still in my first app location (it works when I create this directory/files in my fist app Templates directory) Strangely I don't have this problem with app n°2 -
What would be best if i want to relate one table to few others? (Django models example)
Existed models: class OrderDocument(models.Model): name = models.CharField(max_length=100) file = models.FileField(upload_to=get_document_name) order_group = models.ForeignKey(OrderGroup, on_delete=models.CASCADE, null=True, related_name='documents') class Order(models.Model): name = models.CharField(max_length=100) class OrderGroup(models.Model): name = models.CharField(max_length=100) I want to rewrite it for add ability to add OrderDocuments and choose with what table (Order or OrderGroup) it will related. Which way will the best in this case to implement it? It can be more than 2 relations in future. I don't want using m2m in Order and OrderGroup -
Django get new table entry and create new table if the column value is unique
I am currently studying django and trying to create a backend to manage IOT devices and show their status on a webpage and looking for some guidance / best practice methods. I have N devices each has unique device_id. They are transmitting periodically and mySQL table is updated with some values and the device_id in the first column. I want to create some kind of a sorting mechanism that checks the main table for new entries every minute (or every new row entry) so I used django-celery-beat to create a scheduled job. Now, I want to create a new table if a new device_id has arrived to that column with device_id as the table's name (only if the table name does not exist already) and the table type the will be chosen by sensor_type column value. Is that possible with django? using scheduled tasks is the right way? I think that by checking the table every 1 minute I can miss entries, how can I make sure every entry is checked? Thanks. -
How to run Django selenium test in github actions
I have a Django selenium test that runs fine on local machine using Firefox Webdrive. When I try to run it on github actions I get following error: Traceback (most recent call last): File "/home/runner/work/Pangea/Pangea/core/tests/test_selenium.py", line 12, in setUpClass cls.selenium = WebDriver() File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/selenium/webdriver/firefox/webdriver.py", line 181, in __init__ RemoteWebDriver.__init__( File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 269, in __init__ self.start_session(capabilities, browser_profile) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 425, in execute self.error_handler.check_response(response) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status 1 The test that I am trying to run is very basic as shown below from django.contrib.staticfiles.testing import StaticLiveServerTestCase from rest_framework.reverse import reverse from selenium.webdriver.common.by import By from selenium.webdriver.firefox.webdriver import WebDriver class TestLoginWithSelenium(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.maximize_window() cls.username = "xyz" cls.password = "mnbvcxza" cls.server_url = 'http://127.0.0.1:8000' @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): """ Test Login for a user """ self.assertTrue(1==1) I am running following commands on Github Actions: pip install selenium sudo apt install firefox-geckodriver which geckodriver geckodriver -V sudo mv /usr/bin/geckodriver /usr/local/bin/geckodriver which geckodriver Mozilla Firefox 99.0 geckodriver 0.30.0 -
Injecting js variable in django url
My url looks like this : path('tree_sensor\/(?P<sensorID>.*)', views.tree_sensor, name='tree_sensor') and i have a var sID = 1,2,etc which i want to inject into a django url in a button <a class='popup_button small_text' href='{% url 'agriculture:tree_sensor' "sID" %}'><span>Sensor Page</span></a>") Current url prints "tree_sensor/sID" . I want to get the ID from the objects so it would be something like "tree_sensor/1" "tree_sensor/2" etc. -
How to reset auto increment number every year in Django
I have a model IncomingCorrespondence with auto incrementing field ID. I also have field number, and I want two things for this field: This field will auto-increment its value, just like ID Every new year its value will start over from 0 (or 1) ID Number Date … … … 285 285 2020-03-12 286 286 2020-04-19 287 1 2021-01-01 class IncomingCorrespondence(models.Model): ID = models.models.AutoField(primary_key=True) date = models.DateField(null=True) number = models.IntegerField(null=True) How can I do that the most efficient and reliable way? -
How to upload root directory with sub-directories in django python?
How to upload the entire folder with contain sub-directories using django rest framework. Thanks in advance -
InvalidTextRepresentation: Invalid input syntax for type bigint:"All Forms"
I had a field in my model with book_classes = (("","Select Form"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4'),("All Forms","All Forms")) b_classes = models.CharField('Form',max_length=9,choices=book_classes,default="n/a") And then changed it to b_class =models.ForeignKey(ClassBooks,on_delete=models.CASCADE) Where class ClassBooks(models.Model): name = models.CharField(max_length=10,help_text='The class the book belongs to') I'm now stuck because when I try to migrate I get an error. Invalid input syntax for type bigint:"All Forms" What do I need to do, please? -
AWS CloudWatch Log Group Not Created through Django Logging
I have a Django application in which I am trying to do logging on to AWS CloudWatch. I have added the following code in my settings.py file: CLOUDWATCH_LOGS_BOTO3_CLIENT = boto3.client('logs', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION_NAME ) AWS_LOG_GROUP = 'MyLogGroup' AWS_LOG_STREAM = 'Mystream' AWS_LOGGER_NAME = 'watchtower-logger' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'aws': { 'format': u"%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'watchtower': { 'level': 'DEBUG', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_client': CLOUDWATCH_LOGS_BOTO3_CLIENT, 'log_group': AWS_LOG_GROUP, 'stream_name': AWS_LOG_STREAM, 'formatter': 'aws', }, }, 'loggers': { AWS_LOGGER_NAME: { 'level': 'DEBUG', 'handlers': ['watchtower'], 'propagate': False, }, }, } For logging, I am using the following code in my views: import logging from django.conf import settings logger = logging.getLogger(settings.AWS_LOGGER_NAME) logger.error("this is error message") The user whose access/secret key I am using, has full access to cloudwatch logs but log group and log stream is not created in cloudwatch. And there is no error thrown as well. Per my understanding, the above code will create the log group and log stream in cloud watch if not already created. -
django + htmx doesnt work inside the form
Hi i want to use htmx inside my form and send data to my data Base and same time add the information of the form inside a table under it, not actually a table but a made up table with divs and css tyles, i tried to add htmx tags inside a form but it send data to my data base but it doesnt add it at same time to the table under it and i have to refresh the page to see it, its the same while i delete or mark the job as done, i itried the way i put my codes under, but the css messed up and i cant manage the style of css if i add a div inside the form and then add the htmx tags inside the div, the style mess up bad so i need you guys to help me if there is another way. this is the view i send all of the data base to the table under the form def todo_subjets_list(request): course = request.GET.get("todo_subjets") modules = Todo_subject.objects.filter(subject=course) context = {"modules": modules} print(context) return render(request, "second_todo/todo_modules.html", context) and this is the view func, that i add the form with this … -
Django recaptcha validation
I want to send user that has been detected as a robot to a page and if the validation response was ok I would send him to another url but I don't know how to validate the recaptcha, I have read the documents but it wasn't clear enough. So any help would be highly appreciated. views.py @csrf_exempt def ref_link(request, seller_id): seller = Seller(request) result = seller.ref_link(seller_id, request.GET.get('url', 0)) response = JsonResponse({'result':result} ,safe=False , status=200) # response = redirect(result) # response['Access-Control-Allow-Origin'] = '*' # return response #************* VALIDATION PART ***************** #recaptcha_response = request.GET.get('g-recaptcha-response') #url = 'https://www.google.com/recaptcha/api/siteverify' #values = { # 'secret': "", # 'response': recaptcha_response #} #data = urllib.parse.urlencode(values).encode() #req = urllib.request.Request(url, data=data) #captcha_response = urllib.request.urlopen(req) #captcha_result = json.loads(captcha_response.read().decode()) #if captcha_result['success']: # response = redirect(result[1]) # response['Access-Control-Allow-Origin'] = '*' # return response #else: # print('None') # #if len(result) > 1: # if result[0] == False: # response = render(request, 'captcha.html') # response['Access-Control-Allow-Origin'] = '*' # return response response = redirect(result) response['Access-Control-Allow-Origin'] = '*' return response captcha.html <!DOCTYPE html> <html> <head> <title> im not a robot </title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <meta charSet="utf-8" /> <meta httpEquiv="content-language" content="fa" /> <meta name="language" content="fa" /> <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" /> </head> <body> <div > <form … -
How to filter in a table column contains list in django
I have a table column A=['1','2','3'] and I want filter from the table if the filter value is exist in the list. eg: id='1' Models.objects.filter(A=id) -
In django how In can pass data through URL?
I want to pass the model's id through the URL. I have created a path and view according. Still, I am getting error as ' NoReverseMatch at /url '. Here's the code that I used in Project. In Template : <a href="{% url 'url_name' model.id %}"> In view.py : def view_name(request, id): In urls.py: path('url_name/<int:id>', view_name, name='url_name') -
Django ORM filter by a list and then get the last created item
How to write the most efficient Django ORM query for the following scenario? I need to get items based on a list of accountIds, but it will return duplicate records with the same accountId because accountId is not the primary key. Then I will need to remove the duplicates by only returning the last created record in the queryset. I can use a for loop to loop through the list of accountIds and filter by each accountId and then order by the created date and get the latest one. However, with this approach, I will be calling the database so many times. There are more than 200 account Ids. Are there better ways of doing this? -
Django google recaptcha validation in a template without form
I want to stop click fraud on my website with redirecting user to recaptcha page but the problem is I can't put my validation code in views.py because I'm returning the rendered page so how I can get the response from captcha and then validate the response. robot_detection.py: def ref(result): if(result == True): return escape(external_url) if(result == False): return [False, external_url] if(result == 0): return "product not found" views.py: @csrf_exempt def robot(request, seller_id): seller = Seller(request) result = seller.ref(seller_id, request.GET.get('url', 0)) response = JsonResponse({'result':result} ,safe=False , status=200) if len(result) > 1: if result[0] == False: response = render(request, 'captcha.html') response['Access-Control-Allow-Origin'] = '*' return response response = redirect(result) response['Access-Control-Allow-Origin'] = '*' return response captcha.html <!DOCTYPE html> <html> <head> <title> im not a robot </title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <meta charSet="utf-8" /> <meta httpEquiv="content-language" content="fa" /> <meta name="language" content="fa" /> <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" /> </head> <body> <div > <form method="post"> {% csrf_token %} {{ form.as_p }} <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script> <div id='sub' class="g-recaptcha" data-sitekey="" ></div> </form> </div> </body> </html> captcha validation code: recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': "", 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) captcha_response = urllib.request.urlopen(req) captcha_result = json.loads(captcha_response.read().decode()) if captcha_result['success']: response = … -
Append an object to a list with django GenericViewSet
I wrote a many-to-many field for my model but when I try to write an updated view with generic-view-set don't append the new obj just replace it,how can I write to append the new obj to list, my model: class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='portfolio_assets') def __str__(self): return self.name Serializer class PortfolioUpdateSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ['id', 'name'] View class PortfolioAssetsUpdate(mixins.UpdateModelMixin, viewsets.GenericViewSet ): queryset = Portfolio.objects.all() serializer_class = PortfolioAssetsUpdateSerializer def put(self, request, pk): return self.update(request, pk) Now my problem is when I update my portfolio, a new object replaces to old one, I need to append new to old,I really don't have any idea -
Value of a cell equal to value in another table in Django & Sqlite
I have two tables - Goal & Plan. Plan table has a column "Year". Goal table also has a column "Year". I want value of Goal table's year to be equal to Plan table's year by default. Plan and Goal have 1 to many relationship. As you can see, in the second row of Goal table, the value of "Year" field is set manually while value of first row should be default and it should be 2022 because the plan Id 13's year field value is 2022. Also, when I change the Plan Id 13's year from 2022 to - say 2024 - it should propagate into Goal table too. Is it achievable at all in database or I need to handle it in application layer? -
Save object with a name instead of a class name in Django database
I have a strange problem. check the image here. You can see in the registration table it save each entity with the name 'Registration Object' not with the username. What I want is this. THe code is here models.py from django.db import models # Create your models here. class Registeration(models.Model): name = models.CharField(max_length=200, null=False, blank=False) email = models.EmailField(max_length = 254,null=False, blank=False) department = models.TextField(max_length=200, null=False, blank=False) password=models.TextField(max_length=60) def _str_(self): return self.email -
How to add an extra dictionary to ModelViewset response?
using the model class Sim(modesl.Model): iccid = models.CharField(max_length=64) carrier = models.CharField(max_length=50) status = models.CharField(max_length=100) class Meta(object): app_label = "app" verbose_name = "Sim" class JSONAPIMeta: resource_name = "sim" external_field = "id" using the view : class SimView(viewsets.ModelViewSet): queryset = Sim.objects.all() serializer_class = SimSerializer using serializer: class SimSerializer(serializers.ModelSerializer): class Meta: model = Sim fields = "__all__" for /get/ { "links": { "first": "some link", "last": "some link" "next": null, "prev": null }, "data": [ { "type": "sim", "id": "1", "attributes": { "carrier": "Vodaphone", "iccid": "12345678912345678912", "status": "UnManaged", } } ], "meta": { "pagination": { "count": 1, "limit": 20, "offset": 0 } } } Now I want a dictionary "license_info" to be sent in the response which should appear only once in response, so the response may look like: { "links": { "first": "some link", "last": "some link" "next": null, "prev": null }, "data": [ { "type": "sim", "id": "1", "attributes": { "carrier": "Vodaphone", "iccid": "12345678912345678912", "status": "UnManaged", } } #Either add here { "license_info":"some value" } ], "meta": { "pagination": { "count": 1, "limit": 20, "offset": 0 } } #Or Add here "license_info":{ "some key value pairs" } } I tried to make license_info as property but this was getting repeated for …