Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show data from specific table in my view django
I want only the requests from the Hospital. How can I achieve this? Example: User from Hospital class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) FKbelongs_to = models.ForeignKey('HospitalViewRoleForUsers', on_delete = models.CASCADE, null=True, blank=True) Hospital Model class HospitalViewRoleForUsers(models.Model): RequestsFromLab = models.ForeignKey('request', on_delete=models.PROTECT) Requests from the Hospital FKHospitalRequests = models.ForeignKey('HospitalViewRoleForUsers', on_delete = models.PROTECT) user_request = models.ForeignKey('customuser', on_delete= models.PROTECT) In my View I need to validate which Hospital the user belongs to and, Pass only the request information from that hospital to my user view. The user view that I am trying to build def Get_UserRequestByHospital(request, pk): user = request.user items = requests.objects.filter(FKHospitalRequests = 1).values_list('id', flat = True) return render(request, 'user_profile/list-user-request.html', {'items': items}) In Jupyter testing data it appears like this user_hospital2 = requests.objects.filter(FKHospitalRequests = 1).values_list('id', flat = True) <QuerySet [1]> As we can see, Jupyter returns the request id. Which is linked to the Hospital. But, I am confused and I need help thinking on a solution. I am new to Django, so. I suppose I need to pass the PK to the view, and then, create a filter to check if PK is equal to FK from the Hospital Request? But, also, How I know this user belongs to the Hospital? … -
Django best practices for early development stage
Hello I have been learning django for past few months and creating a blog website.When I was creating blog I got in lot of problems with models and other things. When I was working on my blog website I created models for user and stuff and then later found out that to use authentication is very hard with custom user model so I had to change the whole user model and after that i was using only static folder to store files such as templates,css,js and images and not media for user upload stuff such as blog image,user profile image and in order to do I had to change a lot of things in my settings.py . After that come across with template url stuff I was using hard url like \accounts\login something like that and then found that we can use {% url 'login' %} which is easy in my opinion then i got absolute url error and fixed that . When I was developing I was using function views and then found class based views is easy with listviews, detailviews, creatviews, etc. While developing this I was wondering what is best practices for django what can I do … -
i want to use my one table of database for my project in 2 different apps of django python
e.g. I have a table of employee in which the Agent can add the employee delete and update. and I want to show that employee table in the Employee app how can I do it I try but it shows me the error that I can't use that table in 2 apps ... can anyone plz help me with this.. -
Django is_authenticated always return False
I'm using django-allauth and cpanel to develop a website. Everything works fine, but there is one problem. I always get false in this statement: if request.user.is_authenticated: The strangest thing is that everything works fine on local. But, it always returns false on the real site (using cpanel) even though I'm already logged in. One more weird thing I found (which might be a clue) is I can log in with different accounts at different tabs. I don't know what is the problem. I don't even know where to check the problem. Is the problem in django-allauth? cpanel? session? Where should I check? Thank you. -
Get objects assigned to ForeignKey
to be honest im not pretty sure how to explain this but i want to display all objects assigned to foreignkey when im in one of this objects MODELS.PY class Category(models.Model): def __str__(self): return self.name ... name = models.CharField(max_length=267) CategoryThumbnail = models.CharField(max_length=300) class Video(models.Model): def __str__(self): return self.name ... Category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) nazwa = models.CharField(max_length=267) embedlink = models.CharField(blank=True, max_length=1000) thumbnail = models.CharField(max_length=300, blank=True) VIEWS.PY def Category(request, slug): category_user = Category.objects.get(slug=slug) category_video = Video.objects.filter(Category = category_user) categories = Category.objects.all() dict = {'category_user' : category_user, 'category_video' : category_video, 'categories' : categories} return render(request, 'categories.html', dict) def video(request, id): video_user = Video.objects.get(pk=id) videos = Video.objects.all() categories = Category.objects.all() dict = {'video_user' : video_user, 'categories' : categories, 'videos': videos} return render(request, 'video.html', dict) TEMPLATE categories.html {% for video in category_video %} {% if category_video %} <div class="flex-container"> <div class="between"> <a href="/video/{{ video.id }}"><img loading="lazy" id="resize" src="{{ video.thumbnail }}.png" class="miniimg"></a> <figcaption class="caption"><a style="color: #ffffff; font-size: 17px; font-weight: bold;" href="/video/{{ video.id }}"> {{ video.name }} </a></figcaption> </div> </div> {% endif %} {% endfor %} To this moment everything works but when i want to display objects from video in category but when im trying to display Video Objects that are assigned to the Category … -
How to use two fields as username in Django custom user model?
I have employee table (legacy) with fields Employee_no, Company_name and Password. How can i use my current table as Django user model? Employee_no is duplicate but combination with company_name, it will be unique. I need to use employee_no and company_name as username to login. Employee_no Company_name password 1 Apple any password 1 Samsung any password 2 Apple any password 3 Samsung any password 3 Google any password -
Django - add download link based on upload_folder destination
I have set a location for the file storage based on the data input. Could someone help me with setting up a download link for the same? How do I include this with the media root models.py class lMetadataform(models.Model): def upload_folder(self, filename): return f'LectureMaterial/{self.mtype}/{filename}' #fields id = models.AutoField(primary_key=True) mtype= models.CharField(max_length=2000, blank=True) document = models.FileField(upload_to=upload_folder, verbose_name="data", validators=[validate_file_extension], unique=True) page.html <td><a href="../ldownload/{{ b.document }}"> Dataset</a></td> views.py def ldownload(request,id): with connection.cursor() as cursor: query = '' query += str(id) #print(query) cursor.execute(query) row = cursor.fetchone() if row: print(row[0]) fullname = settings.MEDIA_ROOT + row[0] filename = os.path.basename(fullname) print('FILE: ',fullname) print('NAME: ',filename) fsock = open(fullname, 'rb') if fsock.closed: print("File closed") response = HttpResponse(fsock, content_type='application/gzip') response['Content-Disposition'] = "attachment; filename=%s" % \ (filename) return response else: print("File does not exist") return render(request, 'home.html') urls.py path('ldownload/<id>', views.ldownload, name='ldownload'), -
Django Validator function is not called in models file
i have models department when i add validator it does not call validator function class Department(models.Model): name = models.CharField(unique=True, max_length=50, validators=[lookups_name_validator]) code = models.CharField(unique=True, max_length=20) organization_id = models.ForeignKey(Organizations,on_delete=models.DO_NOTHING, default=1) my validators from django.core.validators import ValidationError import re def lookups_name_validator(branch): pattern = re.compile("^[a-zA-Z0-9_&/.\-]*$") match = re.match(pattern, branch) if match is None: raise ValidationError( f'{branch} is not Valid' ) my view is contain on Classed based API view -
validated data Django rest
I would like to validate data when I send post request, if data in db with the field country and value France exist, then raise ValidationError('Choose another country)' ,if not - create a new object in db. class MainSerializer(serializers.Serializer): email = serializers.EmailField() country = serializers.CharField(max_length=20) created = serializers.DateTimeField() class MainSerializer(serializers.Serializer): email = serializers.EmailField() country = serializers.CharField(max_length=20) created = serializers.DateTimeField() def create(self, validated_data): return Main(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.country = validated_data.get('content', instance.country) instance.created = validated_data.get('created', instance.created) return instance -
Is there a better solution to filter model objects by permission in django
I have a Django model Task containing permissions. from django.db import models from django.contrib.auth.models import Permission # Other stuff class TaskType(models.Model): required_permissions = models.ManyToManyField(Permission) # Other non relevant fields class Task(models.Model): begin = models.DateTimeField( #Options left out end = models.DateTimeField( #Options left out type = models.ForeignKey(TaskType, on_delete=models.CASCADE) # Other non relevant fields Now I have a view where a user is supposed to select a Task in a specific Time slot but should only choose from tasks where the user has the required permissions for and where the task in question wouldn't be blocked by another task in that time slot the user was already assigned to. My current solution to this problem is to query objects from the objects from the database that could be a valid candidates and filter out the ones the user has no permission for in python. This obviously feels a bit silly since this should be done by the database query (as database management systems are quite sophisticated for such tasks). My current solution looks like this: def is_task_valid(self, task): for p in task.type.permissions.all(): if not user.has_perm(p.content_type.app_label + "." + p.codename): return False: # Also checks for all assigned tasks of user in that … -
Why Password reset unsuccessful in django rest-auth password reset
I have problem with django rest-auth password rest. this is my urls.py file(main urls) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi app_name= 'accounts' schema_view = get_schema_view( openapi.Info( title='Blog API', description='oddiy API loyixasi', default_version='v1', terms_of_service='``https://google.com.policies.terms``', contact=openapi.Contact(email="xatamjonovulugbek17@gmail.com"), license=openapi.License('Blog API litsenziasi'), ), public=True, permission_classes=(permissions.AllowAny, ), ) urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('accounts.urls')), path('', include('product.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path(r'^', include('django.contrib.auth.urls')), path('auth/', include('rest_framework.urls')), path('allauth/', include('allauth.urls')), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-radoc'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I add path(r'^', include('django.contrib.auth.urls')), to urls.py. This url sent mail to counsol but I enter url in mail , I take this error: " Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. " Please give me solve I add path(r'^', include('django.contrib.auth.urls')), to urls.py. This url sent mail to counsol but I enter url in mail , I take this error: " Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. " Please give me … -
Django/Python - Get radiobutton value
I have a problem, I want to get the radiobutton value to my view, but I don't know how. What I have now is this: index.html <form class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="radio" name="update_type" value={{view.choice1}}> Choice1 </input> <input type="radio" name="update_radio" value={{view.choice2}}> Choice2</input> <a href="{% url 'core:newview' slug=???? %}" class="btn btn-primary">Update</a> </div> </div> </div> </div> </form> views.py #index.html class view1(generic.TemplateView): extra_context = {"main_page": "active"} choice1 = 1 choice2 = 0 context_object_name = 'mainview' template_name = 'core/index.html' class NewView(generic.TemplateView): extra_context = {"mainx_page": "active"} context_object_name = 'newview' template_name = 'core/index.html' def get(self, request, queryset=None, *args, **kwargs): update_choice = self.kwargs.get('slug') print(update_choice) return redirect(reverse("core:mainview")) urls.py path('mailbox/mainview', login_required(views.MainView.as_view()), name='mainview'), path('mailbox/newview/<int:slug>/', login_required(views.NewView.as_view()), name='newview') Basically, I don't know what I should put at the place in the index.html where the ???? are now. I want to get a 0 as a value from self.kwargs.get('slug') when choice1 is selected in the radiobutton and a 1 when choice2 is selected. Another option is that I not get a 0 or 1 value, but rather returning it as a string: choice1 or choice2 Could someone help me, it's very much appreciated! -
In django-recurrence the between() method with inc=True includes dtstart even when there is no Recurrence then
This a question on jazzband's django-recurrence. I have model with a RecurrenceField: # models.py class Session(models.Model): # other fields dates = RecurrenceField(null=True) In the django admin, I add a rule: weekly, Mondays. I need to get all the Session dates of the current month (including those in the past). However, when I call between() with inc=True, and dtstart = the first day of the month (as decribed in the docs), then that dtstart is returned too (which is a Tuesday for March 2022): # shell output: In [7]: obj = Session.objects.all().first() In [8]: for rule in obj.dates.rrules: ...: print(rule.to_text()) ...: hebdomadaire, chaque lundi # translates to: weekly, every Monday In [9]: month_end Out[9]: datetime.datetime(2022, 3, 31, 0, 0) In [10]: month_start Out[10]: datetime.datetime(2022, 3, 1, 0, 0) In [11]: obj.dates.between(month_start,month_end,dtstart=month_start,inc=True,) Out[11]: [datetime.datetime(2022, 3, 1, 0, 0), # this is a Tuesday! datetime.datetime(2022, 3, 7, 0, 0), # Monday datetime.datetime(2022, 3, 14, 0, 0), # Monday datetime.datetime(2022, 3, 21, 0, 0), # Monday datetime.datetime(2022, 3, 28, 0, 0)] # Monday In [12]: obj.dates.between(month_start,month_end,dtstart=month_start,inc=True,)[0].weekday() Out[12]: 1 -
Django Model Form not saving data
I am working on Django application and I am trying to create form for users' suggestions and comments. I want to see that suggestions/comments in database (admin interface). After the comment is submitted, it is not saved in database. I have some mistake here but I don't know where it is. Can you please help me? views.py: def komentariPrijedlozi(request): if request.method == 'POST': form = CommentsSuggestionsForm(request.POST) if form.is_valid(): form.save() return render(request, 'rjecnik/successCommentsSuggestions.html') form = CommentsSuggestionsForm() context = {'form' : form} return render(request, 'rjecnik/komentariPrijedlozi.html', context) komentariPrijedlozi.html: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Comments and suggestions</title> </head> <body> <section class="main-container1" style=" margin-top: 50px; background-color: lightgray;"> <div class="columns"> <div class="main-par" style="font-size: 21px; margin-bottom: 20px;">Komentari i prijedlozi novih prijevoda:</div> <div class="column is-half is-offset-one-quarter"> <form method="POST" autocomplete="off" enctype="multipart/form-data"> <tr> <th> <label for="suggestion1">Prijedlog novog pojma:</label> </th> <td > <input type="text" name="suggestion1" maxlength="100" autocomplete="off" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"> </td> </tr> <tr> <th> <label for="suggestion2">Prijedlog prijevoda:</label> </th> <td> <input type="text" name="suggestion2" maxlength="100" autocomplete="off" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"> </td> </tr> <tr> <th> <label for="comment">Komentar:</label> </th> <td> <textarea name="comment" cols="40" rows="10" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"></textarea> </td> </tr> {% csrf_token %} … -
How to make Scrapy Request in Django view
I have to create a function or django view for making a scrapy Request to a URL and it will return response of that URL. -
Django : "matching query does not exist" on save() method
I'm building an application that fetches an API and fills a DB with the obtained data. I'm trying to save to DB for each JSON row processed. When I call obj_to_insert.save() at the end, I get an error: geotrek.trekking.models.DoesNotExist: POI matching query does not exist. POI is one of my models, it's correctly defined and imported. Here is the structure of the processing function (I oversimplified it, all the vars I use are correctly defined in the real code, etc.): with transaction.atomic(): for datatype_name, datatype_details in dict.items(): ##fetching the API r = response.json()["results"] for index in range(len(r)): dict_to_insert = {} for f in normal_fields: dict_to_insert[f.name] = other_dict['key'][f.name] obj_to_insert = DataType(**dict_to_insert) for f in fkeys_fields: fk_to_insert = {} if condition: fk_to_insert[f.name] = other_dict['key'][f.name] new_topo = Topology.objects.create(**fk_to_insert) obj_to_insert.topo_object = new_topo elif condition: obj_to_insert.structure = Structure.objects.get(name = AUTHENT_STRUCTURE) elif condition: fk_to_insert[f.name] = other_dict['key'][f.name] ##simplified setattr(obj_to_insert, fk_field, f.related_model.objects.get(**fk_to_insert)) obj_to_insert.save() Everything goes well until the final .save(), which gives the models.DoesNotExist error. It's as if Django gets the obj_to_insert, tries to find a corresponding row in DB and doesn't find it (normal: I'm trying to create it). When I print(vars(obj_to_insert)) just before trying to save, here is the output, which looks perfectly fine to me: … -
Repetition of the same letter
I need to received an error message if I have 3 consecutives identiques value for "PCR POS/Neg" , 3 times in my "output_df". exemple: P P P N P P P N N P P P I have here 3 results P consecutif, 3 times How i can do it ? from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.contrib import messages import re import numpy as np def home(request): #upload file and save it in media folder if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls') and uploaded_file2.name.endswith('.txt'): savefile = FileSystemStorage() #save files name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() return render(request, "index.html") output_df['Date and Time'] = pd.to_datetime(output_df['Date and Time']) output_df['new'] = output_df["value"].apply(lambda x: ord(x)) np.floor(output_df["new"].diff().eq(0).sum() / 3) return output_df.to_html(), -
JS Alarmclock needs adjustment
I'm trying to set an alarmclock for the webapp I'm creating with Django. To do so, I followed some tutorials and adjusted the code for my needs and all. It works. My problem is, I want to set the time and date, manually, with the variables I get from Django views (I passed the hour and min variables into my HTML file). Here is my alarm.html file: {% extends 'mainapp_hf/base.html' %} {% block content %} {{ js_hour }} <div style="width: 100%; display: flex; justify-content: center; "> <div id="clock"></div> <script> const display = document.getElementById('clock'); const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3'); audio.loop = true; let alarmTime = null; let alarmTimeout = null; function updateTime() { const date = new Date(); const hour = formatTime(date.getHours()); const minutes = formatTime(date.getMinutes()); const seconds = formatTime(date.getSeconds()); display.innerText=`${hour} : ${minutes} : ${seconds}` } function formatTime(time) { if ( time < 10 ) { return '0' + time; } return time; } function setAlarmTime(value) { alarmTime = value; } function setAlarm() { if(alarmTime) { const current = new Date(); const timeToAlarm = new Date(alarmTime); if (timeToAlarm > current) { const timeout = timeToAlarm.getTime() - current.getTime(); alarmTimeout = setTimeout(() => audio.play(), timeout); setTimeout(clearAlarm, timeout + 5000); alert( value ); } … -
Add columns in model in DJango based on if else condition
This is my Django code for my model I want to have columns in the model based on the value of chart type enter column there` class DashboardCreativeQuery(models.Model): query_name = models.CharField(max_length=256, null=False, unique=True) query = models.TextField( null=False) chart_type = models.ForeignKey(DashboardCreativeCharts, blank=True, null=True, related_name='chart_type', on_delete=models.CASCADE) if chart_type: test= JSONField(null=False) How can I do it? -
how to use annotate before group by(values) : AttributeError: 'dict' object has no attribute 'annotate field' - django
I'm trying to calculate some fields then group a field, it raise this error : AttributeError: 'dict' object has no attribute 'total_prices' here is the query that i tried collections = Invoice.objects.filter( invoice__status=True).annotate( total_prices=Sum((F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)), paid_prices=Sum(F('cash')), total_discount=Sum(F('discount')), storage_prices=Sum( (F('item__mobile__price')+F('item__mobile__cost')),output_field=DecimalField(max_digits=20,decimal_places=3)), incomes=Case( When(total_prices__gte=F('storage_prices'),then=F('total_prices')-F('storage_prices')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), loss=Case( When( storage_prices__gt=F('total_prices'),then=F('storage_prices') - F('total_prices')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), num=Count('pk'), date_collections=TruncDay('item__mobile__collection__collection_date') ).values('date_collections').order_by('date_collections') for i in collections: print(i.total_prices) i dont want to put the group by before the annotate( i know it works, but not work as i want for the loss annotate) Thank you, most regards .. -
Shango management command update all empty value with integer 1
I have to make a command make all the blank values in integer 1. def handle(self, *args, **options): Soccer.objects.filter(goalblank=True).Update(goalblank=1) -
how to use integer value from for loop to get a list element in django template
I have a list of numbers in views.py list=[0,1,2,3,4,5] (it is not the same all the time I'm fetching it from API) then in my search.html I have written the following code:- {% for i in list %} <a href="https://example.com//{{ id[i] }}"> <img class="row_poster" src="https://this.isapi.org/{{poster[i]}}" alt="" /> <h4>{{title[i]}}</h3> </a> {% endfor %} where the id, poster, title are lists passed through views.py I want to get elements of each list 1 by 1 I tried adding for loop for each but the result was bad all posters render first and then titles were rendering I want to know how can I use it to call items from the list or any other by which I can access elements for all lists in a single loop. I have also tried {% with abcd=i %} but the result was the same keep getting this error Could not parse the remainder: '[i]' from 'id[i]' -
How to test mysql's max_execution_time option in django using pytest
I'm trying to test max_execution_time option of mysql in Django with pytest. But I'm having trouble with making slow query to test the option with pytest. Can you give me any tips or good example of slow query? Environment Python 3.8.10 Django 3.0.14 pytest 5.4.3 MySQL 5.7 Tried @pytest.mark.django_db def test_max_execution_time(): with pytest.raise(OperationalError): result = list(Blog.objects.raw(""" CREATE PROCEDURE InfLoop() BEGIN WHILE 1=1 DO SELECT 1; END WHILE; END; CALL InfLoop(); """)) pytest test.py Actual FAILED test.py F ===================================================================================== FAILURES ====================================================================================== ______________________________________________________________________ test_max_execution_time _______________________________________________________________________ @pytest.mark.django_db def test_max_execution_time(): with pytest.raises(OperationalError): > result = list(Blog.objects.raw(""" CREATE PROCEDURE InfLoop() BEGIN WHILE 1=1 DO SELECT 1; END WHILE; END; CALL InfLoop(); """)) E Failed: DID NOT RAISE <class 'django.db.utils.OperationalError'> test.py:102: Failed ============================================================================== short test summary info ============================================================================== FAILED test.py::test_max_execution_time - Failed: DID NOT RAISE <class'django.db.utils.OperationalError'> Expected 1 passed -
Django JWT graphql auth can not detect the logged in user
I have implemented jwt with graphql in django using django-graphql-jwt. I have graphql django userType as : class UserType(DjangoObjectType): class Meta: model = User fields = ('id', 'username', 'email','first_name','last_name', 'is_active') and have use the tokenAuth for logging the user in. The mutation schema is: class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() refresh_token = graphql_jwt.Refresh.Field() verify_token = graphql_jwt.Verify.Field() schema = graphene.Schema(query=Query, mutation=Mutation) and I call it by this query and get the response successfully: mutation loginUser( $email: String!, $password: String!) { tokenAuth( email: $email, password: $password) { token refreshToken payload } } The verifyToken query also works successfully when I call it and put the returned token in my query variables: mutation VerifyToken($token: String!) { verifyToken(token: $token) { payload } } But When I want to get the logged in user in a query, Django does not detect it. The query class is implemented as: class Query(graphene.ObjectType): #other stuff profile = graphene.Field(UserType) #other resolvers def resolve_profile(root, info, **kwargs): user = info.context.user #This line always prints "AnonymousUser" print(user) jwt_payload_handler = jwt_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = jwt_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) #This line does not print anything (print is not called). probably because the process had an exception in above lines print("Token is ", token) … -
How to modify existing model instance in django?
In Django, I am trying to modify the title of the existing book with id. My views.py file consists of b=Books.objects.filter(book_id__iexact=book) b.title = "Narnia" b.save() I am getting error and unable to save the model instance.