Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I count number of clicks of links in for-loop in Django template tag?
So I have a Django application, where I upload one article per day (to be more precise, I provide title and subtitle of the article as well as its link, so the user can click the link to see the whole article). I have made this using for-loop in template tag, as shown below. ... {% for item in articles %} <div class="row"> <a href="{{item.url}}" class="all-articles" target="_blank" rel="noopener noreferrer"> <div class="col"> <span class="title">{{item.title}}</span><br> <span class="subtitle"> | {{item.subtitle}}</span> </div> </a> </div> {% endfor %} ... Now I'd like to see the number of clicks of each article. But I have no idea on how to make it possible. Any idea? Thank you very much in advance. :) -
I'm working on page-nation using the page narrator, but the results are weird.(django)
I'm working on page-nation using the page narrator, but the results are wrong. There seems to be two things wrong with the results. 1.The number of posts is not 10 2.The template output is strange Two things I want to know I want to know what to send in the view. I want to know what's wrong with the code in the template Thanks for letting me know Below is the code view: if(search_option == "content+title"): print("search bycontent and title =================") page = request.GET.get('page', '1') object_list = MyShortCut.objects.filter(Q(author = user)).filter(Q(title__icontains=search_word) | Q(content1__icontains=search_word) | Q(content2__icontains=search_word)).order_by('-category') print('object_list(count) :::::: ' , object_list.count() ) # 검색 키워드 "강의"로 검색하면 39 paginator = Paginator(object_list, 10) # 페이지당 10개씩 보여주기 page_obj = paginator.get_page(page) print("page_obj ::::::::::::: ", page_obj) context = {'question_list': page_obj} return render(request, 'wm/MyShortCut_list_for_search.html', { "object_list":paginator, "question_list":page_obj }) template <!-- <table class="table table-borderd"> --> 검색 결과: <table border="1" width="100%"> <tr> <td>번호</td> <td>category</td> <td>title 22</td> <td>name</td> </tr> <tbody> {% if object_list.exists %} {% for p in object_list %} <tr> <td> {{ forloop.counter }} </td> <td> <a href="/wm/myshortcut/category/{{p.category}}/"> {{p.category}} </a> </td> <td> {{p.title}} <a href="#wm_detail_{{p.id}}" class="badge badge-dark" data-toggle="collapse">상세 보기</a> {% ifequal p.type.type_name "input" %} <br /> <input type="text" id="wm_detail_{{p.id}}" class="collapse " value="{{p.content1}}" size="100%" /> {% endifequal %} {% … -
Efficiently Saving 60K Records in database in django rest frame work
I have an endpoint (eg http://localhost:8000/api/create/) which creates new record in mysql db with django rest framework class CreateItem(viewsets.ModelViewSet): . . . def perform_create(self, serializer): if serializer.is_valid(): serializer.save() Now i have a requirement that, 60K request will be made in this endpoint with the help of script. How can i handle it most efficiently, which will take less time and resource. I read about Django atomic and celery task but completely confused how to make use of it for this requirements. Any help will be greatly appreciated Thanks in advance -
How to assign and manage a priority mechanism
I am working on a Django web application where users create a list of tasks. Each task is a record in the database (ie: a Django object) and the user is able to assign each task a priority. If the user creates 10 tasks, each of them would have a priority from 1 to 10. I'm struggling to figure out an efficient way to allow users to change the priority of tasks as well as insert and delete tasks. For example: A user moves task priority 3 down to 7. The other tasks priorities need to be adjusted accordingly. A user deletes task with priority 4. Once again the remaining tasks priorities would need to be adjusted. A user inserts a new task with priority 5. This means the existing tasks from priority 5 onwards need to be shifted. Are there any design patterns or suggestions on how to manage what essentially amounts to a queue based on the priority of each item while allowing users to: Move tasks up and down the priority list Delete tasks Add new tasks with specified priorities. -
How to filter by field name in model manager (NameError)
models.py class StudentProfile(models.Model): student = models.OneToOneField( User, related_name='student', primary_key=True, parent_link=True, on_delete=models.CASCADE) membership_end = models.DateTimeField( verbose_name="Membership End Date", default=now, editable=False) objects = StudentProfileManager() managers.py class StudentQuerySet(models.QuerySet): def get_student_chat_list(self): return self.filter(membership_end >= datetime.Now()).values_list('student_id', 'chat_user_sid') class StudentProfileManager(models.Manager): def get_queryset(self): return StudentQuerySet(self.model, using=self._db) def get_student_chat_list(self): return self.get_queryset().get_student_chat_list() This should have a very simple explanation, but I don't understand what's wrong here. I'm getting the following error: NameError: name 'membership_end' is not defined -
Is there a way i can pass data from a django template to a class based session wizard view in Django
I have a project in which i am required to pass data from a template to be accessed in a class. However i am unable to achieve this. i only know how to do it in a function based view but not in a class based view (sessionwizard view to be specific). <div class="time"><i class="fa fa-clock-o bg-red" ></i><h style='color:red'> <a class='article' href="{% url 'account:print_pdf' advert=vacancy.advert %}">Recruit </a></h> </div> Above is my template snippet which takes a variable advert. path('apply/<str:advert>',views.FormWizardView.as_view([Vacancy,Personal,Academic,Other]),name='apply')) This is a snippet of my url.py file whick points the advert to the form wizard view class Finally we have the form wizard view class that is expected to take the variable advert. @method_decorator([applicant_required], name='dispatch') class FormWizardView(SessionWizardView,advert): template_name = "done.html" file_storage =DefaultStorage() form_list = [Vacancy,Personal,Academic,Other] @property def __name__(self): return self.__class__.___name__ def get_context_data(self,form,**kwargs): user=self.request.user msg = Post_vacancy.objects.filter(end__gte=datetime.now().date()) u = User.objects.get(username=user) context=super(FormWizardView,self).get_context_data(form=form,**kwargs) context.update({'msg':msg,'u':u}) return context def done(self, form_list,form_dict, **kwargs): user=self.request.user self.urlhash = id_generator() while Application.objects.filter(uid=self.urlhash).exists(): self.urlhash = id_generator() x=[form.cleaned_data for form in form_list] print(advert) vacancy=x[0]['vacancy'] tsc_no=x[0]['tsc_no'] duration=x[0]['duration'] uid=str(vacancy) + self.urlhash surname=x[1]['surname'] m_name=x[1]['m_name'] l_name=x[1]['l_name'] id_no=x[1]['id_no'] image_id=x[1]['image_id'] institutionA=x[2]['institutionA'] award=x[2]['award'] kcse=x[2]['kcse'] image_cert=x[2]['image_cert'] image_certKC=x[2]['image_certKC'] break_in=x[2]['break_in'] co_curriculum=x[3]['co_curriculum'] image_co=x[3]['image_co'] leadership=x[3]['leadership'] image_lead=x[3]['image_lead'] When i do it as above i recieve an error indicating that advert argument is missing... this … -
Error : Select a valid choice. That choice is not one of the available choices
I am creating a blog using Django. I want my author to be auto-selected in the author's box. Actually the box is getting correctly filled by javascript but when I submit the form it shows "Select a valid choice. That choice is not one of the available choices." But I have provided it a TextInput Field. It works well when instead of TextInput, Select is provided to the author. But I don't want to let the author select I want it to get filled by the first_name who is logged in. please somebody help I trying this for 4 days. Forms.py from django import forms from .models import Post, Category from django.contrib.auth.models import User # choices = [('coding','coding'),('entertainment','entertainment'),('sports','ssports')] choices = Category.objects.all().values_list('name','name') choice_list = [] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag','author','category', 'body', 'snippet') widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'title_tag': forms.TextInput(attrs={'class':'form-control'}), 'author': forms.TextInput(attrs={'class':'form-control', 'id':'gauname','value':'','type':'hidden'}), # 'author': forms.Select(attrs={'class':'form-control'}), 'category': forms.Select(choices=choice_list,attrs={'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control'}), 'snippet': forms.Textarea(attrs={'class':'form-control'}), } views.py class AddCategoryView(CreateView): model = Category form_class = AddCategory template_name = 'add_category.html' # fields = '__all__' models.py class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) # body = models.TextField() body = RichTextField(blank=True, null=True) … -
How to change current_site in view in django
I want to have users initiate a login from a root URL and then get the site user belongs to and finish authentication and route the user to that site. I tried to do so with the following: employee = Employee.objects.get(user__username=username) request.current_site = employee.site user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('https://'+employee.site.domain) I get the error: 'WSGIRequest' object has no attribute 'current_site' How can I change the current_site, since that site doesn't have the user I want to authenticate? -
How to limit data in html using django template?
I am using bootstrap carousel and i am using for template to iterate through data but i want two data at once so i wanted to do was if data exceeds 2 i want to display nothing after that can some one tell me how to do it. <section id="latest-trip"> <div class="container"> <div class="row col-md-12"> <!-- Latest trip left part(carousel part) Start --> <div id="treaking-list" class="col-md-7 ml-4"> <div id="carouselExampleIndicators-three" class="carousel slide" data-ride="carousel" > <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators-three" data-slide-to="0" class="active" ></li> <li data-target="#carouselExampleIndicators-three" data-slide-to="1" ></li> <li data-target="#carouselExampleIndicators-three" data-slide-to="2" ></li> </ol> <div class="carousel-inner"> {% for tour in tours %} <div class="carousel-item {% if tour.id == 1 %} active {% endif %}"> <div class="row"> {% for tour in tours %} <div class="treaking col-md-6"> <img src="{{tour.image}}" alt="Real Adventure Nepal - {{tour.tour_name}}" title="{{tour.tour_name}}" /> <div class="treaking-head"> <h3>{{tour.tour_name}}</h3> <p> {{tour.description}} </p> </div> </div> {% endfor %} </div> </div> {% endfor %} </div> </div> </div> <!-- Latest trip left part(carousel part) End --> <!-- Latest trip right part(Description part) Start --> <div class="col-md-4 ml-5 title"> <h2 class="treaking-title">Latest Trips</h2> <span class="right-styled-para">Explore the unexplored world</span> <p class="treaking-description"> Lorem ipsum dolor sit amet consectetur adipiscing elitsed do eiusmod tempor incididunt utlabore et dolore magna aliqua. Utenim ad minim veniam quiso. … -
ModuleNotFoundError: No module named 'apps.endpointsapps'
I am very new to python and linux, I was trying to create an app from a tutorial and this happend when I tried to run a test of my model. (venv) kali@kali:~/machinelearning/backend/server$ python manage.py test apps.ml.tests Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/kali/machinelearning/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/kali/machinelearning/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/kali/machinelearning/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kali/machinelearning/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/kali/machinelearning/venv/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'apps.endpointsapps' This is my first question on stackoverflow too -
Mypy: Returning Any from function declared to return "str" in django form methods
In every Django form method I try to return a str or other type and I obtain: error: Returning Any from function declared to return "str" return password2 ^ forms.py class UserAdminCreationForm(forms.ModelForm): def clean_password2(self) -> str: password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") passwords = password1 and password2 passwords_not_match = password1 != password2 if passwords and passwords_not_match: raise forms.ValidationError("Passwords don't match") return password2 Unique solution acepted for mypy is to change the str method for Any type, there is a reason to obtain this error or a way to solve it? the only way I've been able to silence this mistake class UserAdminCreationForm(forms.ModelForm): def clean_password2(self) -> Any: password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") passwords = password1 and password2 passwords_not_match = password1 != password2 if passwords and passwords_not_match: raise forms.ValidationError("Passwords don't match") return password2 mypy configuration in setup.cfg [mypy] python_version = 3.8 ignore_missing_imports = True show_column_numbers = True pretty = True warn_unused_ignores = True warn_redundant_casts = True warn_return_any = True warn_unused_configs = True warn_unreachable = True warn_no_return = True disallow_any_unimported = True disallow_any_generics = True disallow_subclassing_any = True disallow_untyped_calls = True disallow_untyped_defs = True disallow_incomplete_defs = True check_untyped_defs = True disallow_untyped_decorators = True strict_optional = True no_implicit_optional = True strict_equality = True … -
Django view order history
I'm working on a function where admin can click on the username of a customer and view the customer's order history. So far I'm only able to view all orders of a user that is logged in. views.py def order_history(request, user): order_qs = Order.objects.filter(user=user) context = { 'order_qs': order_qs, } return render(request, "order_history.html", context) order_history.html {% for order in order_qs %} {{ order.user }} {{ order.id }} {% endfor %} user_list.html {% for Order in order %} <tbody> <tr> <td><a href="{% url 'accounts:order-history' user.id %}">{{ Order.user }}</a></td> </tr> </tbody> {% endfor %} -
Django, managing debug flag in settings.py
Say you have base_settings.py debug_settings.py product_settings.py in debug_settings.py DEBUG = True from base_settings import * in product_settings.py DEBUG = False from base_settings import * in base_settings.py # this condition check is problamatic, I don't think I can define DEBUG variable outside of `base_settings.py` ? if DEBUG: foo() How do you have a common base_settings.py which has conditional code dependant on variable (DEBUG) whose value can be changed from the importing module? (from debug_settings, product_settings) -
Django loop display
I am doing a modal in Django for person detail and is all in a loop, but I am getting only the first person from the list in modal even if I click on a different person. It could be my loops but can't think clearly. Example: <tbody> {% if orders %} {% for order in orders %} <tr> <th scope="row">{{order.order_id}}</th> <td>{{ order.product |capfirst }}</td> <td>{{ order.units}}</td> <td>{{ order.quantity}}</td> <td>{{ order.date}}</td> <td>{{ order.supplier}}</td> <td><button type="button" class="btn btn-link" data-toggle="modal" data-target="#exampleModal">{{order.user}}</button></td> </tr> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">{{ order.user }}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p><em>{{ order.user.position }}</em></p> <p><em>{{ order.user.email }}</em></p> <p><em>{{ order.user.dob }}</em></p> <p><em>{{ order.user.phone }}</em></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-dark" data-dismiss="modal">Ok</button> </div> </div> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <h2>There are no orders.</h2> </div> {% endif %} </tbody> Example: I have clicked on Dan Jink but I got Martin Lawrence Thanks in advance! -
Difference in using __icontains and lowercasing the query?
Is there any difference in performance if I lower case the query before going to use __contains or directly using __icontains. In code: This def search(request): query = (request.GET.get("q")).lower() if query: users = User.objects.filter(location__contains=query) VS def search(request): query = request.GET.get("q") if query: users = User.objects.filter(location__icontains=query) I lowercased the location while inserting it into database. And, query is the query which can be in any cases. Feel free to ask!!! -
Record Clicks on Modal Toggle
I have a page that catalogues media (think similar to an instagram page). The media is viewable on modals, and I'd like to record a "view count" for each piece of media. So whenever the modal containing that media is toggled open, it records a view. This is a simplified version of my code: <button data-toggle="modal" data-target="media-number-999">Click to view Media 999!</button> <div class="modal" id="media-number-999">Media #999 viewable here!</div> I also have a page set up where visiting that page automatically increases the viewcount by 1, and then redirects elsewhere (using django) urls.py: path('views/<id>/', views.media_views, name="mediaviews"), views.py: def media_views(request,id): Media.objects.filter(id=id).update(views=F('views') + 1) return redirect('media_detail', id=id) The reason I'm doing this is so that I can then reference the viewcount in the database to use for sorting/filtering/etc. How can I make a button that both opens the modal, and also records a visit to /views/999/ ? Also open to alternative approaches if there are better ways! I've tried to figure out how to use Ajax to do this but haven't had any luck. Thanks! -
Django website deployed on heroku does not work
I created a django website and was trying to deploy it to heroku. I followed this tutorial and did everything he did but i'm getting these errors in the logs 2020-07-10T02:06:01.015381+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bibhulamichhane.herokuapp.com request_id=9efff235-77f8-41e8-bc9e-9f80bd2b6aa1 fwd="172.98.86.231" dyno= connect= service= status=503 bytes= protocol=https 2020-07-10T02:06:01.743381+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bibhulamichhane.herokuapp.com request_id=bf2f44a0-8f5c-4e63-a1c9-e16a33761803 fwd="172.98.86.231" dyno= connect= service= status=503 bytes= protocol=https my procfile has these contents web: gunicorn website.wsgi --log-file - my requirements.txt includes these asgiref==3.2.3 Django==2.1.7 pytz==2019.3 sqlparse==0.3.0 SQLAlchemy==1.3.9 psycopg2==2.8.4 Jinja2==2.10.3 gunicorn==20.0.4 Can someone explain what these error means and how to fix them or you could also reply with a link to a video or documentation you used to deploy your website and worked -
Render Jinja String While Keeping Linebreaks in Django
I have a jinja string (I set it to be "my_string": "My name is<br>John!") rendered in a Django template: {{ my_string }} When rendered, it shows this in the html page: My name is<br>John! However, I want the line break to actually cause a line break, like this: My name is John! What do I need to do differently? Thanks!! -
How do I add a required field to a model that I didn't write?
I'm using Django 3, Python 3.7, and the django-address module -- https://github.com/furious-luke/django-address . I would like to indicate that the State field of the Locality model is required. Since I didn't write the model myself, I'm not quite sure how to do that. I created the below serializer ... class LocalitySerializer(serializers.ModelSerializer): class Meta: model = Locality fields = ['id', 'name', 'postal_code', 'state'] def to_representation(self, instance): rep = super().to_representation(instance) rep['state'] = StateSerializer(instance.state).data return rep def create(self, validated_data): """ Create and return a new `Locality` instance, given the validated data. """ return Locality.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Locality` instance, given the validated data. """ instance.name = validated_data.get('name', instance.name) instance.postal_code = validated_data.get('postal_code', instance.name) instance.state = validated_data.get('state', instance.name) instance.save() return instance but when I run a test through my serializer (below), @pytest.mark.django_db def test_coop_create_with_no_state(self): """ Test coop serizlizer model """ name = "Test 8899" coop_type_name = "Library" street = "222 W. Merchandise Mart Plaza, Suite 1212" city = "Chicago" postal_code = "60654" enabled = True postal_code = "60654" email = "test@example.com" phone = "7739441422" web_site = "http://www.1871.com" serializer_data = { "name": name, "types": [ {"name": coop_type_name} ], "addresses": [{ "formatted": street, "locality": { "name": city, "postal_code": postal_code, "state": … -
Docker: How do I use access a service that's in another container from the frontend?
I'm running a RESTful Django project on port 8000 and React project on port 3000. For development I've had all my urls on the frontend as href='localhost:8000/api/name' or href='localhost:8000/api/address'. Now that i'm going into production, I want my href's to be href='mysite.com/api/name' or href='mysite.com/api/address'.I can't figure out how to do this.How do I access my RESTful data which is on another container? I found this article but don't think its correct for production. docker-compose.yml version: "3.2" services: backend: build: ./backend volumes: - ./backend:/app/backend ports: - "8000:8000" stdin_open: true tty: true command: python3 manage.py runserver 0.0.0.0:8000 depends_on: - db - cache links: - db frontend: build: ./frontend volumes: - ./frontend:/app #One-way volume to use node_modules from inside image - /app/node_modules ports: - "3000:3000" environment: - NODE_ENV=development - CHOKIDAR_USEPOLLING=true depends_on: - backend tty: true command: npm start db: image: mysql:latest command: --default-authentication-plugin=mysql_native_password volumes: - "./mysql:/var/lib/mysql" - "./.data/conf:/etc/mysql/conf.d" ports: - "3306:3306" restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: temp MYSQL_USER: root MYSQL_PASSWORD: root volumes: mysql: {} -
Use of if statements to know if the user has created a post
I have a django project in which a user can make a post and select the category the post should be in. My current code has 2 categories('action' and 'sports') using 4 views, 1 view displays all of the categories, 1 that contains the form to upload the post and the other 2 views display just one of the categories. I want to make that all users that have made a post can see other peoples posts, if not they have to create one; this is kind of a problem since if the user types the url on the browser, the user will be able to see other people's posts even if the user hasn't create one. I know there should be some if statements on the views.py file, but I have already tried multiple ways to do this and it just still dont work. Any idea to solve this problem helps. models.py CATEGORY_CHOICES = ( ('action', 'action'), ('sports', 'sports'), ) class Mates(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True) categories = models.CharField(choices=CATEGORY_CHOICES, default="choose...", max_length=10) req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) views.py (matesmain displays all of the posts, mates_action just posts related to the action category, mates_sports just … -
Page Nation is applied to the search view, but the search results are not displayed
question: Page Nation is applied to the search view, but the search results are not displayed The contents of the view are as follows. if(search_option == "content+title"): print("search bycontent and title =================") page = request.GET.get('page', '1') object_list = MyShortCut.objects.filter(Q(author = user)).filter(Q(title__icontains=search_word) | Q(content1__icontains=search_word) | Q(content2__icontains=search_word)).order_by('-category') print('object_list(count) :::::::::: ' , object_list.count() ) paginator = Paginator(object_list, 10) # 10 per page page_obj = paginator.get_page(page) print("page_obj ::::::::::::: ", page_obj) context = {'object_list': page_obj} return render(request, 'wm/MyShortCut_list_for_search.html', { "question_list":page_obj }) The template code is: <!-- <table class="table table-borderd"> --> search result: <table border="1" width="100%"> <tr> <td>num</td> <td>category</td> <td>title 22</td> <td>name</td> </tr> <tbody> {% if object_list.exists %} {% for p in object_list %} <tr> <td> {{ forloop.counter }} </td> <td> <a href="/wm/myshortcut/category/{{p.category}}/"> {{p.category}} </a> </td> <td> {{p.title}} <a href="#wm_detail_{{p.id}}" class="badge badge-dark" data-toggle="collapse">detail</a> {% ifequal p.type.type_name "input" %} <br /> <input type="text" id="wm_detail_{{p.id}}" class="collapse " value="{{p.content1}}" size="100%" /> {% endifequal %} {% ifequal p.type.type_name "textarea" %} <br /> <textarea id="wm_detail_{{p.id}}" class="collapse" cols="100" rows="10">{{p.content2}}</textarea> {% endifequal %} {% ifequal p.type.type_name "summer_note" %} <br /> <div id="wm_detail_{{p.id}}" class="collapse" width="100%">{{p.content2 | safe}}</div> {% endifequal %} </td> <td> <a href="" onclick="change_user_for_search(this)" id={{p.author}}> {{p.author}} </a> </td> </tr> {% endfor %} {% else %} <tr> <td colspan="4"> <h4>there is no search results</h4> … -
Django run function when new instance is created/edited and have the function change a variable in the instance created/edited
I have a Django model that has a user inputted field called reserve_time. When a user enters and creates (or edits) a instance of the class I want a function to run and check if the time inputted is during dinner or lunch. I have been trying to use post_save to do this but it hasn't been working, the print statement would say if it was dinner or not but the instance of the class would not be changed at all. Also the current way I'm doing it Reservation.objects.last() only works if right if I create a new instance, not if I edit an old one. models.py: from django.db import models import datetime import operator from django.utils.timezone import now, localtime from django.db.models.signals import post_save # Create your models here. class Reservation(models.Model): shift = '' name = models.CharField(max_length=40) member_id = models.CharField(max_length=10, default="") guest_num = models.IntegerField() reserve_time = models.TimeField(default=datetime.datetime.now) notes = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return f"{self.name} at {self.reserve_time.strftime('%I:%M %p')} ({self.shift}) {self.date_created.strftime('%m/%d/%Y')}" def model_created_or_updated(sender, **kwargs): the_instance = kwargs['instance'] reservation = Reservation.objects.last() if reservation.reserve_time < datetime.time(17, 10, 0): reservation.shift = 'lunch' print('lunch') else: reservation.shift = 'dinner' print('dinner') print('model created/updated') post_save.connect(model_created_or_updated, sender=Reservation) Is there a substitute for Reservation.objects.last() that just … -
Django filter based on related set
We have following models: class House(models.Model): pass class Room(models.Model): size = models.IntegerField() We use Django Rest Framework to serialize the house and its rooms. The issue is that we want to filter the rooms by size. We have a viewset where we define the queryset: def get_queryset(): return House.objects.filter(...) things we have tried: House.objects.filter(room_set__size__gte=10) - but this gives houses with rooms larger than 10, but it does not actually filter out the rooms House.objects.filter().annotate(big_rooms=FilteredRelation('room', condition=Q(room_set__size__gte=10))) this seemed most relevant but did not have any effect :( I have also considered using .extra() but it seems it is deprecated so not great solution... I know I could use custom sql, however, we use Django rest framework filters and thus it would be quite complicated. -
Django doesn't authenticate user
I'm trying to build a login page on django. First i tried using: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth # Create your views here. def login(request): if request.method== 'POST': username = request.POST['username'] password = request.POST['password'] User = auth.authenticate(username=username,password=password) if User is not None: auth.login(request, User) return redirect("/") else: messages.info(request,'invalid credentials') return redirect('login') else: return render(request,'login.html') but i received an error saying: MultiValueDictKeyError at /accounts/login. Then i changed it to: def login(request): if request.method== 'POST': username = request.POST.get('username') password = request.POST.get('password') User = auth.authenticate(username=username,password=password) if User is not None: auth.login(request, User) return redirect("/") else: messages.info(request,'invalid credentials') return redirect('login') else: return render(request,'login.html') then only problem now is that it always shows invalid credentials even when i created new user. Help please.