Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a Django constraint based on data in model
Say I have a simple model like this: class Country: name = models.CharField(max_length=200, unique=True) class City: name = models.CharField(max_length=200, unique=True) country = models.ForeignField('Country', on_delete=models.PROTECT) class Person: name = models.CharField(max_length=200, unique=True) country = models.ForeignField('Country', on_delete=models.PROTECT) city = models.ForeignField('City', on_delete=models.PROTECT) Obviously, I'd like to constrain Person to have be able to refer to cities in the same country as the person. I can't see any easy way of doing this with limit_choices_to in the city field, as it can't reference the current data values. What's the best way of going about this - ideally that would also work with the admin console? -
How to get the ID of row from DataTables and insert in the url thru Ajax?
Following is my code that giving me Loading error when I add the company_id in the url "http://127.0.0.1:8000/api/"'+company_id+'"/edit_company" like that. <script> $(function() { var oTable = $('#sodmzs').DataTable({ "ajax": function (data, callback, settings) { $.ajax({ url: "http://127.0.0.1:8000/api/company/", dataType: "json", type: 'GET', success: function(data) { const data_format = {"data": data}; callback(data_format); } }); }, "columns": [ { "data": "company_id" }, { "data": "name" }, { "data": null, "render": function (data, type, row, meta) { // you can even get the data from other columns here // and render whatever you want on these cells return '<td><a href="http://127.0.0.1:8000/api/"'+company_id+'"/edit_company" class="btn ink-reaction btn-floating-action btn-warning"><i class="md md-edit"></i></a></td>' } } ] }); }); </script> PLease let me know is that the proper way of doing ? -
Django keeps reporting the same error after I already edited views.py
I am editing a Django 2.2 application and I received an Exception: TypeError at /myappname/myurl 'RelatedManager' object is not iterable Exception Location: /myprojectlocation/myappname/views.py in myview, line 41 Whoops, I accidentally typed .objects instead of .objects.all(). Easy fix. But now, no matter how I edit views.py, I keep receiving the exact same exception, always pointing at line 41. I even commented line 41 out entirely, and still get the same exception. The exception Traceback shows the updated line 41, so I know I am definitely editing the right file and the changes are being saved, but the actual exception itself just keeps complaining about that RelatedManager no matter what I edit. I've restarted the webserver and I've cleared all my browsing data. So what on earth is still "remembering" the old code that I've edited many times since? -
How to sync local host with docker host?
I have a hello world Django project and i want to dockerize it. My OS is windows 8.1 and I'm using docker toolbox. using volumes I could persist data in docker container but the code in docker is not sync with the code in my local host. Here is my docker-compose.yml: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - myvol1:/code ports: - 8000:8000 volumes: myvol1: I don't know how should I use volume for this purpose. I have tried this. without using volumes I can run the local development server but when using volume I got that error. I'd be grateful for your help. -
Heroku with Docker release failed - ModuleNotFoundError: No module named 'users.apps'
I've been following a book tutorial that uses docker with Django. When I used the command 'git push heroku master', I get the following output: 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 "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/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 'users.apps' I have also been having issues through this project installing with pipenv, which required a workaround. I'm thinking it could be related. Regardless, here is my heroku.yml file: setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore_project.wsgi And my docker-compose.prod.yml: version: '3.7' services: web: build: . command: gunicorn bookstore_project.wsgi -b 0.0.0.0:8000 environment: - ENVIRONMENT=production - SECRET_KEY=[removed] - DEBUG=0 - STRIPE_TEST_PUBLISHABLE_KEY= [removed] - STRIPE_TEST_SECRET_KEY= [removed] ports: - 8000:8000 depends_on: … -
Django given URL path name get URL
I am trying to create a view which will list the URLs available on the server. given a url path like so: path(r'reindex_search', views.IndexView.as_view(), name='reindex') How can I, from within views.py, get the full path (eg 'http://localhost:8000/reindex_search'), given the name 'reindex'? I have tried using rest_framework.reverse and it works for some of my endpoints but fails on the urls that have variables in the path. Here is my attempt so far: urls.py api_root_dict = OrderedDict() ... api_root_dict['reindex_search'] = 'reindex' ... urlpatterns = [ ... path(r'reindex_search', views.IndexView.as_view(), name='reindex'), path('api/', views.HomeView.as_view(api_root_dict=api_root_dict), name='home'), ... views.py class HomeView(APIView): api_root_dict = None def get(self, request, *args, **kwargs): ret = OrderedDict() namespace = request.resolver_match.namespace for key, url_name in self.api_root_dict.items(): if namespace: url_name = namespace + ":" + url_name try: ret[key] = { 'href': reverse( url_name, args=args, kwargs=kwargs, request=request, format=kwargs.get('format', None) ) } except NoReverseMatch: continue home_url = reverse(viewname='home', request=request) obj = { '_links': { 'self': {"href": home_url}, **ret } } return Response(obj) This fails for example for the following path in my app's urls.py: path('<str:endpoint>/schema', views.schema, name='schema') with this in added to the root dict: api_root_dict['schema'] = 'schema' (by fail I mean NoReverseMatch exception) There must be a better way. How does Django templates do it … -
Server error (500) when I try to search in any language other than English
i want support search with all language in search bar , but when i write an Arabic word for example , it says Server error (500) my code | Models.py : class Homepage(models.Model): name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") page_url = models.URLField(max_length=250,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class PCprogram(models.Model): name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") page_url = models.URLField(max_length=250,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results = list( sorted( chain(pcprograms_database,home_database), key=attrgetter('name'), reverse=True # Optional )) paginator = Paginator(results,6) page = request.GET.get('page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/search.html', context) else: return render(request, 'html_file/search.html') else: return render(request, 'html_file/search.html') search form in html page : <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}" class="form-inline"> <input id="search_box" type="text" name="q" placeholder=" Search For ... " style="color:black" class="form-control mr-sm-2"/> <input class="btn … -
django - AttributeError: 'list' object has no attribute 'apppend' [closed]
I am following Vitor's tutorial on simpleisbetterthancomplex.com and using the same logic on my own program. In my Views.py my for loop is running into an error. The traceback in Line 37 (comment below) says that the 'list' object has no attribute 'append', when the list has a few rows as CharField. Views.py def visuals(request): data = [] labels = [] queryset = Arrest.objects.order_by('number') for arrest in queryset: data.append(arrest.number) labels.apppend(arrest.charge) # This is the error line according to traceback. return render(request, "data/visuals.html", { 'labels': labels, 'data': data, }) Models.py class Arrest(models.Model): number = models.IntegerField() charge = models.CharField(max_length=64) Traceback AttributeError at /visuals 'list' object has no attribute 'apppend' Request Method: GET Request URL: http://127.0.0.1:8000/visuals Django Version: 3.0.8 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'apppend' Exception Location: C:\Users\(removed)\data\views.py in visuals, line 37 Python Executable: C:\Users\(removed)Python\Python38-32\python.exe Python Version: 3.8.1 -
Catching a 413 Request Entity Too Large in Django
When uploading a file, how can I catch the 413 Request Entity Too Large error so I can reload the form with a message saying the file is too large? I've already increased the limit in NGINX with client_max_body_size so this is a fallback in case someone still does exceed the limit. -
Redirecting multiple times to come on a page in django
I am sorry for the title not being descriptive coz I couldnt think of a good one. My concern is that I am having a django website in which I have a product view page. In that If a user is not logged in and clicks on add to cart then he is redirected to login page and and after he logs in he comes back to the product view page that was opened earlier(Using the next)This is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") Now the problem arises when a person is not already a user of my site.In that case the person is redirected to login but and he then chooses to signup and after signup he is redirected back to login page and after logging in he is redirected to index and not to the product view page. So is there any way that for a website user who doesnt have an account when clicks on add to … -
Get XML data from a requests.post in Django
I'm sending a request like this in Django: response = requests.post('https://ws.sandbox.pagseguro.uol.com.br/v2/transactions', headers=headers, params=params, data=data_ps) When I print(response.text) I got the following answer: <?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> <transaction> <date>2020-08-22T14:57:23.000-03:00</date> <code>CCBA67EC-D4C8-42F2-BC84-15C910A36B84</code> </transaction> How can I get the code number (CCBA67EC-D4C8-42F2-BC84-15C910A36B84)? Thank you! -
Unresolved library error when trying to load custom tag in Wagtail CMS
I am new to Wagtail but have some knowledge in Django. I was trying to follow the official documentation of Wagtail but I got stuck in the snippets section. I am trying to render a snippet NavigationComponent in home/templates/home/home_page.html. I have defined a tag in home\templatetags\navigation_tags.py to render it. However when I am trying to load the tag using {% load %}, it doesn't recognize it. Here is the code:- [base.py] INSTALLED_APPS = [ 'home', 'search', 'website', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ########################################################################################### [home/models.py] from django.db import models from wagtail.core.models import Page from wagtail.snippets.models import register_snippet from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel class HomePage(Page): pass @register_snippet class NavigationComponent(models.Model): name = models.CharField(max_length=50, blank=False) link = models.ForeignKey( 'wagtailcore.Page', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) url = models.URLField(blank=True, null=True) panels = [ FieldPanel('name'), PageChooserPanel('link'), FieldPanel('url') ] def __str__(self): return self.name class Meta: verbose_name_plural = 'Navigation Item Container' verbose_name = "Navigation Item Container" @register_snippet class NavigationItem(models.Model): name = models.CharField(max_length=50, blank=False) link = models.URLField() class Meta: verbose_name_plural = 'Navigation Items' [home/templatetags/navigation_tags.py] from django import template from ..models import NavigationComponent register = template.Library() @register.inclusion_tag('../templates/tags/navigation_component.html', takes_context=True) def navigation_components(context): return { 'components': NavigationComponent.objects.all(), 'request': context['request'] … -
How to check password against previously used passwords in django
I have the following model for storing previously used hashed passwords: class PasswordHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) password = models.CharField(max_length=128, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) In the change password form I want check if the new password the user is changing to has not been used the past 5 times. Here is my form validation: class ProfileForm(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), required=False) password2 = forms.CharField(widget=forms.PasswordInput(), required=False) class Meta: model = Employee user_id = None def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id', None) super(ProfileForm, self).__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: raise forms.ValidationError('Passwords do not match.') user = User.objects.get(pk=self.user_id) hashed_password = user.set_password(password1) print(hashed_password) password_histories = PasswordHistory.objects.filter(user=user) for ph in password_histories: print(ph.password) if hashed_password == ph.password: raise forms.ValidationError('That password has already been used') return password2 The problem is that this line returns None: hashed_password = user.set_password(password1) It also saves the password to the user which the document says it does not do here: https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.set_password How can I compare a proposed new password against previously used passwords? Thanks -
The proper way to set user ForeignKey value in DjangoRestFramework
I have this model: class Comment(models.Model): user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, null=False) content = models.TextField(max_length=1000, null=False, blank=False) def __str__(self): """Return the comment str.""" return "'{}'".format(self.content) And its serializer looks like this: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' So far so good when it comes to retrieve data, but when I want to create a new Comment, what would be the proper way to do so? My view: class CommentViewSet(viewsets.ModelViewSet): def get_permissions(self): permissions = [] if self.action == 'create': permissions.append(IsAuthenticated) return [p() for p in permissions] def create(self, request): """Create a comment in some post.""" serializer = CommentSerializer(data=request.data) if serializer.is_valid(): # False because user value is missing. serializer.save() return Response(serializer.data) else: return Response(serializer.errors) That's ok, I tried by overriding validate_user and letting it just pass, but validation is still running when I call is_valid. Also I tried to append request.user to serializer.data, but it's immutable. How could I achieve this if I need to use request.user? The value that I need to set to this field of the serializer is not in request.data. (I don't think letting the front end send the user id would be a good idea). Another solution I have … -
how to structure django templates with django restframework
I have a Django project that currently has the following structures: And each sub-packges (marketdata / oms / portfolio / rebalance) are all django apps that just provide Restful APIs, and they all get mapped in the "app\url.py" like this: I am trying to build the front-end of the project using Django template engine. Where do you think I should put my template files to? Should I create a new app within this project called "front-end" and put them all there? or should I put them under the most relevant existing apps (for example, login.html goes into "user" app) Thanks guys -
How to host multiple django rest framework apps in apache virtual hosts for windows
Here is the config of vhost file in apache windows. It is working but everytime the request is going to the same app which is first in WSGIPythonPath variable. i.e., the two url request will directs to 'company1'. Listen 192.168.168.202:7089 Listen 192.168.168.202:7099 WSGIPythonPath "C:/ApacheDevServer/htdocs/company1/Django_WebServices;C:/ApacheDevServer/htdocs/company2/Django_WebServices" <VirtualHost 192.168.168.202:7099> ServerName 192.168.168.202 WSGIScriptAlias / C:/ApacheDevServer/htdocs/company1/Django_WebServices/Django_WebServices/wsgi.py WSGIPassAuthorization On <Directory C:/ApacheDevServer/htdocs/company1/Django_WebServices> Allow from all Require all granted </Directory> </VirtualHost> <VirtualHost 192.168.168.202:7089> ServerName 192.168.168.202 WSGIScriptAlias / C:/ApacheDevServer/htdocs/company2/Django_WebServices/Django_WebServices/wsgi.py WSGIPassAuthorization On <Directory C:/ApacheDevServer/htdocs/company2/Django_WebServices> Allow from all Require all granted </Directory> </VirtualHost> Can anybody help. Thanks in advance. I want it to work in windows only. -
How can include a regular Django view content in a Wagtail page?
I have a website running on Django that uses Wagtail for most of the pages (that are simply text content, editable through the Wagtail Admin UI). However, I have some content that needs to be dynamically rendered from my own Django model (let's say it's a list of handouts). I'd like that content to be rendered on a Wagtail page that would also have some Wagtail models (e.g., top menu, some introductory text). What's the best way to do this? I thought about making the list of handouts an API endpoint, and rendering it with JavaScript + XHR, but it seems like there should be a good way to do it server-side. -
Follow & unfollow system django
i have follow and unfollow system for my app but when i want that using the if statement html changes from follow to unfollow automatically.. but unfortunately my for loop always gives False in views.py and i don't know what is wrong. here is my models.py file class FollowUser(models.Model): profile = models.ForeignKey(to=Profile, on_delete=models.CASCADE) Followed_by = models.ForeignKey(to=User, on_delete=models.CASCADE) def __str__(self): return "%s" % self.Followed_by here is my views.py file class UserListView(ListView): model = Profile context_object_name = 'users' template_name = 'dashboard/user_list.html' def get_queryset(self): si = self.request.GET.get("si") if si == None: si = "" profList = Profile.objects.filter(Q(phone__icontains = si) | Q(location__icontains = si) | Q(gender__icontains = si) | Q(organization_name__icontains = si)).order_by("-id"); for p1 in profList: p1.followed = False ob = FollowUser.objects.filter(profile=p1, Followed_by=self.request.user.profile.id) if ob: p1.followed = True return profList -
How to get top5 users by the quantity (2 tables connected with each other)?
My models: class Institution(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) type = models.CharField(choices=type_of_organization, default=1, max_length=32) categories = models.ManyToManyField(Category) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) class Donation(models.Model): quantity = models.IntegerField() institution = models.ForeignKey(Institution, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) How can i get top 5 users by the quantity for each Institution? For example, for Institution_id = 1? -
AUTH_PASSWORD_VALIDATORS = [ <== SyntaxError: invalid syntax
I deployed my local repo to heroku and when I tried "heroku run python manage.py migrate" the error AUTH_PASSWORD_VALIDATORS = [ ^ SyntaxError: invalid syntax comes out. I checked the syntax if there's any missing things but I couldn't find any. What should I do to fix this? Below is my full error log File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/init.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/init.py", line 83, in getattr self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/init.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/init.py", line 177, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 724, in exec_module File "", line 860, in get_code File "", line 791, in source_to_code File "", line 219, in _call_with_frames_removed File "/app/config/settings.py", line 127 AUTH_PASSWORD_VALIDATORS = [ ^ SyntaxError: invalid syntax -
Saving different styling formats in Django
I'm trying to build a blog site with Django and I'm wondering how it's possible to save different styling for different posts when creating a post. Something like the editor when creating a question here in Stackoverflow. If lets say the post has highlighted text or code snippet or quotes. How do I save the different styles for different posts? -
Many to Many relationship query returns empty queryset on post_save signal but not in django shell
I have a function in my model that send an email on successful save. But i am struggling to figure out why print statement on signal function in the model returns empty queryset but not in the shell. Below is my code. Model code class Booking(models.Model): """Database table for users booking details""" //more code here items = models.ManyToManyField(BookingItems) //more code here def send_confirmation_email(sender, instance, **kwargs): """Function to send email upon successfull booking creation""" name = instance.guest_name total = instance.final_total, email = instance.email order_number = instance.reservation_id bookingId = instance.id itemsData = instance.items.all() booking = Booking.objects.get(id=bookingId) bookingItems = booking.items.all() print(bookingItems)-----------------------------------> this returns empty queryset <QuerySet []> context = {"name": name, "items": itemsData, 'total': total, 'order_number': order_number} message = render_to_string( "reservations/room_reservation_success.html", context) plain_message = strip_tags(message) subject = f"Your booking details for {instance.hotel.name}" mail.send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [ email], html_message=message) post_save.connect(send_confirmation_email, sender=Booking) Code from shell >>> book = Booking.objects.filter(id=61) >>> print(book[0].items.all()) <QuerySet [<BookingItems: One bedroom>, <BookingItems: Two bedroom>]> >>> What could be the issue here. Why is it returning empty set when there's clearly related child items? Kindly assist -
Django order_by causes query to be very slow
I have a model Line with a total_value and a group fields. I use the following code to get the 10 lines with the highest values within a given group: group_lines = Line.objects.filter(group_id=group_pk, total_value__gt=0) sorted_lines = group_lines.order_by('-total_value')[:10] ids = lines.values_list("id", flat=True) My database is very large, with 10M+ lines. The group_lines query alone returns 1000 lines. My issue is that the values_list query takes about 2 seconds to get executed. If I remove the ordering, it is almost instant. Is it normal to take that long to order 1000 objects? How can I make this query faster? I am on Django 2.1.7, with a MySQL database. -
Calculate streak by date in django
I'm developing a habit tracker using django. The models of the project are the following: class Habit(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField(max_length=500) start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.user.username + " - " + self.title class HabitRecord(models.Model): COMPLETION_CHOICES = ((0, "NOT DONE"), (1, "COMPLETED")) habit = models.ForeignKey(Habit, on_delete=models.CASCADE) note = models.TextField(max_length=500, default="") fire_date = models.DateField(auto_now_add=True) completion_status = models.IntegerField(choices=COMPLETION_CHOICES, default=1) def __str__(self): return str(self.fire_date) now I need to calculate the current streak of a habit (how long a habit has been marked as COMPLETED in a row). Therefore a method called get_streak should be implemented. What is the best way to implement this? -
How can I autofill a field in my django form?
I am trying to create a very simple form for users to borrow book from a library and I have a button to borrow book that redirects user to another page. Once the user is redirected all i want to allow him is to click submit or cancel for specific book. My model for that: class Borrowed(models.Model): person = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL) book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL) taken_date= models.DateField(auto_now_add=True) return_date= models.DateField(default=datetime.today()+timedelta(days=90)) def __str__(self): return f"{self.person} borrowed {self.book}" views.py: def borrow(request, pk): book = Book.objects.get(id=pk) if request.method == 'POST': # form = BorrowForm(instance=request.user.person) form = BorrowForm(request.POST, initial={Book: book.title}) if form.is_valid(): form = form.save(commit=False) form.person = request.user.person form.book = book.title form.save() return redirect('all_books') else: form = BorrowForm(initial=book.title) context = {'form': form, 'book': book} return render(request, 'rental/borrow.html', context) forms.py class BorrowForm(forms.ModelForm): class Meta: model = Borrowed fields= ['book'] I don't know how and where exactly to do that because I am new to Django. Help would be appreciated. Thank you