Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comment is not displaying in django after submission
I have tried to submit a comment from app rather than django admin. Comment is not displaying when submitted from my created app. But it is displaying when I add a comment from django admin app. May be I am doing something wrong in views.py file. Can anyone help me on this? Thank you. views.py: @login_required def book_review(request,id): book = get_object_or_404(Bookslist, id=id) comment=Comment.objects.all().filter(post_id=id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user_id = request.user post.message= comment post.save() return redirect('book_review', id=id) else: form=CommentForm() return render(request, "books/book_review.html", {'book':book, 'comment':comment, 'form': form}) models.py: class Comment(models.Model): message= models.TextField('Message',null=True) date_comment=models.DateTimeField(default=now, null=True) user_id= models.ForeignKey(User, on_delete=models.CASCADE,null=True) post_id=models.ForeignKey(Bookslist,on_delete=models.CASCADE,null=True) forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['message', ] book_review.html: {% extends 'books/base.html' %} {% load static %} {% block stylesheet %} <link rel="stylesheet" href="{% static 'accounts/accounts.css' %}"> {% endblock %} {% block content %} <div class = "container"> <ul class = "nav nav-tabs" id = "myTab" role = "tablist"> <li class = "nav-item"> <a class = "nav-link active" id = "summary-tab" data-toggle = "tab" href = "#summary" role = "tab" aria-controls = "summary" aria-selected = "true">Summary</a> </li> <li class = "nav-item"> <a class = … -
Django Python Autocomplete Light select dont show
I have a problem adding the autocomplete light select2 on my custom Model. I got the package installed with pip, and added in settings.py: INSTALLED_APPS = [ 'dal', 'dal_select2', 'dal_legacy_static', 'django.contrib.admin', 'django.contrib.auth', .... My url for get the querysets: url(r'^property-autocomplete/$', PropertyAutocomplete.as_view(),name='property-autocomplete'), I tested it and I get the results correctly. My autocomplete: class PropertyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Property.objects.all() if self.q: qs = qs.filter(p_address_street=self.q) return qs And on my form, I added: class ReserveForm(BSModalModelForm): re_renter = forms.ModelChoiceField(queryset=User.objects.filter(u_user_type=0).order_by('-pk')) re_inquilinos = forms.ModelMultipleChoiceField(queryset=User.objects.filter(u_user_type=0).order_by('-pk'), required=False) re_enter_date = forms.DateField(required=True, widget=forms.TextInput(attrs={'type':'date'})) re_exit_date = forms.DateField(required=True, widget=forms.TextInput(attrs={'type':'date'})) re_property = forms.ModelChoiceField(queryset=Property.objects.all(), widget=autocomplete.ModelSelect2(url='property-autocomplete')) The re_property is the field I want to be selectable, is a Foreign Key value. In my HTML form I got: {% load crispy_forms_tags %} {% load static %} <form method="POST" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Modificar/Crear Reserva</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.re_property|as_crispy_field }} </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Create</button> </div> </form> {{form.media}} I tried to import select2.js, jquery, etc, But nothing work. The actual result is like a normal select: And I only have that register to choose. I don't know … -
Schema creation and migrations from Django Admin UI
I was searching about the specific need, but did not got many useful results, so i will just ask for any ideas, libraries, hints that you may have. So the idea I want to realize comes from a model that is totally unrelated to the Django app and it may change over time, based on some requirement changes. So i do not want the user to manually execute some SQL commands when changes occur, and i want him to do that over the Admin UI where he would edit some existing columns, constraints, add new ones, using the standard inputs that an admin gives (check boxes, selects etc). From the input he makes, the tables will be created (first time), altered after any change after it etc. So the schema he would work on would look something like this: Table -------------------------------- | id | table_name | table_type | -------------------------------- | 1 | table1 | type1 | -------------------------------- | 2 | table2 | type2 | -------------------------------- Column ----------------------------------------------------------------- | id | column_name | nullable | unique | primary_key | table_id | ----------------------------------------------------------------- | 1 | column1 | false | true | true | 1 | ----------------------------------------------------------------- | 2 | column2 | … -
Django contrib comments: RuntimeError: Model class django_comments.models... application in INSTALLED_APPS
I'm trying to add django-contrib-comments Version: 1.9.2 and Django Version: 3.1.2 I've added it to settings INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... #imports 'comments_moderation', ] it throws this error File "/home/sam/code/kpsga/lamusoftware/blog/models.py", line 5, in <module> from django_comments.moderation import moderator File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/moderation.py", line 369, in <module> moderator = Moderator() File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/moderation.py", line 294, in __init__ self.connect() File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/moderation.py", line 302, in connect signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=django_comments.get_model()) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/__init__.py", line 49, in get_model from django_comments.models import Comment File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/models.py", line 12, in <module> class Comment(CommentAbstractModel): File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/db/models/base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class django_comments.models.Comment doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. which suggests it needs to be added to INSTALLED_APPS but it's already added. -
How to use wkHTMLtoPDF running in docker-compose in Django application
I have a problem with undestanding on how to use wkHTMltoPDF, that I run in docker-compose and Django. Also I can't understand how to setup it in Django and use it in the right way. I will be very glad for any help. My docker-compose.yml: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 wkhtmltopdf: image: openlabs/docker-wkhtmltopdf-aas:latest volumes: - .:/data So, I can't even imagine where I should do it in Django. The example of usage that I need: on main page I fill some forms and then click button "Generate". It should send async requests on generating pdf file of this page with filled forms. Can anybody help me to realise it? -
Django Latest Timestamped Items from Many
I have a Model where there can be multiple instances of the same entry. They have their respective timestamps as I scrape the same data sources daily. I want to only receive the latest entries for each item. I wanted to approach this as grouping by the identifier of the items, which will result in groups of the same items but different timestamps, then get the latest from each group and combine this. My question is, how can this be done in Django? From what I have read I can use the "annotate()" function to GroupBy and then use "latest()" on each group. Is there any better way of accomplishing the same result or is this a proper approach? Thank you! -
Django uploaded file doesn't process
I'm building a Django web-app where the user needs to upload a file. This file should go through a machine-learning alogritme after that the results will be presented on a different page. right now it works if I have text fields present for every feature but when I want to upload a csv file(the csv file is called test.csv) put it in a pandas dataframe the resultpage doesn't show and it looks like the csv file isn't processed. what it should do is if file is uploaded keep the uploaded file in memory process it and return the output on the results page. HTML {% extends "base.html" %} {% block content %} <div class="content"> <div class="row"> <div class="col-lg-4"> <div class="card card-tasks"> <h1> </h1> <form action="{% url 'result' %}"> {% csrf_token %} <p>temp_normal:</p> <input class="form-control" type="text" name="temp_normal"> <br> <p>hour:</p> <input class="form-control" type="text" name="hour"> <br> <p>hour_x:</p> <input class="form-control" type="text" name="hour_x"> <br> <p>hour_y:</p> <input class="form-control" type="text" name="hour_y"> <br> <input class="form-control" type="submit" value='Submit'> </form> </div> </div> <div class="col-lg-4"> <div class="card card-tasks"> <form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="csv_file" id="csv_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div … -
When I clicked on 'viewall' submit button on html it goes to 'RestInfo url' and show NoReverseMatch at error Django
Template Code <a href="{% url 'ViewAll' cust.custId %}" <button class="btn cart viewall">View All</button></a> <a href="{% url 'RestInfo' rest.restId cust.custId %}" style="color: #000000;">RestInfo</button></a> url.py path('ViewAll/<str:mycid>',views.ViewAll,name='ViewAll') path('myRest/<int:myid>/<str:cid>',views.RestInfo,name='RestInfo'), views.py def ViewAll(request,mycid): print("Welcome",mycid) rests= Restaurant.objects.all() return render(request,'viewall.html',{'rests':rests}) def RestInfo(request,myid=None,cid=None): rests= Restaurant.objects.filter(restId=myid) return render(request,"restInfo.html",{'rest':rests[0]}) When I Clicked on button in which viewll url is given then it goes to restinfo and shows me noreversematch error -
Permissions Issues Linux
I'm trying to follow the Django official tutorial. When I'm trying to create a new project: django-admin startproject mysite I have this error : CommandError: [Errno 13] Permission denied: '/home/olivier/Documents/python/Django/official_tutorial/mysite' I thought that I didn't have the rights in this folder. Which is weird cause it's my personal folder. So I checked with ls -l /home : total 4 drwxrwxr-x 27 olivier olivier 4096 oct. 22 15:16 olivier Apparently I do have the rights. Side note I cannot create a venv in it with virtualenv venv virtualenv: error: argument dest: the destination . is not write-able at /home/olivier/Documents/python/Django/official_tutorial SystemExit: 2 What seems to be the problem here ? I'm running Pop!_OS 20.04 LTS -
Filtering Objects Using Other Objects - Queryset, Django
In my Django application, the user provides a unique product name which matches field of another object and then displays second object on the list (that the user sees). So the object's display condition looks something like this obj1.name == obj2.name It is extremely simple for one object but how to use it for get queryset (where the field of objects 1 is equal to the field of object 2)? An example of the effect I want to get: Obj1.objects.all() = ('AS2', 'AS9', 'AD5', 'AG1') Obj2.objects.all() = ('DD1', 'AS2', 'AS9', 'AP33', 'AD5', 'AG1', 'KQ1', 'LG4') query1 = Obj1.objects.all() query2 = obj2.objects.filter(name=???) #and query2 return all objects product which name=name well ('AS2', 'AS9', 'AD5', 'AG1') but from Obj2 -
django isn't sending data to html?
I am a newbie so please ignore the question quality :). my django views.py -- def search(request): if request.method == 'POST': try: query = request.POST["query"] try: query2 = User.objects.get(username=query) except: query2 = None if query2 == None: results = info.objects.filter(name=query) else: results = info.objects.filter(user=query2, name=query) if results == "": results=None return render(request, "search.html", {"results": results}) # https://docs.djangoproject.com/en/dev/topics/db/queries/# #spanning-multi-valued-relationships except: messages.info(request, "User not found") return redirect(home) else: pass my html page -- <div class="container"> {% for result in results %} <a href="profile_seen?profile_seen={{result.user}}-1"> <div style="border: 0.7px solid gray;" class="row card"> <div style="display: flex;align-items: center; justify-content: center;"> <img style="width: 107px; margin: 10px 2%;" class="img-fluid" src="https://facyfun-bucket.s3.ap-south-1.amazonaws.com/{{result.profile_pic}}" alt="error"> <ul style="padding: 11px 12%;" class="list-group list-group-flush"> <li style="font-size: 32px;" class="list-group-item p-0">{{result.user}}</li> <li style="font-size: 19px;" class="list-group-item p-0">{{result.name}}</li> <li style="font-size: 17px;" class="list-group-item p-0">age {{result.age}}y</li> </ul> </div> </div> </a> {% endfor %} Error -- I am sending data(results) but it still shows nothing(not even null value). -
Django save nested data to Elasticsearch
I want to save nested data to elastic, I created model, document and serialize. Incoming Data(from twitter and parsed): {'created_at': '2020-10-26 20:00:14', 'tweetID': xxx, 'userID': xxx, 'userName': 'xxx', 'userScreenName': 'xxx', 'full_text': 'xxx', 'hashtag': ['xxx'], 'urls': ['xxx'], 'ioc': [ {'type': 'xxx', 'value': 'yyy', 'first_discovery': '2020-10-26 20:00:14', 'last_observed': '2020-10-26 20:00:14'}, {'type': 'kkk', 'value': 'mmm', 'first_discovery': '2020-10-26 20:00:14', 'last_observed': '2020-10-26 20:00:14'}]} My Model class: from django.db import models from django.utils.translation import ugettext_lazy as _ class TwitterPost(models.Model): created_at = models.DateTimeField( _('created_at'), blank=True, null=True, ) tweetID = models.CharField( _('tweetID'), blank=True, null=True, default=None, max_length=100, ) userID = models.CharField( _('userID'), null=True, blank=True, default=None, max_length=100, ) userName = models.CharField( _('userName'), null=True, blank=True, default=None, max_length=200, ) userScreenName = models.CharField( _('userScreenName'), null=True, blank=True, default=None, max_length=200, ) full_text=models.CharField( _('full_text'), null=True, blank=True, default=None, max_length=500, ) hashtag = models.CharField( _('hashtag'), null=True, blank=True, default=None, max_length=250, ) urls = models.CharField( _('urls'), null=True, blank=True, default=None, max_length=200, ) hashtag = models.CharField( _('hashtag'), null=True, blank=True, default=None, max_length=250, ) urls = models.CharField( _('urls'), null=True, blank=True, default=None, max_length=200, ) def __str__(self): return self.tweetID class TwitterPostIOCs(models.Model): ioc = models.ForeignKey(TwitterPost, related_name='tweetIOC', on_delete=models.CASCADE) type = models.CharField( _('type'), null=True, blank=True, default=None, max_length=100, ) value = models.CharField( _('value'), null=True, blank=True, default=None, max_length=100, ) first_discovery = models.DateTimeField( _('first_discovery'), blank=True, null=True, ) last_observed = models.DateTimeField( _('last_observed'), blank=True, … -
Django: More pythonic way of saving form data to existing model
I'm currently saving my new ModelForm values by iteration of each form's cleaned values after validation. Is there a better way of doing this? Note: 'Activity' model already contains data for given example record_form = AddRecordTimeFrame(request.POST) activity_form = EditRecordGeneral(request.POST) activity_form_2 = EditRecordChassisDynoTest2(request.POST) if all([activity_form.is_valid(), activity_form_2.is_valid(), record_form.is_valid()]): test_record = RecordModel.objects.get(id=1) activity_record = test_record.activity for field, value in record_form.cleaned_data.items(): setattr(test_record, field, value) for field, value in activity_form_2.cleaned_data.items(): setattr(activity_record, field, value) for field, value in activity_form.cleaned_data.items(): setattr(activity_record, field, value) I'd like to make use of the form's .save() but only change values of the model that are in the fields of the modelform. -
I got an Operational error after trying to register on a web i developed using django python
https://dpaste.com/BZ8VWDUTG OperationalError at /reg_form/ no such table: selection_user Request Method: POST Request URL: http://127.0.0.1:8000/reg_form/ Django Version: 3.1.2 Exception Type: OperationalError Exception Value: no such table: selection_user Exception Location: C:\Users\HP\Downloads\django implementation\Hostel-Management-System\venv\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Users\HP\Downloads\django implementation\Hostel-Management-System\venv\Scripts\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\hhms', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python37', 'C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\venv', 'C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\venv\lib\site-packages'] -
how to disappear html tags in django (safe tag not working properly)
I am making a blogging website like this I want to remove these tags (<p> <em>) which are being displayed in these cards page-html (before adding safe tag): <div class="container"> <div class="card-deck"> {% for post in top_posts %} <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title|truncatechars:14|safe}}</h5> <p class="card-text text-justify">{{post.content|truncatechars:190}}</p> <br> <p class="card-text"><small class="text-muted">{{post.timeStamp|timesince}}</small></p> <div> <a href="/blog/{{post.slug}}" class="btn btn-primary">ReadMore</a> </div> </div> </div> {% endfor %} </div> </div> page-html (after adding safe tag): <div class="container"> <div class="card-deck"> {% for post in top_posts %} <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title|truncatechars:14|safe}}</h5> <p class="card-text text-justify">{{post.content|truncatechars:190|safe}}</p> <br> <p class="card-text"><small class="text-muted">{{post.timeStamp|timesince}}</small></p> <div> <a href="/blog/{{post.slug}}" class="btn btn-primary">ReadMore</a> </div> </div> </div> {% endfor %} </div> </div> how page looks: help me to remove these italics and display the text in original cards style. -
Django's m2m_changed signal on User's groups is not triggered
I created an m2m_changed signal to automatically set is_staff attribute of users when they join/leave a specific group, but the signal is never fired. Here is the signal's definition : @receiver(m2m_changed, sender=User.groups.through) def moderator_group_is_staff(sender: Type[User], instance: Union[User, Group], action: str, reverse: bool, model: Union[Type[User], Type[Group]], pk_set: Set[int]): """Set `is_staff` attribute of users to `True` or `False` when they respectively join or leave the moderator's group.""" moderator_pk = Group.objects.get(name=settings.GROUPNAME_MODERATOR).pk # instance is User, pk_set is Groups' pk if not reverse and moderator_pk in pk_set: if action == "post_add": instance.is_staff = True if action == "post_remove" or action == "post_clear": instance.is_staff = False # instance is Group, pk_set is Users' pk elif reverse and instance.pk == moderator_pk: if action == "post_add": instance.user_set.update(is_staff=True) if action == "post_remove": User.objects.filter(id__in=pk_set).update(is_staff=False) if action == "pre_clear": instance.user_set.update(is_staff=False) I tried from django's admin interface and the manage.py shell, but the function was never called. Any idea ? -
Django all-auth allow users to login only if the user email address is verified
How do i override AllAuth default LoginView to allow users to login only if their email address is verified? -
I want to show JSON data in my Django template when Django's URL is roaded
I want to show JSON data in my Django template when Django's URL is roaded. My Django server structure is like polls(Django's parent app) has urls.py &views.py and templates has app has top.html. polls has app(Django's children app) has urls.py &views.py. I wrote urls.py of app from django.urls import path, include from . import views app_name = 'app' urlpatterns = [ path('index/', views.Top.as_view(), name='index'), ] views.py of app class Top(LoginRequiredMixin, TemplateView): template_name = 'app/top.html' login_url = '/login/' @csrf_exempt def index(request): if request.is_ajax: if request.method == 'POST': json_data = json.loads(request.body.decode("utf-8") dict['A'] = json_data[1]['A'] dict['B'] = json_data[1]['B'] else: dict = [] return render(request, 'app/top.html', dict) I wrote urls.py of polls urlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ] I made test folder has test.html&test.js. I wrote test.html like <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript" src="test.js"></script> </head> <body> <p>TEST</p> </body> </html> and test.js var info = [ { "A": "key", "B": "123, }, ]; const csrftoken = Cookies.get("csrftoken"); var xhr = new XMLHttpRequest(); var json = JSON.stringify(info); xhr.open("POST", "http://127.0.0.1:8000/app/index/"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(json); I run Django server & opened test.html in Google browser.However Console of Google browser said POST http://127.0.0.1:8000/app/index/ 403 … -
Set up db_password for django and postgres in docker
I've a docker image with django 3.1 and postgresql. In the docker-compose.yml I wrote: version: '3' services: app: build: context: . ports: - "8001:8001" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8001" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=password depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password In the Django app's settings.py I read the database password from the .txt file excluded from the .git ... DB_PASSWORD = '' with open('database_password.txt') as f: DB_PASSWORD = f.read().strip() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': DB_PASSWORD, } } ... What is the best practice to make Django and Docker securely read the same password from the same place? The most suitable information about this I found here: https://medium.com/swlh/setting-up-a-secure-django-project-repository-with-docker-and-django-environ-4af72ce037f0 The author offers to use the django-environ package for django. The docker part in this article descibed like this: If you specifed a different user and password in the DATABASE_URL variable in the .env file above, you should include them here (although this will compromise the security of the database, as the docker-compose.yml file will be committed to the repository). When it comes time to deploy the … -
How to create an image sitemap in Django
My model is the Station and the field holding the image url is the image I find difficulty on how to build my sitemaps.py file in order to be able to present also in sitemap.xml file the <image:loc> tag based on the image url. The source here : image sitemap just presents the xml format. I want to build a xml file like this based on the code written in sitemaps.py file. urls.py from .sitemaps import StationSitemap sitemaps = { 'station' : StationSitemap, } urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), ] sitemaps.py from django.contrib.sitemaps import Sitemap from stations.models import Station class StationSitemap(Sitemap): def items(self): return Station.objects.all() def location(self,item): return item -
I got an error name 'LOGIN_REDIRECT_URL' is not defined
I use django and when I put LOGIN_REDIRECT_URL in settings.py on the bottom, I got an error like this name 'LOGIN_REDIRECT_URL' is not defined What problems in my code? https://www.youtube.com/watch?v=3aVqWaLjqS4&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=7 I refer to this and I completely write same code. Please tell meeeeeeee! -
Django template loop many-to-many iteration query efficiency
Models: class ItemManager(models.Manager): def get_queryset(self): return super(AssetsManager, self).get_queryset().prefetch_related( models.Prefetch("assignments", queryset=Assignments.objects.select_related("userid"))) class Item(models.Model): objects = ItemManager() id = UnsignedAutoField(db_column='Id', primary_key=True) user = models.ManyToManyField('Owner', through='Assignments', through_fields=('itemid', 'userid')) @property def owner(self): return self.assignments.select_related("userid").last().userid class User(models.Model): id = UnsignedAutoField(db_column='Id', primary_key=True) item = models.ManyToManyField('Item', through='Assignments', through_fields=('userid', 'itemid')) class Assignments(models.Model): id = UnsignedAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') userid = models.ForeignKey('User', default=None, blank=True, null=True, on_delete=models.SET_DEFAULT) itemid = models.ForeignKey('Item', on_delete=models.SET_DEFAULT, related_name='assignments') In my template I am trying to iterate over the Item queryset while also displaying the owner. The problem is that a new SQL query will be made for every step of the loop. Template loop: {% if item_list %} {% for item in item_list %} {{item}} - {{item.owner}} {% endfor %} {% endif %} The view is a ListView where the queryset is "Item.objects.filter(Q(id__gte=1) & Q(id__lte=5))". The context_object_name is item_list. Using Django Debug Toolbar I notice the following: SELECT ••• FROM `Assignments` LEFT OUTER JOIN `User` ON (`Assignments`.`UserId` = `User`.`Id`) WHERE `Assignments`.`ItemId` IN (1, 3, 5, 2, 4) This query corresponds to {% if item_list %} Then a new query is made for every iteration: SELECT ••• FROM `Assignments` LEFT OUTER JOIN `User` ON (`Assignments`.`UserId` = `User`.`Id`) WHERE `Assignments`.`ItemId` = 1 ORDER BY `Assignments`.`id` DESC LIMIT 1 … -
Django REST endpoints for Watchlists feature
I wanted a system of multiple watchlists per user (upto 5) where users can add/remove products into individual watchlists. I have the following models is my models.py: class Product(models.Model): name = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100) sku = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100, verbose_name='Stock Keeping Unit') description = models.TextField(blank=True) price = models.FloatField(blank=True) class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) display_name = models.CharField(max_length=30) subscription = models.CharField(null=False, blank=False, choices=SubscriptionChoices.choices, default=SubscriptionChoices.SILVER, max_length=100) class Watchlist(models.Model): from .choices import WatchlistChoices profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ManyToManyField(Product) wl_num = models.CharField(null=False, blank=False, choices=WatchlistChoices.choices, default=WatchlistChoices.WL1, max_length=30) name = models.CharField(null=False, blank=False, max_length=20, default='NewWatchList') I have the following choices in a choices.py file: class WatchlistChoices(models.TextChoices): WL1 = 'WL1', _('Watchlist_1') WL2 = 'WL2', _('Watchlist_2') WL3 = 'WL3', _('Watchlist_3') WL4 = 'WL4', _('Watchlist_4') WL5 = 'WL5', _('Watchlist_5') I have put in the choices so that at any given time only the five predetermined watchlists can be used, hence limiting the number of watchlists per user to only 5. How can I build REST endpoints using DRF for the following tasks: Add/remove products into a specified watchlist Change the name of the watchlist Can this be done with class based views or does it need to be done with function based views? -
How to send request using a field in DjangoRestFramework UI
I am making a request from some external source, I am successfully able to make the request both manually and by passing the "ref_no" in my url, but I will like to have a way whereby I can put the "ref_no" in the DRF UI and make a post to the requested source and then get the data. I don't know if this is possible but I would be glad to get a way across this. views.py class Pay(APIView): def get(self, request, reference_id): url = f"https://api.paystack.co/transaction/verify/{reference_id}" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) urls.py from django.urls import path, include from .views import * urlpatterns = [ path('pay/<str:reference_id>', Pay.as_view(), name='pay'), ] -
I want to iterate a range of years using for loop in django
I want to display a set range of years using for loop with some start year to the current year and then after each passing years the current year will be that particular year. Example: start year is 2010 current year is 2020 It will display from year '2010' to '2020' So when 2021 comes the range will display from '2010' to '2021' my code is: import datetime def daterange(start, end, step=datetime.timedelta(1)): current_year = start while current_year < end: yield curr curr += step