Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validate end_time is bigger than start_time django form
I have start_time and end_time datefields in models and I want to assign an error when start_time is later than end_time. forms.py class RentForm(forms.ModelForm): class Meta: model = Rent fields = ['start_time', 'end_time'] def clean(self): cleaned_data = super().clean() start_date = cleaned_data.get("start_time") end_date = cleaned_data.get("end_time") if start_time > end_time: raise forms.ValidationError("Error") views.py def rent_car(request): if request.method == 'POST': form = RentForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: form = RentForm(request.POST) return render(request, 'rent.html', {'form': form) Unfortunetaly I had an error 'unsupported operand type(s) for -: 'NoneType' and 'NoneType'. Please help me solve the problem -
how to make complete django tables(update, delete,search) with (django_tables2)?
friends ... i'm new in django framework i show my table in django_tables2 and i want edit and search and delete from this table so i have no idea how and what i can do ?? can you help me please this is my tables.py import django_tables2 as tables from .models import Immob class ImmobTable(tables.Table): id = tables.Column(verbose_name= 'ID') immo_code=tables.Column(verbose_name='Code') immo_desig=tables.Column(verbose_name='Désignation') immo_qte=tables.Column(verbose_name='Quantité ') immo_datemes=tables.Column(verbose_name='Date mes ') immo_cptimmob=tables.Column(verbose_name='Compte comptable ') immo_dureevie=tables.Column(verbose_name='Durée de vie ') immo_origine=tables.Column(verbose_name='Origine ') immo_fournisseur=tables.Column(verbose_name='Fournisseur ') immo_nufact=tables.Column(verbose_name='N° facture ') immo_datefact=tables.Column(verbose_name='Date facture ') immo_valht=tables.Column(verbose_name='Valeur HT ') immo_monaie=tables.Column(verbose_name='Monnaie ') immo_tauxcvt=tables.Column(verbose_name='Taux de conversion ') immo_tauxctrval=tables.Column(verbose_name='Contre valeur/DA ') immo_frais=tables.Column(verbose_name="Frais d'approche ") immo_coutacq=tables.Column(verbose_name= "Cout total d'acquisition ") immo_refcmde=tables.Column(verbose_name='Référence commande ') immo_datecmde=tables.Column(verbose_name='Date commande ') immo_journee=tables.Column(verbose_name='Numéro de journée ') immo_cptanal=tables.Column(verbose_name='Compte Analytique') immo_local=tables.Column(verbose_name='Localisation ') immo_mode_amort=tables.Column(verbose_name= "Méthode d'amortissement ") immo_code_r=tables.Column(verbose_name= "Dernier plan d'amortissement ") immo_val_amort=tables.Column(verbose_name="Valeur à amortir ") immo_status=tables.Column(verbose_name='Code status') immo_code_bar=tables.Column(verbose_name='Code à barre ') service=tables.Column(verbose_name='Service ') cni=tables.Column(verbose_name='Code cni ') class Meta: model = Immob template_name ="django_tables2/bootstrap-responsive.html" -
How transfer a string (not from form) from HTML page to the server?
I'm doing the task about creating web-project "library". When you are on the main page, you can see list of all the library users. If you press on any of the users' name, the another page with list of user's books will open. And this task became a problem for me: I don't know how server can get the string with user's name from the main page. I thought about ajax, but I guess it works only for forms. And I don't want to turn my text list into form. It seems to be not optimal decision. Please tell me if there any any ways to do it? I will be grateful for any advice. -
Django heroku server : how to solve the responses' 30 seconds limit?
I work on a Django application which is an online newspaper. This app contains an administration that allows editors to write articles, etc... Sometimes, editors have to upload large pdf files, which are compressed and sent around the world on some CDN servers. The problem is that if pdf are too large, the responses takes more than 30 seconds to be returned and the server returns a H12 error. The documentation says that if just one bit is sent to the client during the loading, the limit is restarted to 55 seconds (https://devcenter.heroku.com/articles/limits#http-timeouts). So I have done this in my Django app : pool = Pool(processes=1) import time def my_generator(): response = pool.apply_async(handle_creation, (request.POST, request.FILES, node_model, node_model_name, available_objects_dict)) while True: if response.ready(): if response.successful(): yield "ready" break time.sleep(3) yield "pong" return StreamingHttpResponse(my_generator()) When I run this script on my local server, all works good, but on the heroku server the H18 error is raised. Have you idea to solve it ? -
Fielderror when doing make html in Sphinx of Django project
I'm trying to perform make html of Sphinx for my event management website built using django. My project runs perfectly fine when I do python3 manage.py runserver so I cannot fathom why this fielderror is occuring. If there was an error how is the website running then? How do I fix this error and perform make html Running Sphinx v1.8.5 Configuration error: There is a programmable error in your configuration file: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/sphinx/config.py", line 368, in eval_config_file execfile_(filename, namespace) File "/usr/local/lib/python2.7/dist-packages/sphinx/util/pycompat.py", line 150, in execfile_ exec_(code, _globals) File "/home/afsara/.local/lib/python2.7/site-packages/six.py", line 709, in exec_ exec("""exec _code_ in _globs_, _locs_""") File "<string>", line 1, in <module> File "/home/afsara/Desktop/EventManagement_with_django_merged/EventManagement/docs/conf.py", line 23, in <module> django.setup() File "/home/afsara/.local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/afsara/.local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/afsara/.local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/afsara/Desktop/EventManagement_with_django_merged/EventManagement/reg_group/models.py", line 6, in <module> class User(AbstractUser): File "/home/afsara/.local/lib/python2.7/site-packages/django/db/models/base.py", line 254, in __new__ 'base class %r' % (field.name, name, base.__name__) FieldError: Local field 'email' in class 'User' clashes with field of similar name from base class 'AbstractUser' Makefile:19: recipe for target 'html' failed make: *** [html] Error 2 -
How to use UserViewSet in djoser 2.0.3?
I am new to Djoser and I am struggling to use the functions UserView, UserViewCreate, UserViewDelete to update,create and delete users. The code I am using currently in url_patterns is: from django.conf.urls import re_path from djoser import views as djoser_views urlpatterns = [ re_path(r'^user/view/$', djoser_views.UserView.as_view(), name='user-view'), re_path(r'^user/delete/$', djoser_views.UserDeleteView.as_view(), name='user-delete'), re_path(r'^user/create/$', djoser_views.UserCreateView.as_view(), name='user-create'), ] When I use UserView, I am getting the error as : AttributeError: module 'djoser.views' has no attribute 'UserView' I read the djoser documentation and saw that: UserCreateView, UserDeleteView, UserView, PasswordResetView,SetPasswordView, PasswordResetConfirmView, SetUsernameView, ActivationView, and ResendActivationView These functions have all been removed and replaced by appropriate sub-views within UserViewSet. I searched but couldn't find any way to use UserViewSet. Is there any way to use UserViewSet in djoser 2.0.3? -
Automatic field creation on form submission
I am writing a simple blog app and I'm currently in the position where I need to implement comments on a blog post. So, I have two models: from django.db import models from django.shortcuts import reverse # Create your models here. class Article(models.Model): title = models.CharField(max_length=120) author = models.CharField(max_length=50) content = models.TextField() date = models.DateField(auto_now=True) def get_absolute_url(self): return reverse('articles:article-detail', kwargs={'id': self.id}) class Comment(models.Model): author = models.CharField(max_length=50) content = models.TextField() date = models.DateField(auto_now=True) post_id = models.IntegerField() and a ModelForm: from django import forms from .models import Article, Comment class CommentModelForm(forms.ModelForm): class Meta: model = Comment fields = [ 'content', 'author', ] ...when I submit the form, I want my Comment's post_id field to be automatically generated and correspond to my Article's id, i.e. the comment should be located on the page where it was submitted. Here is my views.py: def article_detail_view(request, id): obj = get_object_or_404(Article, id=id) comments = Comment.objects.filter(post_id=id) comment_form = CommentModelForm(request.POST or None) if comment_form.is_valid(): comment_form.save() comment_form = CommentModelForm() context = { 'object': obj, 'comments': comments, 'comment_form': comment_form } return render(request, 'articles/article_detail.html', context) Any ideas how can I do that? -
Aggregate correct values in view to pass as Django context to template
I am trying to pass the correct html content as context to the template. First I have the follow queryset results: <QuerySet [{'name': 'Gemäldegalerie Alte Meister', 'id': 1, 'piece_type': 'painting', 'count': 1}, {'name': 'Isabella Stewart Gardner Museum', 'id': 2, 'piece_type': 'painting', 'count': 1}, {'name': 'Kunsthistorisches Museum', 'id': 3, ' piece_type': 'painting', 'count': 1}, {'name': 'National Gallery of Art', 'id': 4, 'piece_type': 'painting', 'count': 3}, {'name': 'National Gallery of Art', 'id': 4, 'piece_type': 'sculpture', 'count': 1}, {'name': 'The Frick Collection', 'id': 5, 'piece_type': 'painting', 'count': 2}]> I'd like to pass from view to template with a context in the form of: context: 'name_official', 'id' and 'html excerpt' html excerpt for the Gallery of Art would be in the form of: <h2>Gallery of Art</h2><p>3 paintings</p><p>1 sculpture</p> How would I generate this context data? -
How to fix "Iterators should return strings, not bytes" in Django File Upload
I'm trying to add an option to upload CSV files for one of my models in my Django App. I followed this tutorial to set it up but couldn't get it working. When uploading the file I get the following error: "_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)" This is a sample of the file I'm trying to upload: https://pastebin.com/DMyudHav I have already tried the following answers: How can I handle the error "expected str, bytes or os.PathLike object, not InMemoryUploadedFile' in Python or Django? Getting a TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile My code looks like this right now: import csv ... class AttendantsCSVForm(forms.Form): event = forms.ModelChoiceField(queryset=Event.objects.all(), required=False) csv_file = forms.FileField() class PersonAdmin(admin.ModelAdmin): def import_csv(self, request): if request.method == 'POST': form = AttendantsCSVForm(request.POST, request.FILES) if form.is_valid(): event_id = request.POST.get('event') csv_file = request.FILES['csv_file'] reader = csv.reader(csv_file) for row in reader: # the error occurs here for text in row: print(text) self.message_user(request, _('CSV file imported successfully.')) form = AttendantsCSVForm() payload = {'form': form} return render(request, 'admin/attendants_csv_form.html', payload) How can I solve this? I've also read python's csv documentation but still can't find a solution to this problem. I'm running the … -
Even if username is not alphabetic or specified characters, it can be entered in various characters
When registering an account, usernames can be entered in various characters other than alphabets or specified characters. I want to restrict the character to use username in URL, but I don't know how. I also thought that there was a limitation when I checked the document, but I thought it might not be applicable. I want to know the cause. class User(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() user_id = models.UUIDField(default=uuid_lib.uuid4, primary_key=True, editable=False) username = models.CharField(_('username'), unique=True, max_length=50,validators=[username_validator],error_messages={ 'unique': _("A user with that username already exists."), },) class SignUp(generic.CreateView): """account""" template_name = "accounts/signup.html" form_class = forms.SignUpForm success_url = reverse_lazy('') def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) domain = current_site.domain context = { 'protocol': self.request.scheme, 'domain': domain, 'token': dumps(user.pk), 'user': user, } subject = render_to_string('mail/create/subject.txt', context) message = render_to_string('mail/create/message.txt', context) send_mail(subject , message, 'an@apasn.com', [user.email], fail_silently=False) # user.email_user(subject, message) return redirect('accounts:signupdone') class SignUpForm(forms.ModelForm,UserCreationForm): class Meta: model = User fields = ('email','username') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' def clean_email(self): email = self.cleaned_data['email'] User.objects.filter(email=email, is_active=False).delete() return email -
DateTimeField not saving the Time and Date DJANGO2.1
I have tried countless times different approach to save and TIME and DATE using DateTimeField but DJANGO2.1 keep throwing a template error enter a valid date/time models.py class Party(models.Model): name = models.CharField(max_length=50) date = models.DateTimeField() forms.py class PartyForm(forms.ModelForm): name = forms.CharField() date = forms.DateTimeField(widget=forms.widgets.DateTimeInput(format=['%Y-%m-%d %H:%M'], attrs={'class':'myDateClass', 'type':'datetime-local'})) class Meta: model = Party fields = ['name', 'date'] Also, when i try to use input_formats below: date = forms.DateTimeField(widget=forms.widgets.DateTimeInput(input_formats=['%Y-%m-%d %H:%M'], attrs={'class':'myDateClass', 'type':'datetime-local'})) The terminal throw the error below: File "/Users/macadmin/Documents/Django_fun4/date_and_time/date_time/core/forms.py", line 30, in PartyForm attrs={'class':'myDateClass', 'type':'datetime-local'})) TypeError: __init__() got an unexpected keyword argument 'input_formats' Can anybody help me figure out how to save the TIME and DATE. (Time is the most important data i need right now but if i can save both TIME and DATE it would be great) Thank you for your help in advance. -
visual studio code unresolved import?
I have installed python version 3.7 and visual studio code latest version, after that i have created virtual environment and installed django and created Django project. Whenever i am opening some file, its showing error like below unresolved import 'django.contrib' unresolved import 'django.urls' Undefined variable: 'path' Undefined variable: 'admin' Below are the paths of my application 1) Python : C:\Python\Python37-32\python.exe 2) Virtual environment created D:\django_projects\envs\py1\ 3) Django Project created D:\django_projects\p1\p1 Below are the things i have tried 1) Re Installing Python 2) Setting the Python Path in environment variable even i selected include in the path at the time of python installation 3) Re installing the VS Code 4) Tried commenting the "python.jediEnabled": false, in settings.json file in vs code, but it was giving different error unable to import django. 5) unresolved import 'django.contrib' unresolved import 'django.urls' Undefined variable: 'path' Undefined variable: 'admin' -
how to keep html code with chart js script in the same file to work
im trying add chartJs to my project but the problem is i cant keep the html code <canvas id="myChart" width="400" height="400"></canvas> with the script code in one file {% block body %} <canvas id="myChart" width="400" height="400"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for i in products %}'{{i.product}}',{% endfor %}], datasets: [{ label: '# of Votes', data: [{% for i in products %}'{{i.price}}',{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" type="text/javascript"></script> the error provide is Uncaught ReferenceError: Chart is not defined class Lists(ListView): template_name = 'charts.html' context_object_name = 'products' pass i also tried to to make a separate js file to the script but it provided Uncaught SyntaxError: Unexpected token % and when i copied the script into the … -
implement DRF get_queryset so that a bad query_param responds with an error message
I have a django model which I want to display via Django Rest framework. I am getting all objects in the model to be displayed via the get_queryset(). However, I also have a couple of query_params which will filter out certain objects. This is my main code which is working fine: class PlanView(generics.ListAPIView): """ API endpoint which allows prices to be viewed or edited """ serializer_class = PlanSerializer permission_classes = (IsAuthenticatedOrReadOnly,) # override method def get_queryset(self): //get all objects in Plan model queryset = Plan.objects.all() // possible query parameters to be read from url size = self.request.query_params.get("size", None) price = self.request.query_params.get("price", None) if size is not None: if size == "large": queryset = queryset.filter(Large=True) elif size == "small": queryset = queryset.filter(Large=False) if price is not None: queryset = queryset.filter(price=price) return queryset with this urlpattern: path(r'API/plans', views.PlanView.as_view(), name='prices'), The only problem is that when I purposefully write the below URL in a browser, http://127.0.0.1:8000/API/plans?size=sm which has a bad/misspelled query_param value, the get_query() code will just ignore it and display the objects as if there are no filters. I tried to put an else statement such as: if size is not None: if size == "large": queryset = queryset.filter(Large=True) elif size == … -
How to get and save data of the nearest element in page in python django
I need to add comment module on my homepage in django python - simple textarea under each post. I need to get the nearest post id before i save it in my form, that my comment knows to which post is related. My views.py def home(request): newPostForm = newPost() newCommentForm = newComment() if request.is_ajax(): newPostForm = newPost(request.POST) newCommentForm = newComment(request.POST) if newPostForm.is_valid(): instance = newPostForm.save(commit=False) instance.author = request.user instance.date_posted = timezone.now() instance.save() data = { 'message': 'post is added' } return JsonResponse(data) if newCommentForm.is_valid(): instance = newCommentForm.save(commit=False) instance.author = request.user instance.date = timezone.now() instance.save() data = { 'message': 'comment is added' } return JsonResponse(data) context = { 'newPostForm': newPostForm, 'newCommentForm': newCommentForm, 'posts': Post.objects.all().order_by('-date_posted'), 'comments': Comment.objects.all().order_by('-date_posted') } and my home.html <div class="leftcolumn"> <div class="new_post_form"> <form METHOD="POST" class="new_post" id="new_post"> {% csrf_token %} {{ newPostForm }} <button type="submit">Publish</button> </form> </div> <div id="posts"> {% for post in posts %} <div class="container"> <a class="user" href="#">{{ post.author }}</a>, {{ post.date_posted }} <img src="{{ post.author.profile.image.url }}" alt="{{ post.author }}" style="width:100%;"> <p>{{ post.content }}</p> {% for comment in post.comments.all %} <div class="comment"> <p>{{ comment.content }}</p> <form METHOD="POST" class="new_comment" id="new_commentt"> {% csrf_token %} {{ newCommentForm }} </form> </div> {% endfor %} </div> {% endfor %} </div> </div> I don't … -
n:m relation table foreign key column unique
i have 2 tables Pool table pid(PK) Problem table number(PK) | name | submit | accept and also have n to m relation table PoolProblem PoolProblem pid(FK from Pool table) | number(FK from Problem table) if i insert tuple in PoolProblem like this, 1 | 1 1 | 2 1 | 3 2 | 2 << i want to show error this line, because number fk is duplicated on entire table. i tried ManyToMany relation, set unique constraint at number column(but error,,,) how can i solve it? -
How to select only one row for one user in django?
I have a message database and it has senderid, receiverid, message and date. Now I would like to get list of users whom I have recently messaged with one latest message (sent or received) per person. How can I get just a single row of message per person. I tried but this game me all the messages between two users, I just want the latest message. querySet=MessageModel.objects.filter( Q(sUser=self.request.user) | Q(rUser=self.request.user) ) return querySet but this game me all the messages between two users, I just want the latest message. -
Django doesn't serve images because Debug is set to True - how can I make nginx serve those?
So I'm just deploying my second website. I have a static location with css, js files and everything works alright. Now I just realised that I also have some images uploaded by the users. Here is the model: photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_7 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_8 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_9 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) The problem is that when I try to access those images with DEBUG set to True, I get this Not Found The requested resource was not found on this server. I found on the internet that setting Debug to True makes django not serve the files anymore. So I have to configure nginx to serve those. How can I do that? I have to make it also serve the default /static/ folder, and these photos which don't have a fixed name. (%Y/%m/%d). The absolute path would be something like /etc/USERNAME/main-website/media/photo/%Y/%m/%d. Here is my nginx file from sites-enabled. server { server_name bestdavnic73.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/octavian56/main-website; } location / { include proxy_params; proxy_pass http://unix:/home/octavian56/main-website/bestDAVNIC73.sock; } listen 443 … -
How to realize registration via Facebook in django?
I have my API and here I developed registration view. Now I want to realize registration via facebook, idk how to do it correct. Where i can find some good example(i'm interested only backend part)? -
how can I filter a field list values whenever I change another field value?
I have 3 models Category, Subcategory, and Product I registered them on the Django admin, in the add product admin page I need the subcategories list to be filtered based on the category value I choose. right now the subcategory list shows all subcategories, I need when I choose the category A to have only the subcategories that are related to Category A. Category Model class Category(models.Model): name = models.CharField(max_length=200, db_index=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Subcategory Model class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategories', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Product Model class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, related_name='products', on_delete=models.CASCADE) -
HTML select multiple values from styled list with checkboxes
I have a django project with a list of users that I want to include in a post request. Note that only the users that I have checked should be included in the post request in the django function based view. I wonder how I can get the value of the checked users into the django post request function based view? Its not exactly like in this picture but the checkbox and the user part Is the same, I couldn't find out how to put a local file into stack overflow! The Project Page: @login_required def projectPage(request): obj = Project.objects.filter(canview__user=request.user) assignments = Assignment.objects.filter(canview__user=request.user) allstudents = UserProfile.objects.all() username = request.user context = { 'object': obj, 'MyName': username, 'Assignments': assignments, 'students': allstudents } return render(request, 'allProjects.html', context) The POST REQUEST Page: @login_required def create_project(request): if request.method == 'POST': name = request.POST.get('Project-Name') description = request.POST.get('Project-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Project-ParentAssignmentID')) membersInProject == SOMETHING project = Project(name=name, description=description, parent_assignment=parent_assignment, members = membersInProject) project.save() return redirect('allaStudieplaner') In The HTML template: {% for student in students %} <div class="custom-control custom-checkbox"> <span class="d-flex align-items-center"> <div style="margin-right: 10px"> <div class="circle"> <span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }} </span> </div> </div> <div style="width: 300px"> <span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span> </div> <div … -
Using select_related in add/edit django admin for single field
I need to resolve the N+1 problem. Below is my model: class Work(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(null=True, blank=True) book = models.ForeignKey('Chapter', on_delete=models.CASCADE) job = models.ForeignKey('Job', on_delete=models.CASCADE) user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=True, blank=True) prev_work = models.ForeignKey('self', on_delete=models.CASCADE, editable=False, null=True, blank=True) And now I overrided get_queryset in my ModelAdmin. It works great in List View but when I want to add new element it makes multiple queries because of the "book" field. So how can I override sql for SINGLE field. To be specific, it makes so many queries because in my model file I have this: def __str__(self): return self.book.project.slug + "-" + str(self.book.number) + "-" + self.job.name and there are many books and many projects. -
Including a list view with inclusion tag
I've a list view function (searchview) that I want to include to my template home page with the help of the inclusion tag, please how do I get around this... Thanks in anticipation -
getting the counts and values of foreignkeys relations with query
hi my models are like this and i'm using mysql class UserChannel(models.Model): ... channel = models.ForeignKey(Channel) user_entry_date = models.IntegerField() channelName = models.ForeignKey(ChannelName) is_verified = models.BooleanField(default=False) users = Fk ... class Channel(models.Model): ... name = models.CharField() is_active = models.BooleanField(default=True) class ChannelName(models.Model): ... channel = models.ForeignKey(Channel,) channel_name = models.CharField() i have to show differnt UserChannels and thier counts based on distinct Channel and ChannelName of a range of time which is timestamp (its something like a logging system) right now i am getting all UserChannels of a range of time and i want to show values based on that query so far i have managed to get this done with for loops but it is very inefficient and takes a lot of time to respond channels = Channel.objects.all().values('pk', 'name') channel_names = ChannelName.objects.all().values('pk', 'channel_name') result_list = [] for query in queryset: # list of all UserChannels of a range of time res = dict() for item in channels: query_specific = query.filter(channel=item['pk']) query_is_verified = query.filter(channel=item['pk'], is_verified=True) for channel_name in channel_names: count_query_specific = query_specific.filter(channelName=channel_name['pk']).count() if count_query_specific != 0: res['count_all_specific'] += f'{item["name"]}- {channel_name["channel_name"]} : {count_query_specific}' count_query_is_verified = query_is_verified.filter(channelName=channel_name['pk']).count() if count_query_is_verified != 0: res['count_is_verified'] += f'{item["name"]}- {channel_name["channel_name"]} : {count_query_is_verified}' so i want some thing like this in … -
Django Messages show up only in admin
I have set up a django message that gets displayed when the user logs in, but the messages show up only in the admin. accounts/views.py def login_page(request): form = LoginForm(request.POST or None) context = { 'form':form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username,password=password) if user is not None: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: messages.info(request,"You are now logged in") return redirect("/") else: messages.error(request,"Something went wrong") print("Error") return render(request,"accounts/login.html", context) settings.py MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage' 'OPTIONS': { 'context_processors': [ ... 'django.contrib.messages.context_processors.messages', base.html {% if message is not None %} {% for message in messages %}{{ message }}{% endfor %}{% else %}{% endif %}