Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display items grouped in month together using django regroup
I have a model with following fields examname | month a1 Jan a2 Jan a3 Jan b1 Feb b2 March b3 March I want to display exams in each month grouped in months example Jan : a1 a2 a3 Feb : b1 March: b2 b3 I am using the following queryset def getallexams(request): exams = exam.objects.annotate(month_total=Count('month')).order_by('month') print(exams) context={ "exams" : exams, } return render(request, 'exams/index.html',context) Below is the code I am using to render the template: {% regroup exams by month as month_list %} <div class="accordion" > {% for month in month_list %} {{month.grouper }} # I am not sure how to loop through this month to display each exam {% endfor %} -
django channels realtime total notification
I need realtime total number of notification using django channels. signals.py @receiver(post_save, sender=Notification) def create_notification(sender, instance, created, **kwargs): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'realtime_order', { 'type': 'notification_count', 'text': Notification.objects.all().count() } ) consumers.py class NotificationConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_group_name = None def connect(self): self.room_group_name = f'realtime_order' self.accept() # join the room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name, ) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name, ) def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'notification_count', 'message': Notification.objects.all().count(), } ) def notification_count(self, event): self.send(text_data=json.dumps(event)) Dont know is it the correct procedure. And code is not working. -
DJANGO cant navigate to page using a hyperlink but typing page address works fine
doing a simple django project with 2 apps one for blogs and the other is for users both work fine but i cant navigate using the hyperlink in this page <p> <a href="{% url 'learning_logs:home' %}">Home</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> {% if user.is_authenticated %} Hello, {{ user.username }}. <a href="{% url 'users:logout' %}">logout</a> {% else %} <a href="{% url 'users:login' }">login</a> {% endif %} urls.py in users from django.urls import URLPattern, path from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ path('login/', LoginView.as_view(template_name='login.html'), name='login'), path('logout/', views.logout_view, name='logout'), ] main urls of project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls', namespace='learning_logs')), path('users/', include('users.urls', namespace='users')), ] error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%25%20url%20'users:login'%20%7D Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='home'] topics [name='topics'] topics/<topic_id> [name='topic'] new_topic [name='new_topic'] new_entry/<topic_id> [name='new_entry'] edit_entry/<entry_id> [name='edit_entry'] users/ The current path, {% url 'users:login' }, didn’t match any of these. it shows the page if i type /users/login/ in the address bar -
Django: how to get the value inside a querydict?
I have the following querydict: <QueryDict: {'data_dict[user_id]': ['5'], 'data_dict[location]': ['Library'], 'data_dict[item_sold]': ['book']}> I want to get the value by using the key: i.e (x = data_dict.get('user_id') How can I do that? everytime I try to access the querydict it throws errors. -
Update many objects in one query DRF
I need to bulk update ("is_read" = True) Message instanses by given list of ids in one request with this code: {"ids": [11, 4, 7]} Model: class Message(models.Model): text = models.TextField(max_length=500, verbose_name=_("Text")) sender = models.ForeignKey( to=User, on_delete=models.CASCADE, related_name="sender_message", verbose_name=_("User"), ) thread = models.ForeignKey( to="Thread", on_delete=models.CASCADE, related_name="thread_message", verbose_name=_("Thread"), ) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("Created")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("Updated")) is_read = models.BooleanField(default=False, verbose_name=_("Is read")) I have this serializer: class MessageIsReadSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ("id", "text", "sender", "is_read") And method in views.py: class MessageIsRead(APIView): permission_classes = (AllowAny,) queryset = Message.objects.all() def put(self, request, *args, **kwargs): id_list = request.data['ids'] instances = [] for item in id_list: obj = self.queryset.filter(id=item) obj.is_read = True instances.append(obj) serializer = MessageIsReadSerializer(instances, many=True) return Response(serializer.data) urls.py urlpatterns = [ path("messages-read/", MessageIsRead.as_view()), ] But as a result of running this query I get an error: AttributeError at /messages-read/ Got AttributeError when attempting to get a value for field `text` on serializer `MessageIsReadSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'text'. What is wrong? -
DRF reverse action url from viewset
I have an issue reversing the URL of ViewSet actions in the DRF my codes are below, I try some methods to reverse URLs but also you can see it's not working for me view.py class Device_API(ViewSet): def list(self, request) -> Response: ... def update(self, request, pk) -> Response: ... def create(self, request) -> Union[Response, Http404]: ... def destroy(self, request, pk) -> Union[Response, None]: ... @ action( detail=False, methods=["GET"], url_path=r"filter/(?P<type>\w+)", url_name="filter_type", ) def filter(self, request, type) -> Union[Response, Http404]: ... @ action(detail=True, methods=["GET"], url_name="data") def data(self, request, pk) -> Union[Response, Http404]: ... urls.py from rest_framework.routers import DefaultRouter, SimpleRouter from .views import Device_API Router = DefaultRouter() app_name = "api" Router.register("device", Device_API, basename="Device") urlpatterns = Router.urls and I try to reverse the URL like below but I get an error view = Device_API() view.basename = "Device" view.request = None url = view.reverse_action('filter') or url = reverse('Device-filter') Error django.urls.exceptions.NoReverseMatch: Reverse for 'Device-filter' not found. 'Device-filter' is not a valid view function or pattern name. I and also tried this url = reverse('api:Device-filter') Error Traceback (most recent call last): File "/home/nova/Documents/projects/webserver/ENV/lib/python3.8/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'api' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Django pass Varibals brack the url
Hi there I'm following a youtube tutorial of Django 3.0 to learn but I'm using Django 4.0 something and in this particular code I'm getting an error the code in getting the error on urlpatterns = [ path('update_order<str:pk>', views.updateorder, name ='updateorder'), ]` the code doesn't give me an error urlpatterns = [ path('update_order', views.updateorder, name ='updateorder'),] so if I try to pass any veribals its give me error of "NoReverseMatch at / Reverse for 'updateorder' with no arguments not found. 1 pattern(s) tried: ['update_order/(?P<pk>[^/]+)\\Z']" my views def updateorder(request,pk): form = OrderForm() context = {"form":form} return render(request, 'order_form.html', context) if you need any other information please ask in the comment. Thanks in advance -
Get user input values in a Mathquill environment with a Form
I just started using Mathquill in my Django app. I want to get a user input value from Django.views.py. Until now, I don't have a way to get these input values. E.g in the code below, how do I place the Mathquill expression inside a form such that when a user clicks submit, I get the values of x and y from my views.py <span id="fill-in-the-blank"> \sqrt{ \MathQuillMathField{x}^2 + \MathQuillMathField{y}^2 }</span> <input type="submit"/> <script> var fillInTheBlank = MQ.StaticMath(document.getElementById('fill-in-the-blank')); fillInTheBlank.innerFields[0].latex() // => 'x' fillInTheBlank.innerFields[1].latex() // => 'y' val = $(document.getElementById("fill-in-the-blank")); </script> -
Third Party AP in DRF
Im trying consulting http://ip-api.com/json/ with parameter QUERY,like localhost:8000/api?24.48.0.1 but only received ''"query": [ "This field is required."'' views.py: @api_view() def my_view(request): input = MyInputSerializer(data=request.GET) input.is_valid(True) tp_api = "http://ip-api.com/json{}".format(input.data['query']) response_data = requests.get(tp_api).json() my_serializer = MyOutputSerializer(data=response_data, many=True) my_serializer.is_valid(True) return Response(data=my_serializer.data) Serializers.py class MyInputSerializer(serializers.Serializer): query = serializers.CharField() class MyOutputSerializer(serializers.Serializer): query = serializers.CharField() country = serializers.CharField() Urls.py from django.urls import path from . import views urlpatterns = [ path('api',views.my_view), ] -
Django "o termo '/usr/bin/env python' não é reconhecido como nome de cmdlet..." manage.py [closed]
Estou aprendendo Django e, quando tento rodar o arquivo manage.py, esse erro aparece: /usr/bin/python : O termo '/usr/bin/python' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operável. Verifique a grafia do nome ou, se um caminho tiver sido incluído, veja se o caminho está correto e tente novamente. No linha:1 caractere:1 /usr/bin/python "c:\Users\mathr\Desktop\Coding Projects\Django\hello_ ... + CategoryInfo : ObjectNotFound: (/usr/bin/python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Estou usando uma virtualenv e não mexi em nada no código original do arquivo, apenas dei runserver no terminal. Alguém sabe o que fazer? -
Django MySQL - Setting an index on a Textfield
I have a database of articles that I want to search through. I had been using normal Django ORM to search, which was getting way to slow and then I got to know a little about Indexes in Django. I'm using MySQL and I now know that with MYSQL I cannot put an index field into a TextField as described here in this stack question which I was facing. However in my case I can't change this to CharField. I was reading through the MyQSL Docs which stated MySQL cannot index LONGTEXT columns specified without a prefix length on the key part, and prefix lengths are not permitted in functional key parts. Hence I was of the understanding that since TextField in Django is LONGTEXT for MYSQL, I came across this Django-MySQL package here and thought that using this if I could change the LONGTEXT to a MEDIUMTEXT using this package, this might get resolved. So my updated model I did this class MyModel(Model): ........ document = SizedTextField(size_class=3) However, I still see the same error while applying python manage.py makemigrations django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'document' used in key specification without a key length") How can I go about resolving this? -
How do you pass data into a Django form?
I'm using Django 4.0 and I'm trying to create a web app where the user selects a choice from a dropdown Django form. However, the choices will vary depending on the question and I want the form to be able to adapt to this. This is what I have in forms.py: class QuestionAnswerForm(forms.Form): def __init__(self, q_id, *args, **kwargs): self.q_id = q_id super(QuestionAnswerForm, self).__init__(*args, **kwargs) q_id = self.q_id # this line throws an error question = Question.objects.get(pk=q_id) choice = forms.ChoiceField(choices=get_choices(question)) However, I get the error: name 'self' not defined. I just want to know an easy way to pass the question id to the form so that the get_choices function can then return the choices that need to be displayed on the form. In views.py, the start of my view for the question sets the form in this way: def question_detail_view(request, q_id): print(f"Question id is {q_id}") form = QuestionAnswerForm(request.POST or None, q_id=q_id) -
django admin page disable def response_change
I would like to replace function of save button in admin page. Default is update, but I would like to insert new value to db. models.py class user_with_full_info(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) branch = models.ForeignKey(branch, on_delete=CASCADE) team = models.ForeignKey(team, on_delete=CASCADE) position = models.ForeignKey(position, on_delete=CASCADE) date = models.DateTimeField(default=now) add_button.html {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} <!-- hide default save button --> <!-- {{ block.super }} --> <div class="submit-row"> <input type="submit" value="Save" name="_change_position"> </div> {% endblock %} admin.py class UserFullInfoAdmin(admin.ModelAdmin): list_display = ('get_salary_number', 'user', 'branch', 'team', 'position', 'get_active') change_form_template = "information/user_button.html" def response_change(self, request, obj): if "_change_position" in request.POST: user_with_full_info.objects.create( user = user.objects.get(id = request.POST['user']), branch = branch.objects.get(id = request.POST['branch']), team = team.objects.get(id = request.POST['team']), position = position.objects.get(id = request.POST['position']) ) return HttpResponseRedirect(".") return super().response_change(request, obj) This code is working fine with insert new value, BUT it's always update the selected value too. How can I disable IS_POPUP_VAR in response_change function to not update selected value. -
Using OAuth in an Android app with custom
I am developing an Android app with a REST API. The REST API needs authentication for security. I would like to use Google's OAuth2 provider since I the client will be on Android. I don't want to store passwords myself. I'm trying to understand how the flow should work at a conceptual level. Authenticate to OAuth2 services describes how to get an OAuth token in the Android app. But then what? Do I need a route that accepts this token? I am implementing the API with Django and Django Rest Framework. I found python-social-auth to implement OAuth flows for the API. It works great when I test manually in a browser going to http://localhost:8000/social/login/google-oauth2/. When I request that URL with a HTTP client, it returns HTML for a Google login page. In the Android app, should I load that in a WebView? And then what? That doesn't seem quite right to me since I'd rather use the Android OAuth API that I linked earlier. What am I missing here and how do I solve this? -
Why the name of the form variable is being displayed? django
I have this form form.py from django import forms from .models import User LETTERS= [ ('a', 'a)'), ('b', 'b)'), ('c', 'c)'), ('d', 'd)'), ('e', 'e)'), ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(widget=forms.RadioSelect, choices=LETTERS) and this view views.py from django.shortcuts import render from questoes.models import Questao from .forms import CHOICES # Create your views here. def prova(request): questoes = Questao.objects.order_by('?')[:5] form = CHOICES if request.method=='POST': dados = { 'questoes': questoes, 'form':form(request.POST) } return render(request,'provas/prova.html', dados) else: dados = { 'questoes': questoes, 'form':form } return render(request,'provas/prova.html', dados) I can't figure out why the name NUMS (the form's variable name) is being rendered in the HTML. :( -
Deselection in django forms
Is that possible to deselect selected object in forms.SelectMultiple in Django? My model instance accept the field be None, but when in form i select some object I can't deselect it. -
Django FieldError : Cannot resolve keyword 'total_sales' into field
This is the query I am running to get Total Sales for each party. Party.objects.annotate(total_sales=Sum('sales__salestransaction__total_cost')) It shows correct results. But when I try to apply in my view with get_queryset, it is not working and shows a FieldError which is: Cannot resolve keyword 'total_sales' into field. Choices are: party_address, party_id, party_name, party_phone, sales My View class PartyListView(ListView): paginate_by = 2 model = Party template_name = 'mael/parties.html' def querystring(self): qs = self.request.GET.copy() qs.pop(self.page_kwarg, None) return qs.urlencode() def get_queryset(self): qs = super().get_queryset() if 'q' in self.request.GET: search_txt = self.request.GET['q'] qs = qs.filter(party_name__icontains=search_txt).annotate(total_sales=Sum('sales__salestransaction__total_cost')) return qs.order_by('total_sales') def get(self, request): form = PartyForm() party_list = self.get_queryset() qrstring = self.querystring() paginator = Paginator(party_list, 5) page_number = request.GET.get('page') party_list = paginator.get_page(page_number) return render(request, self.template_name, {'form': form, 'party_list': party_list, 'querystring': qrstring}) Models class Party(models.Model): party_id = models.BigAutoField(primary_key=True) party_name = models.CharField(max_length=128) party_phone = models.CharField(max_length=128) party_address = models.CharField(max_length=128) def __str__(self): return self.party_name class Sales(models.Model): invoice_no = models.BigAutoField(primary_key=True) invoice_date = models.DateField(default=date.today) party = models.ForeignKey(Party, on_delete=models.CASCADE) def __str__(self): return str(self.invoice_no) class SalesTransaction(models.Model): sales = models.ForeignKey(Sales, on_delete=models.CASCADE) item_qty = models.PositiveIntegerField(default=0) total_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name What is a problem with the get_queryset function and how can I solve this error? Please help. -
Create database using docker-compose django
I have a Django application that is dockerized and using Postgres for the database and I want that every time someone builds the docker-compose so the app should create the database inside db container if the database is not already existed there, and also I have some static data inside some tables and I want to insert that data if the same data doesn't exist in the tables. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - dev.env ports: - "5432:5432" app: container_name: app build: context: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./core:/app - ./data/web:/vol/web env_file: - dev.env ports: - "8000:8000" depends_on: - db volumes: postgres_data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # COPY ./core /app WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] /scripts/run.sh #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami python manage.py … -
Error The to_field 'admin.username' doesn't exist on the related model 'testwebsite.Callers'
I have 3 model. 2 model for creating user. 1 model get primary key from user model my model class CustomUser(AbstractUser): user_type_data=((1,"AdminHOD"),(2,"Managers"), (3,"Teamleaders"),(4,"Admins"),(5,"Supports"), (6,"Callers"),(7,"Fields"),(8,"Tester") ) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) class Callers(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) gender=models.CharField(max_length=225) profile_pic=models.FileField() address=models.TextField() team_id=models.ForeignKey(ListofTeam,on_delete=models.CASCADE,default=1) group_id=models.ForeignKey(ListofGroup,on_delete=models.CASCADE,default=1) objects=models.Manager() class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.CASCADE, to_field="admin.username") my error when i makemigrations testwebsite.report.nhan_vien: (fields.E312) The to_field 'admin.username' doesn't exist on the related model 'testwebsite.Callers'. I try username only class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.CASCADE, to_field="username") It still error testwebsite.report.nhan_vien: (fields.E312) The to_field 'username' doesn't exist on the related model 'testwebsite.Callers'. How can I get username as to_field in model Thanks for your reading -
How to add the same data to list of users?
Let us suppose the I have list 10000 Users in my website And there field "new_notification" (just for example) Now i want a certain notification to the every user in the list not for in the other users data. let us suppose list user = ['user1','user2',] data= 'new post is out' Now one way is this for i in user: i.data = data i.save() But according this is time consuming for 10000 running the for loop is not good according if i am wrong then please correct. I hope you understand my problem Is there more fast alternative of for loop? Thanks in advance. -
when am working on a formA, How i can get a value of a field from modelB after select a Many2Manyfield of a modelB on Django
I have modelA that contain some fields,one of the those fields is type "ManyToManyField"(call another modelB that has 3 fields, one of them defined as"sigma"), the story that in the formA I want when i select option from the ManyToManyField(modelB) , I get the value of sigma of this ManyToManyField selected. enter image description here ---> I have tried to do that but always i get the last value of the sigma(get the sigma from last example added on the admin page of the modelB) entered on the admin page and not the value of sigma that correspond the many2manyfield selected by the user. **PS:**the data of the modelB i have added it throw the admin page to be displayed when i work with the formA on my localhost. Here is the code in the models.py: code of the ModelA: class ModelA(models.Model): description = models.CharField(verbose_name=" Description ", max_length=60) modelelement = models.CharField(verbose_name=" Mode Element ", max_length=60) element = models.ManyToManyField(ModelB) code of the ModelB in the models.py: class ModelB(models.Model): designation = models.CharField(verbose_name="designation", max_length=60) resistance = models.CharField(verbose_name='resistance W', max_length=50) sigma = models.FloatField(verbose_name='Sigma', max_length=50) def __str__(self): return self.designation + " " + self.resistance in forms.py : class ModuleForm(ModelForm): class Meta: model = ModelA fields … -
Django Authentication without Django Admin functionality
I am working on a Rest API using Django Rest Framework. I want to add registration and authentication, but I don't know how to do it. There is a bunch of methods of doing that in official docs, but they all seem to be using Django Admin functionality (by inheriting their User classes from AbstractBaseUser), which I don't want to use. I want to do it from scratch, have my own Person class which does not use any Django Admin functionality. I am planning to disable Django Admin in my project. Is there a way to do that? -
Django - How can I send absolute url for a model from views.py to another python script?
I'm pretty new to Django and am trying to make a breadcrumbs module. It works pretty well, except I'm having trouble trying to link back to URLs which need a primary key. I've got a breadcrumbs.py file which simply looks up the list of keywords in a list and adds HTML in the form of list items. The problem is to link back to, for example, the profile of a user, I need to send the absolute_url for that profile to breadcrumbs.py. However, since I'm calling the get_breadcrumbs function from within views.py, I can't directly send the request object as an argument in extra context. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.SET_DEFAULT, blank= True, default=Role.get_default) image = models.ImageField(default='profile_pics/default.png', upload_to = 'profile_pics') def __str__(self) -> str: return f"{self.user.username}'s profile" def get_absolute_url(self): return reverse("profile", kwargs={"pk": self.pk}) views.py: from apps.backend_utils.breadcrumbs import get_breadcrumbs class ProfileView(LoginRequiredMixin, DetailView): model = Profile template_name = 'users/users_profile.html' extra_context = { 'breadcrumbs': get_breadcrumbs(['home']), 'page_title' : 'Profile', } breadcrumbs.py: from django.urls import reverse_lazy breadcrumb_lookup = { 'home': { 'title' : 'home', 'url_name': 'home', 'icon_class' : 'fas fa-home', }, 'profile': { 'title' : 'Profile', }, ...[Code omitted]... } for k, v in breadcrumb_lookup.items(): if 'url_name' in v.keys(): v.update({'url': … -
Problem with Select a valid choice. That choice is not one of the available choices
in my form.py I have a class StudentsForm: class StudentsForm(ModelForm): def __init__(self, *args, **kwargs): students = kwargs.pop('students ') course = kwargs.pop('course ') super().__init__(*args, **kwargs) CHOICE_LIST = [('', '----')] i = 1 for itm in students: CHOICE_LIST.append((i, itm)) i += 1 self.fields['students'].choices = CHOICE_LIST self.fields['students'].initial = [''] self.fields['course'].choices = [(1, course), (2, '----' )] self.fields['course'].initial = [1] class Meta: model = StudCourse fields = ( 'course', 'students', ) widgets = { 'course': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Select course', 'style': 'color: crimson; background-color:ivory;' }), 'students': forms.SelectMultiple(attrs={'class': 'form-control' , 'placeholder': 'Select students', 'style': 'color: crimson; background-color:ivory;' }), } my view.py def test(request): #team = get_team(request) # here the second students is a query set of model Student, 2nd course is an object of model #Course form = StudentsForm(students=students, course=course) if request.method == 'POST': form = StudentsForm(request.POST, students=students, course=course) if form.is_valid(): form.save() return redirect('home') if team.exists(): return render(request, 'app/students_goal_form.html', {'form':form}) my students_goal_form.html {% block content %} <section id="students_form"> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <div class="col-3"></div> <div class="col-6"> <div class="form-group"> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success"> <i class="icon-circle-arrow-right icon-large"></i> Save </button> </form> </div> </div> <div class="col-3"></div> </div> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <p>&nbsp</p> … -
Django Rest Framework how to check an object is exists or not?
I'm trying to check if an object is exists or not and this is how I do: try: control = Card.objects.filter(cc_num = cc_number)[0] exists = True except (IndexError): exists = False It works but I wonder if there is a more practical way to do? (The reason I use except(IndexError) is I'm finding the object with typing [0] to end of model.objects.filter().)