Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django delete an object
Good day, I have a Model object, which contains the user who created it, as well as the one specified in a form. with localhost:800/delete/int:title_id/ the one object is deleted. Question: How can I make sure that user a user who also created the object can delete it. If userXY owns the object with ID 123 and he calls localhost:800/delete/123, the object will be deleted. But if OtherNutzerYX calls localhost:800/delete/123, the object will not be deleted because the object does not belong to him, but to UserXY. models.py class NewTitle(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) creator_adress = models.GenericIPAddressField(null=True) id = models.BigAutoField(primary_key=True) def __str__(self): return str(self.title) urls.py path('delete/<int:title_id>/', views.title_delete), views.py def title_view(request): titles = NewTitle.objects.all() custom_title_id = random.randint(1111, 1111111111111) if request.method == 'POST': form = NewTitleForm(request.POST, instance=NewTitle(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.id = custom_title_id while NewTitle.objects.filter(id=obj.id).exists(): obj.id = random.randint(111, 11111111111) obj.save() return redirect('/another') else: form = NewTitleForm() return render(request, 'test.html', {'form': form, 'titles': titles}) def title_delete(request, title_id): if #WHAT CODE HERE?: NewTitle.objects.filter(id=title_id).delete() else: return redirect('https://example.com') return HttpResponseRedirect('/another') The relevant code is the title_delete function. I don't know what to write in the if statement. It has something to be like: 'if … -
Faccing issue while exporting csv file in django
I am exporting a CSV file on the frontend as the user clicks on the download button, but sometimes I get an empty file and sometimes I get the exact file that I want. This is happening only on the deployment of the app. The function which is doing all this is : (the channel_list contains a list of dictionaries which has 'url' as key) def exportfile(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachement; filename="channelUrls.csv"' writer = csv.writer(response) for list in channel_list: writer.writerow([list['url']]) channel_list.clear() return response The function which is inserting data to channel_list is : channel_list = [] def home(request): context = {'message' : ""} if request.method == 'POST': rows = [] video_id = [] file = request.FILES["file"].readlines() for f in file: rows.append((f.decode('utf-8'))) for row in rows[0:len(rows)-1]: video_id.append((row[-13:])) video_id.append((rows[len(rows)-1][-11:])) video_id = [x.replace("\r\n","") for x in video_id] search_url = 'https://www.googleapis.com/youtube/v3/videos' parameter = { 'key' : settings.YOUTUBE_DATA_API_KEY, 'part' : 'snippet', 'id' : ','.join(video_id) } data = requests.get(search_url,params=parameter) results = data.json()['items'] temp_list = [] for result in results: data = { 'name' : result['snippet']['channelTitle'], 'url' : f'https://www.youtube.com/channel/{ result["snippet"]["channelId"] }' } temp_list.append(data) [channel_list.append(x) for x in temp_list if x not in channel_list] context['message'] = "Click on Download File to download the file" return render(request,'index.html',context) … -
Trigger onchange via Selenium from Python
I have a Django webapp displaying a form. One of the fields is a FileField, defined via the Django model of the form: class Document(models.Model): ... description = models.CharField(max_length=100, default="") document = models.FileField(upload_to="documents/", max_length=500) The document filefield has an onchange ajax function attached. This is the code of the html page as displayed: <div class=""> <input type="file" name="document" onchange="checkFileFunction(this.value, &#x27;/ajax/check_file/&#x27;)" class="clearablefileinput form-control-file" required id="id_document"> </div> Now, I'm trying to test this with pytest via Selenium. I can send the file path to the field via send_keys(). However, the onchange event seems not to be triggered. (It does work fine when I select the file manually.) file_field = self.driver.find_element(By.NAME, "document") file_field.clear() file_field.send_keys(str(path/to/myfile)) This will register the file fine and it will be uploaded, but the onchange function never happens. I have searched and it seems others also have encountered the problem of send_keys not triggering the onchange event. But I have not been able to implement any of the suggested solutions in my Python code. (I'm not at all firm with JavaScript, yet.) The only solution I understood how to implement was sending a TAB or ENTER afterwards (file_field.send_keys(Keys.TAB)) to change the focus, but that triggers an selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: … -
Python file not getting the values from html file in django for login page
Hello I am new to django so pardon my mistakes. I have made a small login page but I am not able to get the user input values in the textbox to the python (i.e. views.py). Can anyone tell me why? This is my urls page from . import views from django.urls import path, include urlpatterns = [ path('', views.login), path('user_login/',views.studlogin,name='user_login/'), ] This is the views.py file studlogin function def studlogin(request): if request.method == 'POST': username = request.POST.get('Username') password = request.POST.get('Password') if username=="jake": return render(request, 'new.html') The html code for the login page that is index.html is {% load static %} <!DOCTYPE html> <html class=''> <head> <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <script src='https://production-assets.codepen.io/assets/editor/live/console_runner-079c09a0e3b9ff743e39ee2d5637b9216b3545af0de366d4b9aad9dc87e26bfd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/events_runner-73716630c22bbc8cff4bd0f07b135f00a0bdc5d14629260c3ec49e5606f98fdd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/css_live_reload_init-2c0dc5167d60a5af3ee189d570b1835129687ea2a61bee3513dee3a50c115a77.js'></script><meta charset='UTF-8'><meta name="robots" content="noindex"><link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /><link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /><link rel="canonical" href="https://codepen.io/aperyon/pen/oxzpaE?depth=everything&order=popularity&page=23&q=translate&show_forks=false" /> <style class="cp-pen-styles">html, body { border: 0; padding: 0; margin: 0; height: 100%; } body { background: tomato; display: flex; justify-content: center; align-items: center; font-size: 16px; } form { background: white; width: 40%; box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7); font-family: lato; position: relative; color: #333; border-radius: 10px; } form header { background: #FF3838; padding: 30px 20px; color: white; font-size: 1.2em; font-weight: 600; border-radius: 10px 10px … -
Cache.get() not returning anything
My Cache settings, CACHES = { "default": { "BACKEND": "util.redis.ExtendedCache", "LOCATION": "redis://%s:%i/1" % (REDIS_HOST, REDIS_PORT), "TIMEOUT": 7 * 24 * 60 * 60, # One week in seconds "OPTIONS": { "SOCKET_TIMEOUT": 1, "CLIENT_CLASS": "util.redis.ExtendedClient", "CONNECTION_POOL_KWARGS": {"max_connections": 1}, "SERIALIZER": "util.redis.FailsafePickleSerializer", }, }, } When I'm doing the following in a view function, from django.core.cache import cache cache.set(key, value) Its not returning anything when I'm querying the same in shell, cache.get(key) # returns nothing! -
Django admin - autocomplete(_field) without foreignkey or manytomany relationship
I was wondering whether there is a function which lets me implement an autocomplete_field without having this variable be linked to another relation via a foreign key. I.e. I have the models Aaa, Bbb, & Ccc. Bbb & Ccc are related using a foreign key, while Aaa is related to the other two models through even other models. Now I want on the admin side a specific field Ccc, which consists of a field in Aaa, to be autocomplete with the values from Aaa (or at least a suggestion feature so that mistakes are minimized). However, Ccc and Aaa are not directly related; thus, I find it invalid to just assign this item a foreign key. Any suggestions on how to resolve this? As you can figure from my question, I am pretty new to django and would be very grateful for some help here. -
Test django pagination ordering on ListView with large page size
I have a view with a fixed pagination size of 100. I need to test that the ordering is correct, given the pagination. Looking at this example I can create 100 + 1 objects, then test that the expected objects are returned, but this takes a very long time (1 minute+). Is there a way to reduce the pagination size on a generic.ListView for tests? I essentially want to test that the get_queryset method is returning the correct results. Here is my slow running test so far: def test_custom_ordering(): """ test that page ordering is correct, and works with pagination standard page size is 100 NOTE populating 100 results takes a long time, thus we run all ordering tests in this method """ feedbacks = [] # create 101 feedbacks on consecutive days for i in range(0, 102): feedbacks.append( factory.create_feedback( date=datetime(2021, 1, 1) + timedelta(days=i), ) ) # no ordering specified => default: requested_at response = requests.get(f'{URL_NAME}?order_by=date') results = response.html.findChildren("table")[0].findChildren("tr") # expect feedback 0 (oldest) up to 101 (100 page size) # first of results is header, so ignore utils.check_same_results(feedbacks[:100], results[1:]) -
403 Forbidden error in django app hosting on apache with postgres db
I know with sqlite you run the commands: chmod 664 ~/myproject/db.sqlite3 sudo chown :www-data ~/myproject/db.sqlite3 sudo chown :www-data ~/myproject These will give apache access to the db, but how do would I go about doing this with postgres? Thanks -
502 Bad Gateway error with Nginx and Django channels
I'm trying to set up web sockets in my Django application. I'm using Nginx as a reverse proxy and I run the Django application with manage.py runserver without using gunicorn or daphne. When I run just the application locally, I can connect to the web sockets and they work, but when running it with Nginx I get 502 Bad Gateway. upstream web-dev { server web_dev:8080 fail_timeout=600; } server { listen 8050; location /api/ws/ { proxy_pass http://web-dev; proxy_http_version 1.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 1d; } location / { proxy_pass http://web-dev; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; } } -
ModuleNotFoundError: No module named 'jiraglean.jiraglean'; 'jiraglean'
I am trying to run a tests file in a Django project, the app is called jira and project jiraglean , test file is tests.py I run the test with: jiraglean test jira.tests --settings=core.settings.test Which causes this error: File "/Users/pavel/.pyenv/versions/3.8.2/lib/python3.8/runpy.py", line 86, in _run_code File "/Users/pavel/.pyenv/versions/3.8.2/lib/python3.8/multiprocessing/context.py", line 57, in Manager exec(code, run_globals) File "/Users/pavel/Library/Caches/pypoetry/virtualenvs/jiraglean-VXquq6c2- py3.8/bin/jiraglean", line 2, in <module> from jiraglue.jiraglue import run ModuleNotFoundError: No module named 'jiraglean.jiraglean'; 'jiraglean' is not a package I am in a poetry virtual env when doing this. I don't understand why it is looking for the project in the bin folder of the cache, as it is obviously not there. Relevant files/folders. jiraglean ├─ core │ ├─ management │ ├─ permissions │ ├─ settings │ │ ├─ __init__.py │ │ ├─ base.py │ │ ├─ ci.py │ │ ├─ dev.py │ │ └─ test.py │ ├─ __init__.py │ ├─ api.py │ ├─ pagination.py │ ├─ serializers.py │ ├─ urls.py │ ├─ utils.py │ └─ wsgi.py ├─ jira │ ├─ __init__.py │ ├─ admin.py │ ├─ api.py │ ├─ apps.py │ ├─ models.py │ ├─ serializers.py │ ├─ tests.py │ └─ views.py -
Google CloudSQL warnings flooding logs
For the past few days I get the following two warning entries in my logs every half a second, to the point that the logs (without filtering) are useles. CloudSQL warning: your action is needed to update your application and avoid potential disruptions. Please see https://cloud.google.com/sql/docs/mysql/connect-overview for additional details: googleapi: Error 400: Invalid request: Invalid value for region: . Region name can't be empty., invalid and failed to refresh the ephemeral certificate for ###############: googleapi: Error 400: Invalid request: Invalid value for region: . Region name can't be empty., invalid The url they point you at is of no use, and there is not region name setting anywhere. Anyone faced a similar issue? This is an appengine standard environment django app and the cloudsql is msql if that helps -
How to create a custom student group and add students to that group?
I am creating a student project management system and each student will have a group with project. Only the admin will be able to add the students to the specific group using a drop down list menu. So far, I have create a student model and a group model such as these. class Student(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) id = models.IntegerField(max_length=11,primary_key=True) course_taken = models.CharField(max_length=50,null=True) specialization = models.CharField(max_length=50,null=True) area_of_interest = models.CharField(max_length=50,null=True) group = models.ForeignKey(Group,null=True) def __str__(self): if self.user.first_name and self.user.last_name: full_name = self.user.first_name + " " + self.user.last_name return full_name class Group(models.Model): id = models.AutoField(primary_key=True) members = models.OneToManyField(User,through='Student') project_id = models.ForeignKey(Project,null=True) How to continue from this ? -
Fixture not found pytest
Hey I got a simple test where the fixure is not found. I am writting in vsc and using windows cmd to run pytest. def test_graph_add_node(test_graph): E fixture 'test_graph' not found > available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory > use 'pytest --fixtures [testpath]' for help on them. This is the error I get, here is the test code: import pytest import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'giddeon1.settings') import django django.setup() from graphs.models import Graph, Node, Tag @pytest.fixture def test_graph(): graph = Graph.objects.get(pk='74921f18-ed5f-4759-9f0c-699a51af4307') return graph def test_graph(): new_graph = Graph() assert new_graph def test_graph_add_node(test_graph): assert test_graph.name == 'Test1' im using python 3.9.2, pytest 6.2.5. I have see some similar questions but they all handle wider or bigger problems. -
How to add pagination to Django Filter Views?
Filtering and Pagination with Django I want to add pagination in filter view function below contain my code Filters.py : when i add paginated by is unavailable at the wepages class AccountFilter(django_filters.FilterSet): username = django_filters.CharFilter(lookup_expr='icontains') first_name = django_filters.CharFilter(lookup_expr='icontains') last_name = django_filters.CharFilter(lookup_expr='icontains') is_staff = django_filters.BooleanFilter(widget=CustomBooleanWidget) is_superuser = django_filters.BooleanFilter(widget=CustomBooleanWidget) is_active = django_filters.BooleanFilter(widget=CustomBooleanWidget) date_joined = django_filters.DateFromToRangeFilter(label='Date Joined Range', widget=django_filters.widgets.RangeWidget(attrs={'placeholder': 'yyyy/mm/dd','class': 'datepicker', 'type': 'date'})) ` views.py : # AccountFilter View: def AccountViewFilter(request): userf_list = User.objects.all() userf_filter = AccountFilter(request.GET, queryset= userf_list) return render(request, 'accounts/user_list.html', {'filter': userf_filter}) user_list.html: {% if filter.qs%} <table class="table"> <thead class="thead-dark"> <tr> {# <th scope="col">No</th> #} <th scope="col">User Name</th> <th scope="col">User Email</th> <th scope="col">Is Staff</th> <th scope="col">Is Active</th> <th scope="col">Date Joined</th> <th scope="col">Is SuperUser</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> {{endif}} -
Python/Django Improperly Configured Error - Settings are not configured
I have a Django project called Veganet that I am trying to connect to two other applications using flask, but when I run my main script vega_flask_run.py it gives me an improperly configured error. The source of the error is coming from a script named models.py, more specifically line 2 where I am declaring from django.contrib.auth.models import User. I have tried to use a few posts to solve my problem including: Django DB Settings 'Improperly Configured' Error ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details “settings.DATABASES is improperly configured” error performing syncdb with django 1.9 I have tried their solutions which mostly includes changing the INSTALLED_APPS variable in my projects settings.py and changing the DATABASES variable inside settings.py, as well as using windows powershell to execute python manage.py shell, django-admin.py shell --settings=mysite.settings, and then setting the DJANGO_SETTINGS_MODULE variable to point to my projects settings and lastly using from django.core.management import setup_environ from veganet import settings setup_environ(settings) as the answer suggests in the first link. here is the error in it's entirety: Exception has occurred: ImproperlyConfigured Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or … -
Docker container build fails on local if a unit test fails but build successfully on Azure
init.sh file #!/bin/bash cd /code python manage.py migrate python manage.py load_fixtures python manage.py collectstatic --noinput python manage.py test || exit 1 python manage.py runserver 0.0.0.0:8000 When the test fails my docker compose fails and container is not built but when I take the code online to azure pipeline. It works with out giving test error. -
django not checking elif condition views.py
In my views.py if i provide only 1 elif condition its working but when i give 2 elif condition its not working In views.py def dashboard(request): if request.user.is_superuser: a=branch.objects.aggregate(Count('id')) b=emp.objects.aggregate(Count('id')) elif request.user.admin.position == 'admin': a=branch.objects.aggregate(Count('id')) b=emp.objects.filter(branch=request.user.admin.branch_name).aggregate(Count('id')) elif request.user.emp.position == 'employee': a=branch.objects.aggregate(Count('id')) b=emp.objects.filter(branch=request.user.emp.branch).aggregate(Count('id')) -
Django 4.0.1 authentication from not default database
I create project using DRF, I'm using two database alias: Default and Oracle. On oracle database there are all django tables. How can I use authenticate if auth_user is on oracle not default database. -
Problem installing django-auth-ldap on Centos 8
I have problem with finalizing netbox installation on Centos8. Netbox is working fine with Gunicorn and Apache. I wanted to add LDAP auth but there is a problem with django-auth-ldap installation. Can you tell my why? I'm using proxy but all installations where ok sofar. Maybe there is no setuptools version for centos8 higher or equal to 40.8.0? (venv) test # python -m pip --proxy http://x.x.x.x:8080 install django-auth-ldap Collecting django-auth-ldap Using cached django_auth_ldap-4.0.0-py3-none-any.whl (20 kB) Collecting python-ldap>=3.1 Using cached python-ldap-3.4.0.tar.gz (376 kB) Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: /opt/netbox-3.1.6/venv/bin/python /tmp/pip-standalone-pip-7k0onaz9/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-af6_ygqc/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel cwd: None Complete output (7 lines): WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8aaf45b880>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /simple/setuptools/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8aaf45bc10>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /simple/setuptools/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8aaf45b040>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /simple/setuptools/ … -
How to retrieve URL fragment parameters in drf APIView?
I have created a callback view for instagram account connection in django by inheriting the APIView class. After successful connection of instagram account facebook redirects me to the InstagramConnectCallbackView and includes the response data as a URL fragment. url: http://localhost:8000/v1/instagram-connect/callback/?#access_token=EAAN....&data_access_expiration_time=1650543346&expires_in=6254&state=eyd... But I don't know how to read the URL fragments from the request into the get method. callback view: class InstagramConnectCallbackView(APIView): permission_classes = (permissions.AllowAny,) version = settings.FACEBOOK_GRAPH_API_VERSION def get(self, request, format=None): .... I tried the following: request.get_full_path() # returns `/v1/instagram-connect/callback/` request.query_params() # returns `{}` Any help will be appreciated. -
How to setup memcached for Django 3.0 on App Engine?
So I have a Django 3.0 app that I want to deploy to App Engine. I want to use Memcached in order to cache data that has been pulled from BQ to my Django app. So far what I have is that I set up my Django's views.py as follows: from google.appengine.api import memcache def index(request): cached_data = memcache.get('cached_data') if not cached_data: # Syntax to pull data here memcache.add(key='cached_data', value='pulled_data', time=3600) My app.yaml also includes app_engine_apis: true However, after deploying the app using gcloud app deploy and opening the web app, I'm getting a 500 Server Error. I believe this error is because of the Memcached but I'm not sure what I am missing. Additional Note: I have not set any CACHES in my settings.py as none were mentioned on the GCP website. I used this during development locally: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } But then I removed it right before deploying to App Engine. I've tried following this SO Answer but it didn't work for me. -
want fetch existing data from db in django. 1054 "Unknown column 'traders.id' in 'field list'" error getting. Id is automatically generate in db
def Fetch_data(request): if 'q' in request.GET: q = request.GET['q'] #enter image description here'q' is name given in form data = Traders.objects.filter(traders_name__icontains=q) else: data = Traders.objects.all() return render(request,"fetch_data.html", {'data':data}) html file(tempplate)- <tbody> {% for data in data %} <tr> <th scope="row">1</th> <td>{{data.traders_name}}</td> <td>{{data.email}}</td> <td>{{data.registration_no}}</td> <td>{{data.address}}</td> </tr> --> {% endfor %} </tbody> -
How to validate fields in Django?
I'm new to Django. I was a .NET developer. I've created a form for new users' registration, but my problem is that I need some validation controls to validate my fields. I could not find any resources or examples. Any help, please? My newuser.html is in the below: {% block content %} <form method="POST"> {% csrf_token %} <table> <tr> <td> <lable>Name </lable> </td> <td> <input type="text" name="name"> </td> </tr> <tr> <td> <lable>Username </lable> </td> <td> <input type="text" name="username"> </td> </tr> <tr> <td> <lable>Password </lable> </td> <td> <input type="password" name="password"> </td> </tr> <tr> <td> <lable>Confirm password </lable> </td> <td> <input type="password" name="confirmPassword"> </td> </tr> <tr> <td> <lable>email </lable> </td> <td> <input type="email" name="email"> </td> </tr> <tr> <td> <input type="submit" name="save" value="Save" colspan=2> </td> </tr> </form> {% endblock content %} -
in Django: How to get and display in template verbose_name of a model that their value is true, while name of field unknown?
I have a model than has a lot of models.BooleanField declarations. class a_lot_of_booleans(model.Models): old_or_new = models.BooleanField(default=False,verbose_name="is it an old or a new item") product_for_teens = models.BooleanField(default=False,verbose_name="is this product for teens") in_original_package = models.BooleanField(default=False,verbose_name="is this product in original package?") Which then is used in some other classes like: class product_for_sale(a_lot_of_booleans): U_Id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) product_name=models.CharField(max_length=50) class product_for_buying(a_lot_of_booleans): U_Id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) product_name=models.CharField(max_length=50) The class a_lot_of_booleans might change over time. Some booleans might get added some might get removed. What I need is to display a list of several entries, of the verbose_name, of only the true fields on one of the classes that inherit the a_lot_of_booleans class and the value of product_name, belonging to specific user. What I"m trying in the views.py is the following: def view_rfps(request): list=product_for_sale.objects.all().filter(U_Id=request.user) for item in list: values=item._meta.fields for value in values: res=item.objects.filter(**{value:'True'}) ##<< lines that fail print(res) the above code fails on res=item.objects.filter(**{value:'True'}) on "Manager isn't accessible via search_for_constructor_rfp instances" The idea later to pass on the res variable to view, however I cannot pass this point. I have several items in list and for every list several boolean fields, that I"m not sure what they names gonna be in a future, so … -
How to coordinate randomly chosen objects in a DRF APIView?
I am building an API for a game and need to select a random game round for a randomly chosen resource. Choosing the random resource works. What I am trying to do now, in order to coordinate players is to filter the game rounds by the resource that has been chosen randomly and then return a random game round. The code below shows what I have tried so far, namely to access the resource for which a game round has been played over the method with the @property decorator. models.py class Gameround(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gamesession = models.ForeignKey(Gamesession, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) objects = models.Manager() def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) def create(self): pass @property def tags(self): tags = self.taggings.values('tag') return tags.values('tag_id', 'tag__name', 'tag__language', 'resource_id') class Tagging(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, related_name='taggings') resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='taggings') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) origin = models.URLField(max_length=256, blank=True, default='') objects = models.Manager() def create(self, tag): tagging = self.create(tag=tag) def __str__(self): return str(self.tag) or '' def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) I am then …