Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run Django admin site on Android
This is what am facing with with Django on my Android I'm using Pydroid on my phone. Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occurred. Contact administrator" and in the terminal it shows this error: storage/emulated/0/mysite $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 28, 2022 - 16:28:28 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C. [28/Apr/2022 16:28:45] "GET /admin/ HTTP/1.1" 302 0 [28/Apr/2022 16:28:55] "GET /admin/ HTTP/1.1" 302 0 Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/zoneinfo/_common.py", line 12, in load_tzdata return importlib.resources.open_binary(package_name, resource_name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 88, in open_binary package = _get_package(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 49, in _get_package module = _resolve(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 40, in _resolve return import_module(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line … -
Can't aggregate a DecimalField in Django
I have a queryset where I want to aggregate the fields amount which itself is a DecimalField. The target field is also a DecimalField. I get this error: django.core.exceptions.ValidationError: ["“{'amount__sum': Decimal('3821.02000000000')}” value must be a decimal number."] Why does it say it must be a decimal number even though it is a DecimalField? # models.py class Payment(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created amount = models.DecimalField(decimal_places=2, max_digits=10) class Payroll(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() def test(): ... # Loop the companies for company in qs_companies: # Query all Payments of that company in that month qs_payments = Payment.objects.filter(offer__company=company).filter(month=period) # Create a payroll run instance payroll_run = Payroll.objects.create( company=company, month=next_payroll_run, amount=qs_payments.aggregate(Sum('amount')), line_items=qs_payments.count() ) payroll_run.save() ... -
How to have sequent numbers in django model
I have a model that represents a book and a model named chapter. models.py class Book(models.Model): title = models.CharField(max_length=255) book_summary = models.TextField() author = models.ForeignKey(Author, related_name='books', on_delete=models.DO_NOTHING) upload_date = models.DateField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='books', blank=True) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.PROTECT,) def __str__(self): return self.title class Chapter(models.Model): book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) chapter_num = # has to be consecutive text = models.TextField() I want to number each chapter so that I can order them. But I cannot implement that with AutoField because if I delete a chapter there will be 1, 3 ,4... and so on. How can I do this? -
Django DateField clashes with datetime.date instance: AttributeError: 'Period' object has no attribute 'strftime'
When I try to create a new model instance within a function I get the following error: TypeError: fromisoformat: argument must be str My first guess was the format of the date object but I pass a valid date object which also is the Django DateField format? # utils.py def create_payroll_run(): # Query all active companies qs_companies = Company.objects.filter(is_active=True) # Get the 1st of the month for the payroll run to be created next_payroll_run = date.today().replace(day=1) # Get the period instance period = Period.objects.get(period=next_payroll_run) # Loop the companies for company in qs_companies: # Query all Payments of that company in that month qs_payments = Payment.objects.filter(offer__company=company).filter(month=period) print(qs_payments) # Create a payroll run instance payroll_run = Payroll.objects.create( company=company, month=period, amount=qs_payments.aggregate(Sum('amount')), line_items=qs_payments.count() ) payroll_run.save() return payroll_run # Models.py class Payroll(models.Model): """ A table to store monthly payroll run information of companies """ # Relates to one company company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() class Period(models.Model): """ A table to store all periods, one period equals a specific month """ period = models.DateField() Full Traceback: import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend(['/Users/jonas/Desktop/salaryx_django', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev']) if 'setup' in … -
How to read PSQL "explain" to improve Django query
I have a query in Django that ends up pulling about 3000 rows which are joined to another table. I've refactored as much of the query as possible to reduce joins, but I am trying to eek out additional performance from indexing. My initial (fumbling) attempts have improved things a little, but I'm butting up against the extent of my knowledge for database management. Thoughts on improving performance? Here's the explain: Sort Key: assets_deliverables.id -> Nested Loop (cost=0.43..34.15 rows=8 width=1212) -> Seq Scan on localization_language (cost=0.00..1.70 rows=1 width=89) Filter: (id = 1) -> Nested Loop (cost=0.43..32.37 rows=8 width=1123) -> Nested Loop (cost=0.29..31.10 rows=8 width=216) -> Seq Scan on assets_nodes (cost=0.00..9.31 rows=1 width=153) Filter: (upper((code_path)::text) ~~ '/WATCH%'::text) -> Index Scan using assets_deli_node_id_6e3b6b_idx on assets_deliverables (cost=0.29..21.78 rows=1 width=63) Index Cond: ((node_id = assets_nodes.id) AND (language_id = 1)) Filter: (((kind_id = 15) OR (kind_id = 19) OR (kind_id = 11) OR (kind_id = 24) OR (kind_id = 27) OR (kind_id = 34) OR (kind_id = 24) OR (kind_id = 17) OR (kind_id = 16) OR (kind_id = 34) OR (kind_id = 19) OR (kind_id = 11) OR (kind_id = 27) OR (kind_id = 15) OR (kind_id = 34) OR (kind_id = 13) OR … -
Django rest framework jwt {"detail": "You do not have permission to perform this action."}
I am trying to make a request using django-rest-framework and django-rest-framework-jwt but The response that I get detail": "You do not have permission to perform this action." views.py class Test(generics.RetrieveAPIView): permission_classes = [IsAuthenticated] authentication_classes = [] queryset = User.objects.all() def get(self, request): return response.Response({"test": "Test "}, status=status.HTTP_200_OK) urls.py from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token from .views import Test urlpatterns = [ path('', Test.as_view(), name='test'), path('token/', obtain_jwt_token, name='token_obtain_pair'), path('token/refresh/', refresh_jwt_token, name='token_refresh'), ] settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': timedelta(days=5), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } and the request that I made: >curl -X GET http://127.0.0.1:8000/users/ -H 'Authorization: Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMCwidXNlcm5hbWUiOiJoYXNhbm1iaWxhbDE5OThAZ21haWwuY29tIiwiZXhwIjoxNjUxNTkxMDYxLCJlbWFpbCI6Imhhc2FubWJpbGFsMTk5OEBnbWFpbC5jb20iLCJvcmlnX2lhdCI6MTY1MTE1OTA2MX0.bvmtH6mnItBjwKkvaNU5eMXlEyk2ZAytMWzhEE_Ibhs' Note: I've used django-rest-framework-simplejwt and got the same problem... -
Failing to deploy a Django web app to AWS beanstalk
I am trying to deploy A django app to beanstalk and I get some errors related to python and requirements.txt and I can't figure out what to do, Any help is appreciated. here are the errors I get: (the logs are in pastebin bellow) ERROR [Instance: i-0e7826c4558b1d21a] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2022-04-28 15:13:52 UTC+0000 ERROR Your requirements.txt is invalid. Snapshot your logs for details. logs: https://pastebin.com/g1uZLqur -
Struggeling with Twilio login - sms auth in Django
So I built a login with sms verification which works fine. The problem is that It's not possible to enter 14 digits (includes "+" symbol) in my admin user-settings. The following error applies when I try to save the user-settings in my admin-console: (1406, "Data too long for column 'phone_number' at row 1") So I tried to upset the max_lenght of (my phone number) to 20 instead of 12, but it still does not send a sms automatically. ## models.py ### # imports class Costom_User(AbstractUser): phone_number = models.CharField(max_length=20) Appart from this error I also receive the following error when I try to go through my login verification : TwilioRestException at /verify/ Unable to create record: The 'To' number "my phone number" is not a valid phone number. I think Twilio only accepts E.164 numbers and so on I need to change the length of possible phonenumber inputs for a user, but I dont know how I shall do that. I am glad for any help, as I said the code works fine, when I input my phone number in the code instead of leaving it as parameter the sms is send, the problem which I need to solve is the … -
How to filter using a function in the left side of an expression?
It is possible to execute a filter with the Django ORM using the Replace function on the left side? It would be to achieve something like this query: select * from my_table where replace(field, '-', '') = 'value' If I try to use the function at the right side, inside the filter function, I'm receiving this error: keyword can't be an expression -
how to get adress from certain selected object?
So I have model with name and adress value. Is it possible to reveal adress in the table after i select certain value of "library". For example - i select some name from option tag and after that adress adds itself in thr table class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') function revealMore() { var blank_text = document.getElementById('blank_option'); // var text_area = document.getElementById('text_area') if (this.value !== blank_text) { var library = this.value; text_area.value = library; } } {% if shop_name %} <select name="shops" id="shop_select" class='box'> <option value="" disabled selected id='blank_option' onchange='revealMore()' name='select_option'></option> {% for library in shop_name %} <option id='library_element'>{{library.shop_name}}</option> {% endfor %} <table> <tr> <th>Adress</th> </tr> <tr> <td id='adress'></td> </tr> </table> -
Django get TypeError: the JSON object must be str, bytes or bytearray, not dict
I'm saving a dict into a JSONfield field in my model. This is going ok, but when I want to retrieve data by id, the next error message appears: ***TypeError: the JSON object must be str, bytes or bytearray, not dict This is an example of what I'm doing: data = {"123": {"dummy": false, "dummy2": 123}}} data is saved succesfully with object.save() into the model. I can see that in the database. When I try to retrieve a registry by id with: try: my_record = models.MyModel.objects.get(business_id=my_id) except models.MyModel.DoesNotExist: logger.debug(f"Record does not exists {my_id}") continue This is the full Traceback: my_record = models.MyModel.objects.get(business_id=my_id) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 425, in get num = len(clone) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 269, in __len__ self._fetch_all() File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 70, in __iter__ for row in compiler.results_iter(results): File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1100, in apply_converters value = converter(value, expression, connection) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/fields/json.py", line 74, in from_db_value return json.loads(value, cls=self.decoder) File "/usr/lib/python3.8/json/__init__.py", line 341, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict I know the issue … -
How do I print " this character in python [duplicate]
Pardon me if this is not a big deal. I came across a program which needed to print " this character and whenever I use this character it closes the string. How can I print this " -
Database design required for a requirement of tree structure [closed]
Database design required for a requirement of tree structure: Tree structure with node Green ones in the image are kind of folder structure and blue ones are links -
Django form not showing when request.method is changed from GET to POST
I am creating a form but when I change request.method == 'GET' to request.method == 'POST', my form does not open when I enter its link. Also when I use 'GET', the form data does not get saved. Please help me solve this problem. Here are the relevant files: models.py from django.db import models # Create your models here. class GrpDetails(models.Model): year = models.IntegerField(default='') branch = models.CharField(max_length=30) group = models.IntegerField(default='') session = models.DateTimeField() sem = models.IntegerField(default='') subject = models.CharField(max_length=50) stu_list = models.FileField(upload_to='documents/') views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.contrib import messages import csv from django.contrib.auth.decorators import login_required from .forms import GrpDetailsForm from .models import GrpDetails # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('dashboard') else: messages.info(request, 'Username or password are invalid!') return redirect('login') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('login') @login_required(login_url='login') def dashboard(request): return render(request, 'dashboard.html') @login_required(login_url='login') def add_class(request, id=0): if request.method == 'GET': if id == 0: form = GrpDetailsForm() else: info = GrpDetails.objects.get(pk=id) form = GrpDetailsForm(instance=info) return render(request, 'newform.html', {'form': form}) else: if id == 0: form = … -
Django Dependent/Chained Dropdown List for more than 2 field
I have implemented a Dependent / Chained Dropdown List (as can be seen in the following code). Now, however, I would need to add a field; so far I have: the provinces, cities (which appear based on the selected province) and offices (which appear based on the selected city). Do you have any advice on how to do it? <script> $( document ).ready(function() { var $a = $("#provddl"); $b= $("#comddl"); $options = $b.find('option'); $a.on('change',function() { $b.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); }); </script> <div> <labe>Provincia: </label> <select id="provddl"> <option> --- selezionare province--- </option> {% for a in A %} <option value="{{ a.province_id }}"> {{ a.province_name }} </option> {% endfor %} </select> </div> <div> <label>Comune: </label> <select id="comddl"> <option> --- select city--- </option> {% for b in B %} <option value="{{ b.province_id }}"> {{ b.city_name }} </option> {% endfor %} </select> </div> -
The Function is being called before the button click. What should i do? [closed]
html code: <div class="container"> <h1>Add An Employee</h1> <hr> <form action="/add_emp" method="post"> {% csrf_token %} <label for="first_name">First Name</label><br> <input type="text"id="first_name" name="first_name" value="{{ first_name }}"><br> <label for="last_name">Last Name</label><br> <input type="text"id="last_name" name="last_name" value="{{ last_name }}"><br> <label for="department">Department</label><br> <input type="text"id="department" name="department" value="{{ department }}"><br> <label for="Salary">Salary</label><br> <input type="text"id="Salary" name="Salary" value="{{ salary }}"><br> <label for="role">Role</label><br> <input type="text"id="role" name="role"value="{{ bonus }}"><br> <label for="bonus">Bonus</label><br> <input type="text"id="bonus" name="bonus" value="{{ role }}"><br> <label for="phone">Phone Number</label><br> <input type="text"id="phone" name="phone" value="{{ phone }}"><br> <hr> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> --> It is calling a views.py function before i click the submit button. If you need the python code as well tell me i will add it. I need help resolving this. All help appreciated. -
Can you horizontally access other fields via "related_name" in Django?
I have a theoric question that I have to solve in order to provide a solution. I am reading a piece of code, but something doesn't make sense to me in how it is accessing the fields through a reverse lookup with "related_name". I share with you the important parts of the code to explain myself. I was looking for more information related to this, and strengthened my knowledge about "related_name" but didn't find something that helped me. class Account(models.Model): country = models.ForeignKey( 'Country', on_delete=models.PROTECT, null=True, blank=True ) class Stage(models.Model): step_name = models.CharField(max_length=100) n_step = models.PositiveIntegerField(null=True, blank=True) class Status(models.Model): TIPOS_STATUS = { ('open', 'open'), ('open_staged', 'open_staged'), ('closed_won', 'closed_won'), ('closed_lost', 'closed_lost') } name = models.CharField(choices=TIPOS_STATUS, max_length=50) class AssignedAccount(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, null=True, blank=True, related_name='assignation', ) status = models.ForeignKey(Status, on_delete=models.PROTECT) stage = models.ForeignKey( Stage, null=True, blank=True, on_delete=models.PROTECT, ) The thing is that I know that I can do something like the following with related_name and do a reverse lookup to see all the assigned accounts toward an account: account = Account.objects.get(pk=1) assigned_accounts = account.assignation.all() But now see what they do with the FK between these two in this DF: accounts = Account.objects.all() accounts_dataframe = pd.DataFrame( list( accounts.values( 'pk', 'country__two_letter_code', 'assignation__stage__n_step', … -
Replacing values for multiple different elements each time I poll the server - htmx
I'm trying to poll the server once every 5 seconds and update 3 different values on the page, all in different locations. I've watched a few tutorials on htmx and oob swaps and I think I'm close to the solution but I just can't get it. The results are coming through fine from the backend, they're just all going into the div with the id="udp", where I trigger the server poll from. I think this is what's causing me the problem but I'm not sure whether I need to move the hx-trigger to ensure id="ujp" and id="uep" both get updated or if I've missed something else? result.html: <div> <div class="card-body" style="margin: 0 auto"> <div id="udp" hx-get="{% url 'result' %}" hx-trigger="every 5s" hx-swap-oob="true" style="text-align: center;"> {% include 'partials/updated_results.html' %} </div> </div> </div> <div class="card"> <div class="card-body" style="margin: 0 auto"> <div id="uep" hx-swap-oob="true" style="text-align: center;"> {% include 'partials/updated_results.html' %} </div> </div> </div> <div class="card"> <div class="card-body" style="margin: 0 auto"> <div id="ujp" hx-swap-oob="true" style="text-align: center;"> {% include 'partials/updated_results.html' %} </div> </div> </div> updated_prices.html: <div id="udp" hx-target="#udp" hx-swap="outerHTML"> {% if add_result1 %} <p>{{ add_result1.result }}</p> {% else %} <p>Retrieving results...</p> {% endif %} </div> <div id="uep" hx-target="#uep" hx-swap="outerHTML"> {% if add_result2 %} <p>{{ add_result2.result … -
Pros/Cons of hosting website on apache vm
I recently have begun hosting my own website on an Apache Linux VM, through the Google Cloud compute engine. This project primarily used Django for backend & API call handling, while using React as the primary frontend engine. Initially hosting the site was difficult for, but once it was running, it was fast, easy to tie to a domain, and performed all functionality as required. My main question was, in this sort of web-application scenario, what would be some alternatives for hosting a site like this? Is this a computationally efficient way of hosting a site? Is it an expensive method when compared to alternatives? How well would this scale with the number of users? -
Django Form Search Bar with multiple chocie
I have a ManyToMany relationship and i want the following : 1) to make for the ManyToMany field, from the form, a search bar. 2) to display all the searched items as check boxes 3) then check ( if wanted) and submit them How should i approach this ? Thanks ! -
is it unconventional to prefix a django app with _
prefixing Django apps with _ does seem to work but is it unconventional? Will it give problems? exemple: _login _dashboard _proxy core locale static templates -
User object has no attribute
I am creating an app in which it manages ranking and ELO functions for a local hobby game store. I am using django to write the application. I am having troubles trying to figure out how to access a user's model from their name. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mtg_currentELO = models.IntegerField(default=1000) mtg_highestELO = models.IntegerField(default=1000) mtg_lowestELO = models.IntegerField(default=1000) def __str__(self): return self.user.username views.py def home(request): users = User.objects.all() if request.method == 'GET': user1 = User.objects.get(username=request.POST['player1']) user2 = User.objects.get(username=request.POST['player2']) print(user1, user2) # DEBUG LINE -- it does find print(user1.mtg_currentELO) # DEBUG LINE -- it does NOT FIND So what I'm trying to accomplish is the find mtg_currentELO from the user1. However, I can't access it via user1.mtg_currentELO. How can I access the property mtg_currentELO of a Profile, via the user's name? -
how to reveal info of selected element?
Is there any way to show info of the object under tag? I somehow need to reveal under this tag adress of selected object: class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') HTML code: {% if shop_name %} <select name="shops" id="shop_select" class='box'> <option value="" disabled selected id='blank_option' onchange='revealMore()' name='select_option'></option> {% for library in shop_name %} <option id='library_element'>{{library.shop_name}}</option> {% endfor %} </select> {% else %} <p>ERROR</p> {% endif %} <script src={% static 'js/show_more.js' %}></script> JS: function revealMore() { var blank_text = document.getElementById('blank_option'); if (this.value !== blank_text) { var library = this.value; alert(library); } } document.getElementById('shop_select').addEventListener('change', revealMore); -
What should i implement on my model regarding data security?
I only have this to define the limit of data on my model. class Direcao_ST(models.Model): direcao= models.CharField("Direção", max_length=7) slugD = models.SlugField(null=False, default="") def clean(self): if (Direcao_ST.objects.count() >= 20 and self.pk is None): raise ValidationError("Can only create 20 Direcao instances. Try editing/removing one of the existing instances.") I would like to know which are the most essential things that I should implement on my Model regarding security. And is there any "defaults" measures of security that every Developer should implement in their Models? -
Django forms.Form reflecting property field constraints
I'm implementing a Django Form witch should contain the field 'fieldA' from modelA: class ModelA(models.Model): fieldA = models.CharField(max_length=8) ... My question is: Is there a way to have Django form, which will automatically handle validation of fieldA (check the max_length)? I know I Could use form.ModelFormclass referring to ModelA, but then the form would reflect all the fields of the ModelA. I would like to use simple forms.Form. I'm looking for a solution like: class formX(forms.Form): fieldA = forms.CharField(**modelA.fieldA.constraints) fieldB = ... some other fields not related to ModelA ... .... even more fields