Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django formset displaying wrong objects
when creating a new recipe post, I use two formsets for ingredients and directions. however, the new post formsets are being populated by existing ingredient and direction objects when they should be empty. here is my view for the new post and the forms: def post_new(request): form = PostForm() ingredient_form = IngredientFormSet(prefix='ingredient_form') direction_form = DirectionFormSet(prefix='ingredient_form') if request.method == "POST": form = PostForm(request.POST, request.FILES) ingredient_form = IngredientFormSet(request.POST, prefix='ingredient_form') direction_form = DirectionFormSet(request.POST, prefix='direction_form') if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() if ingredient_form.is_valid(): for i_form in ingredient_form: if i_form.is_valid() and i_form.has_changed(): i_form.instance.recipe = post i_form.save() if direction_form.is_valid(): for d_form in direction_form: if d_form.is_valid() and d_form.has_changed(): d_form.instance.recipe = post d_form.save() return redirect('post_detail', pk=post.pk) return render(request, 'blog/post_edit.html', {'form': form, 'ingredient_form': ingredient_form, 'direction_form': direction_form}) class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'image', 'text', 'prep_time', 'cook_time', 'servings_first', 'servings_second', 'tags'] IngredientFormSet = modelformset_factory(Ingredient, fields=['name', 'int_amount', 'float_amount', 'measurement' ], extra=15) DirectionFormSet = modelformset_factory(Direction, fields=['text', 'order' ], extra=25) -
Django Web Application Reverse for '/register' not found. '/register' is not a valid view function or pattern name
I'm new in Django, and have one problem. I'm learning with a book "Django Web Application" that is quite old I think. base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %}class="selected"{% endif %}> <a href="{% url 'dashboard' %}">Panel główny</a> </li> <li {% if section == "images" %}class="selected"{% endif %}> <a href="#">Obrazy</a> </li> <li {% if section == "people" %}class="selected"{% endif %}> <a href="#">Osoby</a> </li> </ul> {% endif %} <span class="user"> {% if request.user.is_authenticated %} Witaj, {{ request.user.first_name }}! <a href="{% url 'logout' %}">Wyloguj</a> {% else %} <a href="{% url 'login' %}">Zaloguj</a> {% endif %} </span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include, url import account.views urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls', namespace='app')), url(r'^account/', include('account.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py x2 from django.conf.urls import url from . import views from django.urls import path, include urlpatterns = [ #url(r'^login/$', views.user_login, name='login'), path('accounts/', include('django.contrib.auth.urls')), … -
How to add 2 codes into settings without overwriting
I have 2 projects one is website with image and one is just the music site im trying to bring music file into my site but the settings is giving me some issues. how do I add both directory's in settings.py without disrupting one or the other? This is the settings code I want to add PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '..', 'static'), ) MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') This is the code i don't want to overwrite as it leads to the html webpage. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'fork/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' -
Django DateField cannot be None
I'm really struggeling wih the DateTime cannot be None Issue of Django (3.0.4). I Know this is a known Issue on Stackoverflow but I'm not able to solve it. I do have the Field: begin_holidays = models.DateField(null=True, blank=True) And now if a submit a form where request.POST['begin_holidays'] is not set I get the error: „“ is invalid date format. It has to be YYYY-MM-DD Has anyone an Idea ? -
How can I dynamically serve files and then make them downloadable in Django?
I'm currently working on a project that deals a lot with iCalendar files. Where after the user searches for their name on my website I would like to have an option for them to add the events shown to their phone calendars. The way I imagined that could be done is by creating a .ics file and when users click it the file would begin downloading based on the name of the user. So what I have made so far is a Django view that that when the "Add to Calendar" button is pressed, the view is rendered. The view would then just get the name queried and get its ics_string or the calendar data. Here is the view that i've written so far def serve_calendar(request): name = request.GET.get('name', '') ics_string = get_calendar_details(name) #the portion of code that i can't figure out return response What I am missing is how do I send this file for download to the client's machine without the need to create it on the server. I've found some answers using io.StringIO and FileWrapeprs from the Django library however they have not worked for me. Other answers I've found use the X-SendFile but that would not … -
Trouble with deploying my website through Heroku
''' 2020-03-23T22:23:26.957835+00:00 app[api]: Release v6 created by user shirlimotro7@gmail.com 2020-03-23T22:23:26.957835+00:00 app[api]: Deploy 77a43bc3 by user shirlimotro7@gmail.com 2020-03-23T22:23:35.653714+00:00 heroku[web.1]: Starting process with command :gunicorn alarm-manager.wsgi 2020-03-23T22:23:38.067910+00:00 heroku[web.1]: Process exited with status 127 2020-03-23T22:23:38.082750+00:00 heroku[web.1]: State changed from starting to crashed 2020-03-23T22:23:38.086700+00:00 heroku[web.1]: State changed from crashed to starting 2020-03-23T22:23:37.994083+00:00 app[web.1]: bash: :gunicorn: command not found 2020-03-23T22:23:40.000000+00:00 app[api]: Build succeeded 2020-03-23T22:23:44.604910+00:00 heroku[web.1]: Starting process with command :gunicorn alarm-manager.wsgi 2020-03-23T22:23:47.251714+00:00 heroku[web.1]: State changed from starting to crashed 2020-03-23T22:23:47.108337+00:00 app[web.1]: bash: :gunicorn: command not found 2020-03-23T22:23:47.235221+00:00 heroku[web.1]: Process exited with status 127 2020-03-23T22:23:48.258412+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=manager-107.herokuapp.com request_id=49ed5309-e238-424a-afbe-5cee328e4af0 fwd="87.68.68.48" dyno= connect= service= status=503 bytes= protocol=https 2020-03-23T22:23:49.102443+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=manager-107.herokuapp.com request_id=beb755a6-f5e2-4128-a768-6e0a58de3b5f fwd="87.68.68.48" dyno= connect= service= status=503 bytes= protocol=https 2020-03-23T22:26:53.132132+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=manager-107.herokuapp.com request_id=dd3f11e9-fb9f-4b74-9ac7-89fd20f1249f fwd="87.68.68.48" dyno= connect= service= status=503 bytes= protocol=https 2020-03-23T22:26:55.313805+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=manager-107.herokuapp.com request_id=f942f0c3-22cb-437b-b1f1-b55b8155e93c fwd="87.68.68.48" dyno= connect= service= status=503 bytes= protocol=https 2020-03-23T22:26:55.768444+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=manager-107.herokuapp.com request_id=45e88074-0f32-4f45-be2b-1033c638dd17 fwd="87.68.68.48" dyno= connect= service= status=503 bytes= protocol=https 2020-03-23T22:34:51.007678+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=manager-107.herokuapp.com request_id=8f3afe93-2915-448d-8896-f5fdd9e711fe fwd="87.68.68.48" dyno= connect= service= status=503 bytes= protocol=https 2020-03-23T22:45:01.620001+00:00 heroku[web.1]: State changed from crashed to starting 2020-03-23T22:45:08.107720+00:00 heroku[web.1]: … -
How to display img file in django template?
I know the title is a bit misleading but I explain everything. I am in the process of creating a store in django and there is a small problem that I do not know how to work around. Well, for each product I want to assign several photos that I save in the database. That's why I created the Photo model, which is connected to the Book model with a ForeignKey. The whole problem is that I do not know how to indicate on the store's home page one of the photos that is assigned to a specific book. Of course, there are many books on the page that are generated in a for loop. If it is helpful, I save the pictures for each book in a separate folder, the function content_file_name is responsible for that Of course, I am open to other ideas to achieve such an effect as described above. I am not sure if the path I have chosen is optimal. #models.py def content_file_name(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (instance.book.slug, ext) return os.path.join('books_img', instance.book.slug, filename) class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=300) publisher = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField() seller … -
Custom HTML Login Form with Django Registration Redux
How can I send the Input Data from my Form to the Django Registration Redux Backend? I know about Crispy Forms but I want to use my custom bootstrap html form. <form role="form"> <div class="form-group"> <label class="form-control-label">Email address</label> <div class="input-group input-group-merge"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input type="email" class="form-control" id="input-email" placeholder="name@example.com"> </div> </div> <div class="form-group mb-4"> <label class="form-control-label">Password</label> <div class="input-group input-group-merge"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> <input type="password" class="form-control" id="input-password" placeholder="********"> <div class="input-group-append"> <span class="input-group-text"> <a href="#" data-toggle="password-text" data-target="#input-password"> <i class="fas fa-eye"></i> </a> </span> </div> </div> </div> <div class="mt-4"><button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill" value="Log in"> <span class="btn-inner--text">Create my account</span> <span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span> </button></div> </form> -
Characters like ' in Django Template. Probably unicode error
I have in Django view the following string string = "'DE', 'FR', 'IT'" which is transfered to a template: return render(request, 'template.html', {'string':string}) In the template I get this string as follows: &#x27;DE&#x27;,&#x27;FR&#x27;,&#x27;IT&#x27; The problem is that this "'" symbol gets a strange translation; How shall I transfer this string to template? Thank you -
Where do I place the logic for validating and transforming a request to a model object in DRF?
I have a working python app that I'm trying to transform in a webapp using django and django rest. For now, I just want to do a post request containing some data: { "orderside" :"long", "symbol" : "BTCUSDT", "leverage" : "20", "entry_price" : "100", "order_cost" : "5.2", "sl_price" :"99.4", "tp_price" : "101.2" } Based on this data, I need to do some validity checks and some calculations. If the data is valid, I want to persist the results as a Trade entity in the database (no 1 to 1 mapping from request to model). This is the model for a Trade: from django.db import models class Trade(models.Model): created_datetime = models.DateTimeField(auto_now_add=True) entry_filled_datetime = models.DateTimeField() tp_sl_filled_datetime = models.DateTimeField() orderside = models.CharField(max_length=10) symbol = models.CharField(max_length=10) leverage = models.PositiveSmallIntegerField() entry_price = models.FloatField() quantity = models.FloatField() sl_price = models.FloatField() tp_price = models.FloatField() entry_id = models.CharField(max_length=25) tp_id = models.CharField(max_length=25) sl_id = models.CharField(max_length=25) state = models.PositiveSmallIntegerField() side = models.CharField(max_length=10) class Meta: ordering = ['created_datetime'] Where do I have to put the code for validation of the request data , and where do I put the calculation logic? Can I put both in the view class, like below? And where does a serializer fit in to this? class … -
Trouble with media directory/files on pythonanywhere
I seem to be having an issue serving up media content on my website. Everything works fine when run on localhost. However, when deployed to python anywhere, I receive a FileNotFoundError when I attempt to upload an image via a form. I've taken a look through overflow for some related topics however I've not found any threads which have allowed me to solve my problem. Here is the exact error received when submitting the image upload form: It seems to be an issue with the resize method in models.py (which works fine on localhost) Here are the appropriate setup files: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' IMAGES_DIR = os.path.join(MEDIA_URL,"images") I believe the error is due to the images_path method not retuning the correct location (but it works on localhost). Here is the model which stores the image and defines how images are saved: models.py class Image(models.Model): # this might work? def images_path(): return os.path.join(settings.IMAGES_DIR, 'usruploads') def resize(self): im = PIL.Image.open(self.image) size=(200,200) out = im.resize(size) out.save(self.image.__str__()) def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) self.resize() image = models.ImageField(upload_to=images_path()[1:], max_length=255) I will also throw in the media directory structure of the … -
How do I get Django to run a case-insensitive query against my MySql 5.7 db?
I'm using Django 2.0 and Python 3.7. I have this model and manager for attempting to find my model by a name, case-insentively. The backing database is MySql 5.7. class CoopManager(models.Manager): ... # Look up coops by a partial name (case insensitive) def find_by_name(self, partial_name): queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True) print(queryset.query) return queryset class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() Unfortunately, when the query actually gets created, it doesn't appear Django is doing anything to account for case-insensitivity. This is an example query that results ... SELECT `maps_coop`.`id`, `maps_coop`.`name`, `maps_coop`.`type_id`, `maps_coop`.`address_id`, `maps_coop`.`enabled`, `maps_coop`.`phone`, `maps_coop`.`email`, `maps_coop`.`web_site` FROM `maps_coop` WHERE (`maps_coop`.`name` LIKE %res% AND `maps_coop`.`enabled` = True) What changes do I need to make so that Django executes the query in a case-insensitive way against my MySql database? -
Make a string with a UTC+1 date aware
Using the below code which prints 2020-05-02 15:59:00+00:00. Shouldn't it subtract 1 hour and print 2020-05-02 14:59:00+00:00? TIME_ZONE = 'UTC' and USE_TZ = True in settings.py. from datetime import datetime from django.utils.timezone import make_aware str_date = "02-05-2020 15:59" # UTC+1 dt = make_aware(datetime.strptime(str_date, '%d-%m-%Y %H:%M')) print(dt) This subtracts 1 hour from my Ubuntu machine date from django.utils import timezone now = timezone.now() print(now) -
Django DRF @permission_classes not working for IsAdminUser permission
I want to apply IsAdminUser permission on my view. I am able to do it by setting the permission_classes attribute: class UserProfileView(APIView): permission_classes = [IsAdminUser,] def get(self, request, pk=None): ... However, if I try to do the same using decorator then it seems to be ineffective and checks only for authenticated users. class UserProfileView(APIView): @permission_classes([IsAdminUser]) def get(self, request, pk=None): ... I want to understand why is it behaving so. Am I doing anything wrong? My environment configuration: Python==3.7.6, Django==2.2.10, djangorestframework==3.11.0, django-oauth-toolkit==1.2.0 -
Best Way to Handle user triggered task (like import data) in Django
I need your opinion on a challenge that I'm facing. I'm building a website that uses Django as a backend, PostgreSQL as my DB, GraphQL as my API layer and React as my frontend framework. Website is hosted on Heroku. I wrote a python script that logs me in to my gmail account and parse few emails, based on pre-defined conditions, and store the parsed data into Google Sheet. Now, I want the script to be part of my website in which user will specify what exactly need to be parsed (i.e. filters) and then display the parsed data in a table to review accuracy of the parsing task. The part that I need some help with is how to architect such workflow. Below are few ideas that I managed to come up with after some googling: generate a graphQL mutation that stores a 'task' into a task model. Once a new task entry is stored, a Django Signal will trigger the script. Not sure yet if Signal can run custom python functions, but from what i read so far, it seems doable. Use Celery to run this task asynchronously. But i'm not sure if asynchronous tasks is what i'm … -
.Net entity framework pendant for Django shell
I was used to program in Django where you have a shell. This is basically a Python interpreter where you can program in Python and can query your database. For example you open a shell from a Linux terminal with python manage.py shell Then you can query your database using Python code for example like this: print(apartment.rooms.count()) for room in apartment.rooms: print(room.square_meters) Thats really convenient because you can query your database, test some algorithms and don't have to touch your productive code. Now I am working in .Net Core and write an MVC application. But I haven't found something similar so far. Is there something similar? Or how do you add/delete/update your database during development in .Net (using entity framework)? -
Creating a photo gallery with comments in Django
I am in the process of putting together a website where people can post pictures and comment on the pictures. I have created a page where people can add pictures, and a gallery page, where pictures are displayed. I have also created a comments model (with a ManyToMany image field) and comments form for users to add comments. I am not clear on how I put a comment form beneath each of the images, and to make it so that any comments posted are associated with the relevant image (and appear beneath it). I have done a bit of googling, and can't find any guides that show me how to do this. What advice would you give me, please? Thank you. Jeff -
How can I resolve role errors in postgres? "ERROR: createdb: error: could not connect to database template1: FATAL: role 'John' does not exist"
So I'm going through a Django course using postgres, and I've been stuck on the same error for a few hours. I'm on Windows, and know that postgres likes to default to the name on the OS (in this case, it's John) when trying to log in or creating a database. So I did a few things: created a username named "john" with CreateDB privileges, changed the pg_hba.conf "md5" setting to "trust", then looked at all the roles with the psql \du command: Role name | Attributes john | Create DB demo | Superuser, Cannot login postgres | Superuser, Create role, Create DB, Replication, Bypass RLS But the problem is still the same. Whenever I try to createdb, just to test things, I get this error: createdb: error: could not connect to database template1: FATAL: role "John" does not exist I noticed that "John" is capitalized. I made sure to capitalize "John" when creating the role, but it just defaults to "john" automatically in the role name, so the "John" must still be referring to the OS name. How is this error solved? I assume it must be common, since I see tons of references to it, but none of … -
Why this intermediate Django page won't get back to the former action?
This is Django 1.11.29 and I'm trying to write a simple Django admin action with an intermediate page. I've seen something like this has been asked here but even following the response advice I can't manage to solve it. In my ModelAdmin I have this: from django.contrib.admin import helpers from django.shortcuts import render class MyModelAdmin(admin.ModelAdmin): ... actions = ['send_email'] ... So I implemented my send_email action like this: def send_email(self, request, queryset): print(request.POST) print(queryset) if 'apply' in request.POST: # Do some stuff else: return render(request, 'admin/confirm_email.html', { 'mymodels': queryset, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME }) This is pretty standard according to the Django documentation. The admin/confirm_email.html looks like this: {% extends "admin/base_site.html" %} {% block content %} <p>You're about to send a lot of mails!</p> <form action="" method="post"> {% csrf_token %} {% for mymodel in mymodels %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ mymodel.pk }}" /> {% endfor %} <br /> <input type="button" value="Cancel" onClick="history.go(-1); return true;" /> <input type="submit" name="apply" value="Confirm" /> </form> {% endblock %} The problem is that when the admin action is invoked, it enters the intermediate page, but when hit Confirm in the intermediate page, it won't call the admin action back, so I cannot process the answer. … -
Django redirecting to a wrong url
when i click submit on my form it goes to ../register/register/ where as my expectation is that it should go to ../register This is my main project urls.py urlpatterns = [ path('participants/', include('participants.urls')), path('admin/', admin.site.urls), ] This is my application urls.py urlpatterns = [ path('register/', views.register, name="register") ] This is my views function def register(request): if request.method == "POST": username = request.POST['username'] # email = request.POST['email'] password = request.POST['pass'] print(username, password) user = User.objects.create_user(username=username, password=password) user.save() return redirect('register') else: return render(request, 'register.html') -
Django template for loop is empty
I am trying to build a detail view in django, but nothing is displayed in the template. views.py class MyDetailView(DetailView): model = Article template_name = 'detail.html' detail.html {% extends 'base.html' %} {% load i18n %} {% endblock %} {% block content %} {% for item in itemlist %} {{item.pk}} {{item.title}} {% empty %} There are no items in this list {% endfor %} {% endblock %} Why is nothing displayed in the template here? -
KeyError at / "https://pbs.twimg.com/media/EUDjMHoWsAERZ83.jpg'"
I want to access the number of retweets and number of likes on a tweet that I get using twitterAPI. I have written the following code with some help from other sources. I am not able to understand the reason for this error. The error is in line 88 of the code. Please help me out. I am attaching the image for the error. views.py: from django.shortcuts import render from TwitterAPI import TwitterAPI from Post.models import Album import calendar from django.contrib.auth.models import User import requests import http.client,urllib.request,urllib.parse,urllib.error,base64,sys import simplejson as json consumer_key='RNBUUEtazKVJemcMedGHWgMCV' consumer_secret='zILQDS386Dd4WRr8810gD5WAGbfkeVRDT3BYWs7RKChY1U7duM' access_token_key='893345180958564352-UT4mqHeDQyYllebzbsIPItOCyjHs8eP' access_token_secret='Gv2pbj6eeKvKPWjbePfO71la7xOeib2T5lV4SaL86UUdj' api = TwitterAPI(consumer_key,consumer_secret,access_token_key,access_token_secret) me = User.objects.get(username='vedant') def newsfeed(request): hashtag_string = '#Swachh_Bharat' hashtag_string = hashtag_string.lower() if(request.GET.get('mybtn')): hashtag_string = str(request.GET.get('hashtag')) print("HashtagString :: ",hashtag_string) if hashtag_string == '#vedant': url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] url_list_in_database = Album.objects.all().filter(user = me).values('image_url') temp = Album.objects.all().filter(user = me).values('image_url','date','retweet_count','like_count') url_list = {} for entry in temp: dt = str(entry['date'])[0:10] dt = calender.month_name[int(dt[5:7])]+" "+ dt[8:10]+"," + dt[0:4] url_list[str(entry['image_url'])] = (dt, str(entry['retweet_count']),str(entry['like_count'])) return render(request, 'Post/newsfeed.html', {'url_list': url_list}) #get the images of particular hashtag else: url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] r = api.request('search/tweets',{'q':hashtag_string,'filter':'images','count':1000}) url_dict = {} for … -
Django with react depkoyment on google cloud
Im trying to build server for my project where frontend is react and backend is django. I did it locally works just fine, but how I should deploy it on google cloud platform, i want to make it live through external ip of my virtual machine. I tried everything what i found on google, but usually all guides are for localhost. -
How to redirect user to login page while adding items to cart?
I am newbie to django. I am creating simple order system. I want only logged in user to add items in cart. If user is not looged in, redirect user to login page and after logged in again redirect user to previous page. This is my views.py @require_POST @login_required def cart_add(request, dish_id): cart = Cart(request) dish = get_object_or_404(Dish, id=dish_id) form = CartAddDishForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(dish=dish, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') -
how to filter user created by another superuserso that it can send notice
in my forms.py class NoticeFormWarden(forms.ModelForm): class Meta: model = Noticee fields = ('name','description','users','file',) def save(self,user): owner = user issue_date = datetime.datetime.now().strftime("%Y-%m-%d") name = self.cleaned_data['name'] description = self.cleaned_data['description'] users = self.cleaned_data['users'] file = self.cleaned_data['file'] Noticee.objects.create(name=name, description=description, users=users, file=file, owner=owner, issue_date=issue_date) def __init__(self, users, *args, **kwargs): super(NoticeFormWarden, self).__init__(*args, **kwargs) self.fields['users'].queryset = User.objects.filter(is_hostelstaff=True) self.fields['name'].widget.attrs['placeholder'] = ' Subject' self.fields['file'].widget.attrs['placeholder'] = ' Subject' self.fields['description'].widget.attrs['placeholder'] = 'write your msg here . . .' self.helper = FormHelper() self.helper.form_show_labels = False in views.py def WardenCreateNotice(request): form = NoticeFormWarden(request.user, request.POST or None) if request.method == 'POST': if form.is_valid(): print('Saved notice') form.save(request.user) form = NoticeFormWarden(request.user) return redirect("warden_view:notice-warden2") context = { 'form': form, 'user': request.user, } return render(request, 'warden_view/notice.html',context) i have four type of user. admin,warden,staff,student admin create warden warden create staff and staff create student . now i want send notice so that admin send notice to warden and warden send notice to their created staff note that one warden has many staff and it can send notice to its only staff so how can i filter specific warden created staff