Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in Basic User Permissions in Django blog
My simple Django blog don't work - if I go to http://127.0.0.1:8000/posts/create/ I see Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/posts/create/ Raised by: posts.views.post_create Looking in the git history I understand what error in posts/views.py. The file itself looks like this from urllib.parse import quote from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.contrib import messages from .forms import PostForm from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render def post_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, 'Successfully Created') return HttpResponseRedirect(instance.get_absolute_url()) context = { 'form': form, } return render(request, 'posts/post_form.html', context) def post_detail(request, id=None): instance = get_object_or_404(Post, id=id) share_string = quote(instance.content) context = { 'title': instance.title, 'instance': instance, 'share_string': share_string } return render(request, 'posts/post_detail.html', context) def post_list(request): queryset_list = Post.objects.all() paginator = Paginator(queryset_list, 5) page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'object_list': queryset, 'title': 'List' } return render(request, 'posts/post_list.html', context) def post_update(request, id=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = … -
Django - how to follow some object ?
Hi I want to make a follow button in author details that let the user to follow an author and let the author have more than user can follow him here you are some of code that I write please check it Models.py aid = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=80) country = models.CharField(max_length=50) DOB = models.DateField(auto_now_add=True) DOD = models.DateField(auto_now_add=True) bio = models.TextField() followAuthor = models.ManyToManyField(User, related_name="FollowAuthor", blank=True) views.py def follow(request,event_id): user = request.user event = Author.objects.get(pk=event_id) event.followAuthor.add(user) event.save() urls.py path('/bookcity/follow', views.follow, name="follow"), # ex: /bookcity/authors path('authors/', views.author, name='authors'), # ex: /bookcity/authors/3 path('authors/<int:author_id>/', views.authorDetail, name='detail'), Template that I put in it follow button {% extends "base.html" %} {% block content %} <div> <p>Name: </p> <p>{{ author.name }}</p> <p>Books: </p> {% if books %} <ul> {% for book in books %} <li><a href="/bookcity/books/{{ book.bid }}/">{{ book.name }} </a></li> {% endfor %} </ul> {% else %} <p>No books are available.</p> {% endif %} {% if request.user.is_authenticated %} <li><a href="#">{{ request.user.username }}</a></li> <button type="submit">follow</button> <li><a href="/bookcity/authors/{{ author.aid }}/follow">follow</a></li> {%endif%} </div> {% endblock content %} -
How can I reset openedx static files cache?
I need to know how to force the openedx lms/cms to clear static files cache. When I browse the lms for example, I got the static files like that /static/css/lms-style-vendor.XXXXXXX.css I need to get the original source of this file not the cached one with XXXXXXX token. Or even generate a new one. Also when I run django server, it take a while to load the modification in HTML templates. Best, -
Filter querySet by value of page tag field
I'm creating a website using Wagtail. I have a page model called NewsItem. On the page I want to list the most recent news items that have the same tag, alongside the main content of the page itself. I'm not sure how to get the value of the tag field in order to filter a queryset and return the other news posts. I've tried various things: def render(self, value): news = NewsItem.objects.live().filter(tags__name=value['tags']).order_by('-date') return render_to_string(self.meta.template, { 'self': value, 'news_items': news, }) My tag field looks like this: tags = ClusterTaggableManager( through=Tags, blank=True, related_name='news_tag', verbose_name="News tags", help_text="News, Video..") I don't know if I need the return render_to_string bit, I just found an similar example online. Any help appreciated. -
Django: access previous information on save, or copy without changing original
I have a app where users fill in tests. The turn in submission objects which consist of some datetime information and all of the linked UserAnswer objects. Like so: class AssessmentSubmission(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) start_date = models.DateTimeField(default=timezone.now, editable=True) last_edited = models.DateTimeField(auto_now=True, editable=True) test = models.ForeignKey(Assessment) class UserAnswer(models.Model): answer = models.FloatField() question = models.ForeignKey(Question, related_name='answers') submission = models.ForeignKey(AssessmentSubmission, related_name='answers') Pretty straightforward, however, things get a bit more complicated from here. What I want is that, if a user edits / changes an answer more than 14 days since his last edit to the UserAnswer.submission, a new submission gets created, with all of the old answers AND the new edited answer, whilst leaving the original 'old' submission intact. To this end, I've overwritten the UserAnswer.save method with the following code: def save(self, copy=False, *args, **kwargs): print(self.answer) delta = datetime.datetime.now(tz=pytz.timezone(settings.TIME_ZONE)) - self.submission.last_edited #If less than 14 days have passed, change the 'last edited' value of the linked submission if copy == False and delta.days < 14: submission = self.submission submission.last_edited = timezone.now submission.save(copy=False) #If more than 14 days have passed, clone the submission and link question to submission if delta.days >= 14 and copy == False: answers = self.submission.answers.all() cloned_submission = self.submission cloned_submission.pk … -
Django and selenium TypeError: setUpClass() missing 1 required positional argument: 'cls'
I'am trying to experiment django v2 with selenium and got this error: ====================================================================== ERROR: setUpClass (level.tests.LevelListViewTest) ---------------------------------------------------------------------- TypeError: setUpClass() missing 1 required positional argument: 'cls' ---------------------------------------------------------------------- Ran 0 tests in 0.000s FAILED (errors=1) This is how my test looks like: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.firefox.webdriver import WebDriver class LevelListViewTest(StaticLiveServerTestCase): @staticmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @staticmethod def tearDownClass(cls): cls.selenium.quit() cls.selenium.tearDownClass() def test_level_is_in_admin_panel(self): self.selenium.get('%s%s' % (self.live_server_url, '/admin/login/?next=/admin/')) I use sqlite as database and I have already created a superuser and installed selenium using pip -
How to use two models for single index search in sphinx-django
I'm using django-sphinxql for search requirements in my django project. I want to use two models in my app for search with some query. Models look as below Class Model1(models.Model): name = models.CharField(max_length=50) model2 = models.ForeignKey(Model2, on_delete=models.CASCADE) Class Model2(models.Model): caption = models.CharField(max_length=50) I want to enable search for both name and caption fields above such that Model1 is returned for any matches, e.g. if query="abc" matches caption the response should be Model1, How would I achieve that I've created index for Model1 but don't know how to add caption from Model2 in it as well. My index for Model1 is as below class Model1Index(indexes.Index): name = fields.Text(model_attr='name') class Meta: model = Model1 settings.INDEXES['source_params'] = {'sql_field_string': ['name'],} Quick help is appreciate. -
Django DRF list of ids object
I have such serializers class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('id',) class MyModelIdListSerializer(serializers.Serializer): ids = MyModelSerializer(many=True) And request body like { "ids": [ { "id": "f07e3673-6631-4139-90da-331773ba868e" }, { "id": "f07e3673-6631-4139-90da-331773ba868e" } ] } But need this { "ids": [ "f07e3673-6631-4139-90da-331773ba868e", "f07e3673-6631-4139-90da-331773ba868e" ] } I can do ListField with UUID as child but need to write custom validate if such id exists on table -
Django CreateView - setting required field automatically - not working
I'm trying to set the value of circuit programatically instead of this being an option in my form. I have done this previously using form_valid, but I've just realised as the circuit value is required, then the form may not be valid to add the field to? Currently when I output form.errors to my template I get circuit field is required here is the view class AddFile(CreateView): form_class = FileForm template_name = "circuits/file_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('circuitfiles.add_file'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.circuit_id = self.kwargs['circuit_id'] self.refer = self.kwargs['refer'] self.site = get_object_or_404(SiteData, pk=self.site_id) self.circuit = get_object_or_404(Circuits, pk=self.circuit_id) return super(AddFile, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("circuits:edit_circuit", args=(self.circuit_id, self.site_id, self.refer)) def form_valid(self, form): form.instance.circuit = self.circuit return super(AddFile, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() kwargs['is_add'] = True return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['circuit_id']=self.circuit_id context['circuit_name']='{} {}'.format(self.circuit.provider.provider,self.circuit.circuit_type.circuit_type) context['SiteName']=self.site.location context['refer']=self.refer context['FormType']='Add' context['active_circuits']='class="active"' return context -
Server Error (500) on Django 1.6
I have Django 1.6 project and is run using the Gunicorn web application server behind the Nginx web server. Now i want to transfer that project to new host. For that i have copied all code across the new machine and install all required dependencies using pip install -r requirements.txt that went successful. When i was trying to run python manage.py runserver 0.0.0.0:8000 it was giving me below error: Unable to process log entry: Unsupported Sentry DSN scheme: Traceback (most recent call last): File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/raven/contrib/django/models.py", line 174, in sentry_exception_handler client.captureException(exc_info=sys.exc_info(), request=request) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/raven/contrib/django/models.py", line 54, in <lambda> _getattr_ = lambda x, o: getattr(get_client(), o) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/raven/contrib/django/models.py", line 154, in get_client instance = Client(**options) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/raven/base.py", line 141, in _init_ self.set_dsn(dsn, transport) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/raven/base.py", line 195, in set_dsn transport_registry=self._registry, File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/raven/conf/remote.py", line 69, in from_string raise InvalidDsn(ERR_UNKNOWN_SCHEME.format(url.scheme)) InvalidDsn: Unsupported Sentry DSN scheme: I had a below settings in settings.py file: RAVEN_CONFIG = { 'dsn': os.environ.get('SENTRY_DSN', ''), } I had tried to change it with RAVEN_CONFIG = { 'dsn': None } Or RAVEN_CONFIG = {} After that it gives me below error on console: Raven is not configured (logging is disabled). Please see the documentation for more information. And in browser it … -
Django profiling middleware
I want to write a profiling middleware in Django using cProfile. These are my basic requirements:- It should list the number of calls and time spent for each function It should inspect time spent for sql queries I came across some custom profiling middleware for Django on Github during my search, but I am not sure about how to use them and what results will they give as I am new to Django. A step by step explanation would be very helpful. -
Django Permission by Foreign Key
I have this Classes class Group(models.Model): GroupName = models.CharField(max_length=256) class Content(models.Model): Content = models.CharField(max_length=256) GroupName = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='Group') in Django i have some user accounts. How to Limit they rights on the Contentview by the groupname. So User A can only see Content where GroupName is "Content A" and User AB can see Content where GroupName is "Content A" and "Content B" Short, how to limit the view by permission on a attribute in a class A example: View from User A on Content: Content GroupName test1a A test2a A test3a A test4a A View from User AB on Content: Content GroupName test1a A test1b B test2a A test2b B test3a A test3b B test4a A test4b B So I can give permissions by Groupname -
Django-mptt inheritance for product category model
I am using mptt for my category model and I'm having issues with parent categories not inheriting their children's products. For example, if I have Men's Footwear(Top Level/Root Node) >> Men's Trainers(Subcategory/Leaf Node), Mens's footwear does not inherit any objects from the subcategory 'Men's Trainers'. I am importing products from a csv using a custom script which matches a regex in the category. Men's Footwear >> Regex: Mens Footwear Men's Trainers >> Regex: Mens Trainers How can I configure my model so that parent categories inherit their subcategories products. Models.py ` from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): regex = models.CharField(max_length=100, blank=True) name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name class Brand(models.Model): brand_name = models.CharField(max_length=500, default='') def __str__(self): return self.brand_name class Product(models.Model): aw_deep_link = models.CharField(max_length=500, default='') description = models.CharField(max_length=500, default='') product_name = models.CharField(max_length=500, default='') aw_image_url = models.CharField(max_length=500, default='') search_price = models.DecimalField(max_digits=6, decimal_places=2, … -
Django select_for_update with nowait=True not raising DatabaseError for conflicting transctions
According to Django docs: Usually, if another transaction has already acquired a lock on one of the selected rows, the query will block until the lock is released. If this is not the behavior you want, call select_for_update(nowait=True). This will make the call non-blocking. If a conflicting lock is already acquired by another transaction, DatabaseError will be raised when the queryset is evaluated. I was experimenting with this but found a strange behavior. Below code when run simultaneously doesn't raise the error but works in a blocking manner. def test4(): with transaction.atomic(): WorkflowCallContact.objects.select_for_update(nowait=True).filter(id__in=[1,2,3,4]).update(number="22222") time.sleep(10) list(WorkflowCallContact.objects.filter(id__in=[1,2,3,4])) To test, I am just opening to shells and calling the same function parallelly. But instead of throwing DatabaseError on the second call because of nowait=True, the call becomes blocked for 10 secs. Database I'm using: postgres Django version: 1.9 -
Django: How correctly show list of objects in related models?
I have 2 models: Product and Section. models.py: class Section(models.Model): name = models.CharField(max_length=255, blank=False, null=True,) class Product(models.Model): name = models.CharField(max_length=255, blank=False, null=True,) section = models.ForeignKey(Section,on_delete=models.CASCADE) I am trying to show list of sections with there products in template. I used for this task regroup tag but have some problems. 1) Sections without any product don't visible. How to show sections without products too? 2) In database some products has NULL value in section field. How to group this products to one section too? I will be grateful for any advice or example! =) views.py: context['products'] = Product.objects.select_related('section').order_by('section') template: {% regroup products by section as products_by_section %} {% for section in products_by_section %} {{ section.grouper}} {% for product in section.list %} {{ product }} {% endfor %} {% endfor %} -
Can't figure out how to query model in Django form
So what I'm trying to do might seem simple, yet complicated for me. I have these four models: Course, Lecture, Teacher and TeacherData. Firstly TeacherData and Teacher have a common field name teacher_ID, so when a teacher makes an account, it cannot be created unless his ID doesn't match the one from TeacherData. Secondly in the Course model, when a course is created, supervisor needs to specify a course teacher and a seminar teacher from the TeacherData model, so a supervisor doesn't need to wait for a teacher to create his account, to create a course. Thirdly, I have a form, where a teacher can add lectures to a specific Course. Problem is that all courses show for any teacher. A teacher has his own courses, unless a seminar teacher and a course teacher are appointed in same course. The problem: I do not know how to create the query which will allow the teacher to add lectures only to his courses. My logic is the following: Since Teacher and TeacherData share same teacher_ID, I could use that to access the same teacher(Teacher) as the one that teaches the course or seminar(TeacherData), and after that find a way to show … -
How do I multiply values in a query set in django correctly
I want to multiply two values in a queryset how do I achieve this: This is what I have : def get_adjustment(self): Adjustment.objects.filter(employee_month_id=1,adjustment_type=2) .values('exchange_rate','amount').aggregate(Sum('amount', field="exchange_rate*amount") -
Django form not saving data to database
I am making an app in django where users are asked a few questions about a business and their answers are stored in the database. I have registered the app in the admin section and can see it in the admin panel. However while submitting the form, the data doesn't seem to saved in the database although url review-sucess is shown. The admin section doesn't show any records inserted. models.py from django.db import models yes_or_no_choices = ( ('YES','Yes'), ('YES','No'), ) class ModelReview(models.Model): review_date = models.DateTimeField() business_name = models.CharField(max_length=200) user_review = models.TextField() user_name = models.CharField(max_length=50) forms.py from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from . import models class FormReview(forms.ModelForm): class Meta: model = models.ModelReview fields = '__all__' exclude = ['review_date'] views.py from django.http import HttpResponse from django.shortcuts import render, redirect from . import forms def FunctionReviewSuccess(request): return render(request, 'reviews/review-success.html') def FunctionPostReview(request): if request == 'POST': instance_form = forms.FormReview(request.POST.request.FILES or None) if form.is_valid: form.save() return redirect ('review-sucess') else: instance_form = forms.FormReview() return render(request, 'reviews/post-review.html',{'prop_form':instance_form }) post-review.html <h1>Post a review</h1> <form class="review-form" action="{% url 'review-success' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ prop_form }} <input type="submit" name="" value="Post Review"> </form> -
printing unquoted values from a nested dictionary in Ptython [on hold]
I have the following dictionary {'city': 'D', 'country': 'N', 'opentimes': [{'weekday': 'Mon-Sun', 'open': '00:00', 'close': '24:00'}], 'orders': 400, 'cards': ['x', 'y', 'z'], 'services': ['a', 'b', 'c']} The output does not print the nested key-val pair correct. I get the values as follows: D N [{'weekday': 'Mon-Sun', 'open': '00:00', 'close': '24:00'}] ['x', 'y', 'z'] ['a', 'b', 'c'] How can I print all the values without quotes and brackets, as: D N weekday: Mon-Sun, open: 00:00, close:24:00 x, y, z a, b, c -
How to reorganize django settings file?
I have this standard django generated settings: project/project | __init__.py | settings.py | urls.py | wsgi.py And it's working. However, I want to reorganize this layout to this: project/project/settings | __init__.py | base.py | __init__.py | urls.py | wsgi.py When I do it of course it's not working: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. So where and what I need to change in order this to work? -
Django Rest API : Add current User to User Field with Token Auth
Requirements : Python 3.7 Django 2.0 I'm working on my Django Rest API and I would like to add current user into my User field when an object is created but it doesn't work up to know. I'm using JWT Authentification with my API Rest. I followed this question : How to set current user to user field in Django Rest Framework? But it doesn't seem to work with my code. I have my serializers.py file : class IndividuCreateSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'Etat', 'Civilite', 'Nom', 'Prenom', 'Sexe', 'Statut', 'DateNaissance', 'VilleNaissance', 'PaysNaissance', 'Nationalite1', 'Nationalite2', 'Profession', 'Adresse', 'Ville', 'Zip', 'Pays', 'Mail', 'Telephone', 'Utilisateur', 'Image', 'CarteIdentite', ] def create(self, validated_data): obj = Individu.objects.create(**validated_data) Identity_Individu_Resume(self.context.get('request'), obj.id) return obj And my /Api/views.py file : class IndividuCreateAPIView(CreateAPIView) : permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) queryset = Individu.objects.all() serializer_class = IndividuCreateSerializer def user_create(self,serializer): serializer.validated_data['Utilisateur'] = self.request.user return super(IndividuCreateAPIView, self).user_create(serializer) In order to try my API, I configured a pythonic file which makes the same job than an other web application. This file looks like : import requests mytoken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IkFkbWluIiwiZXhwIjoxNTE5Mzc4MDExLCJlbWFpbCI6InZhbGVudGluQGRhdGFzeXN0ZW1zLmZyIiwib3JpZ19pYXQiOjE1MTkzNzQ0MTF9.7AKpbNEcdir2FLU064QzwwZGiylV-P7LBm1nOJIekwE" url = 'http://localhost:8000/Api/Identification/create/' filename1 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/pictures/photo.jpg' filename2 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/Carte_Identite/carte_ID.gif' files = {'Image' : open(filename1,'rb'), 'CarteIdentite': open(filename2,'rb')} data = { "Etat": … -
Bootstrap Navbar Toggle displaying in dev but not production environment
I've got a website set up with django and django-compressor for managing (ie merging & minifying) my static files. These are hosted by Amazon on S3. I'm using Bootstrap 4 and the MDBootstrap style library. The website is virtually identical in production and in my development environment, with the exception of the navbar-toggler-icon which displays in dev but not in production. It does still work in production, if you click/tap on where it should be it still opens the menu, it's just invisible. This is my production website - if you use dev tools to access the mobile view you will see that it is missing on the top-right corner of the navbar. The code is identical to my dev environment - the only difference is that it is being served from a different stylesheet, so for the life of me I can't figure out why it's not working. Any ideas on what could be going wrong? How do I even begin to debug this? -
Django - Can't set default DateTimeField value
When I save form with empty date and date_added fields in django-admin site then it saves empty values there. I want to save current time instead. Here's code: from django.db import models import datetime from django.utils import timezone # Create your models here. class Event(models.Model): def __str__(self): return self.title title = models.CharField(max_length=300) date = models.DateField(default=datetime.date.today, blank=True, null=True) date_added = models.DateTimeField(default=timezone.localtime, blank=True, null=True) text = models.TextField() class EventPhoto(models.Model): event_id = models.ForeignKey(Event, on_delete=models.CASCADE) photo = models.ImageField(upload_to='news/') Why default=timezone.localtime doesn't work? -
Unable to login with Django user
I am unable to login using the user credentials I have created using the Django admin. How can I fix it? I have created the Abstract user model and I am trying to notify the users before the given expiry date. Django code: settings.py- AUTH_USER_MODEL = 'myapp.User' models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from datetime import datetime, timedelta # Create your models here. class User(AbstractUser): u_id = models.CharField(max_length=10) m_expiry = models.DateTimeField(null=True,blank=True) days_left = 7 def expire_date( self ): return self.m_expiry + timedelta( days = self.days_left ) views.py from __future__ import unicode_literals from django.shortcuts import render from notifications.models import Notification from notifications import notify from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.contrib.auth.models import User import datetime User = get_user_model() # Create your views here. @login_required def home(request): notifications = request.user.notifications.unread().order_by('-timestamp') return render(request, 'index.html', {'notifications': notifications}) @login_required def send_notification(request): recipient_username = request.POST.get('recipient_username', None) expired = request.user.expire_date if recipient_username: recipients = User.objects.filter(username=recipient_username) else: recipients = User.objects.all() for recipient in recipients: if expired: notify.send( request.user, recipient=recipient, verb=request.POST.get('verb', '') ) return HttpResponseRedirect(reverse('home')) @login_required def mark_as_read(request): request.user.notifications.unread().mark_all_as_read() return HttpResponseRedirect(reverse('home')) Thank you. -
How to auto fill form fields with a instance of a Model?
In my Django project, I have a model named Customer. The model consists of products which have following entities: name, address, mobile_number and so on. When the user is entering name in the form. If the customer exists, name__istartswith=q (where q is the query i.e., user input) then it should suggest every customer that starts with q. Then user can select the customer that he needs other fields should be filled with that instance of the model. If no match found then it user should create a new customer.