Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter to be applied even when pagination
class ActionView(View): def get(self, request): client = request.user.client page_number = request.GET.get('page', '1') status_filter = request.GET.get('status', '') jobs = Job.objects.filter( client=client, action_status__isnull=False).order_by('-due_date') if status_filter in ['open', 'dismissed', 'done']: jobs = jobs.filter(action_status=status_filter) paginator = Paginator(jobs, 3) try: page = paginator.page(page_number) except PageNotAnInteger: # If page is not an integer, deliver first page. page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. page = paginator.page(paginator.num_pages) return render(request, 'action_required.html', {'jobs': jobs, 'page': page, 'status_filter': status_filter}) template: action_required.html Job No. Date Title Customer Address Action required Action Action By {% if jobs|length %} {% for job in page %} <td> {{ job.job_number }}</td> <td>{{ job.due_date|date:'d/m/Y' }}</td> <td>{{ job.title }}</td> <td>{{ job.contact }}</td> <td>{{ job.contact_info }}</td> {% endfor %} {% endif %} {% bootstrap_pagination page %} Here when apply filter and do pagination my filter is getting loosed.Now i want if status filter is selected as 'done' and applying pagination all status are getting displayed but it should display only 'done' status even after applying pagination. -
How to get sql data at template in Django?
I want to get SQL data directly to a template in Django with below code {% if {{item.image_amount}} > 0 %} But error message appears Could not parse the remainder: '{{item.image_amount}}' from '{{item.image_amount}}' In order to get SQL data directly to template, how can I write code? models.py class TestEu(models.Model): id = models.TextField(blank=True, primary_key=True) national = models.TextField(blank=True, null=True) image_amount = models.IntegerField(blank=True, null=True) view.py class DbList(ListView): model = TestEu paginate_by = 100 ... ... sql += " where eng_discription ~* '\y" +n_word+"\y'" object_list = TestEu.objects.raw(sql) return object_list testeu_list.html {% for item in object_list %} {% if {{item.image_amount}} > 0 %} <td><img src="{% static 'rulings_img/' %}{{item.item_hs6}}/{{item.id}}-1.jpg" width="100" height="100"> {{item.image_amount}}</td> {% endif %} -
Django - How to annotate count() of distinct values
I have the following model: class Bank(model.Model): name: models.CharField .... Using the following sample data: ╔══════════════╗ ║ Row ID, Name ║ ╠══════════════╣ ║ 1, ABC ║ ║ 2, ABC ║ ║ 3, XYZ ║ ║ 4, MNO ║ ║ 5, ABC ║ ║ 6, DEF ║ ║ 7, DEF ║ ╚══════════════╝ I want to extract distinct bank names like so: [('ABC', 3), ('XYZ', 1), ('MNO', 1), ('DEF', 2)] I have tried using annotate and distict but the following error is being raised: NotImplementedError: annotate() + distinct(fields) is not implemented. I've also come accross the following question on SO: Question 1 Which has answers on using models.Count('name', distinct=True) but it's returning duplicate values. How can I handle this using Django ORM? -
How to dynamically select storage on the basis of model fields?
This is a duplicate question to this Django dynamic models.FileField Storage, but the question is not answered with correct solution yet. I also have the similar use case. I need to dynamically change the storage on the basis of the model field. I have tried using the callable for storage https://docs.djangoproject.com/en/3.1/topics/files/#using-a-callable. But I think this callable gets called before the model field values are initialized. Please suggest how can I do this. -
why when I click a different user returns me back to the current request user?
sorry, I had to take some screenshots to explains what is going on with me. now, I have much profile that has many different users and when I log in with one of it I'll assume the username is: medoabdin like you find on the screenshot now (medoabdin) and the name of it is (Origin) for me is a current user request. so, now I have also many different questions created by the different users, and when I want to enter any other profile let's suppose the user is (abdelhamedabdin) by current request user it returns me back to the current request (medoabdin) and not returns me back to abdelhamedabdin. however, when I check the link URL I find the link is correct and when I log in with (abdelhamedabdin) user I see the same thing occurs to me against (medoabdin) so, can anyone tell me what is going on guys? these are screenshots: current request (medoabdin), several questions, show the link url for different users, accounts/profile.html {% extends 'base.html' %} {% block title %} {{ user.first_name }} {{ user.last_name }} Profile {% endblock %} {% block body %} <!-- User Profile Section --> {% if user.is_authenticated %} <div class="profile"> … -
how to create a link which points to the a potion of a chapter by using ebooklib python
I developing an application in DJango python to create EPub fies dynamically. I am using CKEditor and ebooklib. But I have a doubt with TOC, My intention is to create a link in TOC which points to the a potion of a chapter. We can create the same as section and link to chapter but when i create so section load as a separate page,see its sample code below Please see the sample code c2 = epub.EpubHtml(title='About this book', file_name='about.xhtml') c2.content='<h1>About this book</h1><p>Helou, this is my book! There are many books, but this one is mine.</p>' c2.set_language('hr') c2.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none') c2.add_item(default_css) # add chapters to the book book.add_item(c1) book.add_item(c2) # create table of contents # - add manual link # - add section # - add auto created links to chapters book.toc = (epub.Link('intro.xhtml', 'Introduction', 'intro'), (epub.Section('Languages'), (c1, c2)) ) But when I execute I will get section in a separate page.My intention is to point to the section of the chapter, not as a separate page. (its like pointing to a subheading in chapter) and add section link in TOC (table of contents). Please help ? Thanks -
How to setup a AWS Cloudwatch scheduled Event to call a function in Django(AWS Lambda)
I am running a Serverless Django Rest API on AWS Lambda. I would like to call a specific function in Django regularly. How should I setup the scheduled call by using Cloudwatch event? I can select the Lambda function in the Cloudwatch trigger but I can't specific the function that I want to use? How to pass the parameters to the Lambda function? Is there any suggestions? Thanks~ -
Unblocking the web server?
I am using the below given function in python flask to download file stored in telegram cloud.Everything is working fine, the problem arises when size of file is large, it blocks whole web server until the download is complete. So please tell me how I can make it run parallel without blocking the server. def ping_me(chat_id,user,im_name): os.system('tgcloud -m download -n admin_helper -u "assignment_collector_bot" -p "portal/static/documents/users/"'+str(user.telegram_id)+'"/temp/" -c "'+im_name+'"') return Response('ok',status=200) -
aws media files not showing
I'm using aws s3 to store media files for a Django app, I install boto3 and django-storages. It uploads files to aws but the file does not render. I opened the link and see this message <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>15134F3A4F5CCB2B</RequestId> <HostId>ieKre9JIipHoSqal7QUt/jTPQY5hdrsfI95cyLQAtVIjM8r+OnjhDIGYH6cDpJQr1wXu71foxek=</HostId> </Error> My configs are: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None I really don't have much to go on from the error message, where do I use this AWS4-HMAC-SHA256 on aws? Any help will be appreciated. -
Styling non field errors with django crispy form?
I am using crispy forms to style my form.But I want to customize non field error.It's showing as list.I know how to modify with custom CSS.But is there any other way to do this. I want the non field error to be shown as in second image -
What parameters to give an image tag to display an Django image from image.url in database
What keywords should I pass in to an img tag to display an image? my current line is like this: <img src="{{ skill.image.url }}"> models.py: from django.db import models # Create your models here. class Skill(models.Model): name = models.CharField(max_length=100) class Type(models.IntegerChoices): WEBDEV = 1 SOFTWARE = 2 DATABASE = 3 type = models.IntegerField(choices=Type.choices) image = models.ImageField(upload_to='img', blank=True) def __str__(self): return self.name -
React: TypeError: Cannot read property 'match' of undefined
I am using simple React-Django app. I have Django models orders, customer and products. Orders model have many to one relationship with customer and products. I successfully connect my frontend React with Django and able to show the Orders data in React. I want display single customers order and the data looks like this image. In React I made router home and customer Details like this in my app <Router> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/customer/:id" component={PersonDetail} /> </Switch> </Router> After fetching the Order-list. I fetched customer's name and create one link and that link direct to Customer-detail page. From there I was trying fetch single user's product purchase detail but I am getting error: TypeError: Cannot read property 'match' of undefined and in my django backend I am getting this error : ValueError: Field 'id' expected a number but got 'undefined'. I don't what I am doing wrong This is my orderlist const [state, setstate] = useState([]) useEffect(() => { getData() }, []) const getData = async () => { const order = await fetch('http://127.0.0.1:8000/api/order-list/') const orderData = await order.json(); console.log(orderData); setstate(orderData) } return ( <> <div className="App"> { state.map((person: any, index: number) => { return … -
How to send notification to admin when data is stored
I (admin) want to create a way to be notified via email every time a user presses send with their question from the comment page. The site is not setup for a user to create a profile. I have been looking at django-signals but I can't find an example that fits my issue. -
Difficulty in implementing search feature for a django project
This is the path i've set to my urls.py file inside the encyclopedia directory: path("encyclopedia/search.html", views.search, name="search"), This is the view: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): querry = form.cleaned_data['querry'] data = util.search_entry(querry) if data is None: return HttpResponse("No matches found!") else: return render(request, "encyclopedia/search.html", { "result":data }) search.html extends layout.html and {{ result }} is simply passed inside the body block. Added the util function search entry as follows: def search_entry(querry): _, filenames = default_storage.listdir("entries") if querry in entries: return querry else: results = [] for entry in filenames: if re.search( querry, entry ): results.append(entry) if not results: return None else: return results And finally, the form template in layout.html: <form action="encyclopedia/search.html" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> {{ form }} </form> But whenever i enter anything, i get the same error " The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. " I am unable to figure this out... -
CSRF token in angular 2
I am coding a simple login,it is working with @csrf_exempt but when I remove it I get the forbidden error. I looked a lot but cant fix it, Please do explain and help me. Django code: @csrf_exempt # @api_view(['POST']) def login(request): if request.method == 'POST': print(request.COOKIES) sadmin_data = JSONParser().parse(request) print(sadmin_data) users = auth.authenticate(email = sadmin_data["email"],password = sadmin_data["password"]) if(users): auth_token = jwt.encode({'email':users.email}, settings.JWT_SECRET_KEY) serializer= LoginSerializer(users) data={ "user":serializer.data,"token":auth_token.decode('utf-8'),"type":users.usertype } return JsonResponse(data,status=status.HTTP_201_CREATED) else: content = {'message': 'Please Contact the developers'} return JsonResponse(content, status = status.HTTP_404_NOT_FOUND) Angular Code: <form (ngSubmit)="onSubmit()"> <div class="card-body"> <div class="example-container"> <mat-form-field appearance="standard"> <mat-label>Enter your email</mat-label> <input matInput placeholder="pat@example.com" [(ngModel)]="sadmin.email" name="email" required> <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error> </mat-form-field> </div> <div> <mat-form-field appearance="standard"> <mat-label>Enter your password</mat-label> <input matInput [type]="hide ? 'password' : 'text'" [(ngModel)]="sadmin.password" name="password" > <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide"> <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon> </button> </mat-form-field> </div> <button mat-raised-button class="login-btn" type="submit">Login</button> </div> </form> Also When I print the cookies I get {}. -
How to Get Last Inserted id in Django Slug?
I am trying to create a unique slug, on the basis of last inserted id in my Django Project, But I am unable to get last Inserted id in my Slug, Please elt me know Where I am mistaking. Here is my models.py file... class ProjectStatus(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, default= None, related_name="ProjectStatusCity", help_text=f"Type: Int, Values: Select City Name.") name = models.CharField(max_length=190, default=None, help_text=f"Type: string, Default: None, Values: Enter Project Status.") slug = models.SlugField(max_length=190, unique=True, default='', editable=False, help_text=f"Type: String, Default: None, Values: Enter Slug.") meta_title = models.CharField(max_length=190, default=None, help_text=f"Type: string, Default: None, Values: Enter Project Status.") def __str__(self): return self.name def get_absolute_url(self): kwargs = { 'pk': self.id, 'slug': self.slug } return reverse('article-pk-slug-detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.name + "-" + "prsid" + "-" + "city" + "-" + "s" self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) I want the last inserted id after s in thsi line (value = self.name + "-" + "prsid" + "-" + "s"), And I have relation with city so I want city name also here, Please help me to solve this issue. -
How to turn a Django Rest Framework API View into an async one?
I am trying to build a REST API that will manage some machine learning classification tasks. I have written an API view, which when hit, will trigger the start of a classification task (such as: training an SVM classifier with the data the user provided previously). However, this is a long running task, so I would ideally not have the user wait once they have made a request to this view. Instead, I would like to start this task in the background and give them a response immediately. They can later view the results of the classification in a separate view (haven't implemented that yet.) I am using ASGI_APPLICATION = 'mlxplorebackend.asgi.application' in settings.py. Here's my API view in views.py import asyncio from concurrent.futures import ProcessPoolExecutor from django import setup as SetupDjango # ... other imports loop = asyncio.get_event_loop() def DummyClassification(): result = sum(i * i for i in range(10 ** 7)) print(result) return result # ... other API views class TaskExecuteView(APIView): """ Once an API call is made to this view, the classification algorithm will start being processed. Depends on: 1. Parser for the classification algorithm type and parameters 2. Classification algorithm implementation """ def get(self, request, taskId, *args, **kwargs): … -
Best way of using Django queryset where JSONField != {}
class JobAnalysis(Base, XYZ): env_vars = JSONField( default=dict ) job = models.ForeignKey( Job, related_name='jobanalyses' ) seller = models.ForeignKey( ABC, null=True ) class Usage(Base): job = models.ForeignKey( Job, null=True, blank=True ) I want all usages where env_vars has some key pair. usages_qs = Usage.objects.filter( job__jobanalyses__seller__isnull=True ).exclude( job__jobanalyses__env_vars__exact={} ) I am using above queryset to fetch all usage information where seller is null and env_vars is not equals {} usages_qs.query SELECT "Usage"."job", FROM "Usage" LEFT OUTER JOIN "Job" ON ("Usage"."job_id" = "Job"."id") LEFT OUTER JOIN "JobAnalysis" ON ("Job"."id" = "JobAnalysis"."job_id") WHERE ("JobAnalysis"."seller_id" IS NULL AND NOT ("Usage"."job_id" IN (SELECT U2."job_id" FROM "JobAnalysis" U2 WHERE U2."env_vars" = '{}') AND "Usage"."job_id" IS NOT NULL)) But I am seeing performance issue here because .exclude(job__jobanalyses__env_vars__exact={}) create inner query and because of that this select statement is timing out. Is there any better way of writing Django queryset for getting all usage record where seller is null and env_vars != {}? -
django each user needs to create and view data Issue
I have build a simple application for Creating User data, starting from user registration till the CRUD operation. now I want to extend the application to multiple users. i.e. A user can login and does CRUD likewise B user can login and does CRUD operation so on...C,D,E,F,G etc... Each individual user should able to see its own data .... for that i have used decorators/groups ...etc.. My problem is how to pass particular user data into view to see the particular user data like tasks = request.user.Task.objects.all() for this, I am getting error Internal Server Error: /query/ Traceback (most recent call last): File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\s5114509\PycharmProjects\todo Modified\tasks\decorators.py", line 21, in wrapper_function return view_func(request,*args,**kwargs) File "C:\Users\s5114509\PycharmProjects\todo Modified\tasks\views.py", line 107, in query tasks = request.user.Task.objects.all() File "C:\Users\s5114509\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'Task' [15/Oct/2020 23:07:22] "GET /query/ HTTP/1.1" 500 83300 - Model from django.contrib.auth.models import User from django.db import models # Create your models here. from … -
Jumbotron and background images disappear when the window size changes from full screen to small
Have an issue with my homepage, the jumbotron/background images disappear when the window size changes from full screen to small screen, when it's resized the background/jumbotron images re-appear,how can the images be made responsive ? Below is the styling: <style type = "text/css"> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; position:center; background-size:cover; background-attachment:fixed; } .jumbotron{ margin-top:20px; background-image:url("{% static '9.jpg'%}" ); background-repeat:no-repeat; background-size:cover; position:center; color:white; } body{ background-image:url("{% static '8.jpg' %}"); background-repeat:no-repeat; background-size:cover; background-position:center center; background-attachment:fixed; overflow:visible; } -
ValueError at / empty range for randrange() (0, 0, 0) Django Hosting
File "/root/payyannuronline/webapp/views.py", line 61, in indexrandom_ads=ads.objects.all()[randint(0,count - 1)]File "/usr/lib/python3.8/random.py", line 248, in randintreturn self.randrange(a, b+1)File "/usr/lib/python3.8/random.py", line 226, in randrangeraise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))ValueError: empty range for randrange() (0, 0, 0) Views.py def index(request): count=ads.objects.count() random_ads=ads.objects.all()[randint(0,count - 1)] return render(request,'index.html',{'nbar': 'index','random_ads':random_ads}) Tenmplate <div class="container"> {% load static %} <img class="mySlides" src="/media/{{ random_ads.cover }}" alt="{{ random_ads.title }}" style="width:100%"> Models.py class ads(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=260) owner = models.CharField(max_length=260) contact = models.IntegerField(null=False) email = models.EmailField(null=True) subject = models.CharField(max_length=360,null=False) description = models.TextField(max_length=2600) cover = models.ImageField(upload_to='images/ads/', default=None) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True,) validity = models.DateField(null =False) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Python code execute through django shell but not through file
I recently installed the python library riskchanges. Now I created the test_lib.py file and try to use the library function as below, from RiskChanges.load_SHP import loadshp loadshp(r'F:\SDSS\1. code\data\Country_border.shp', connstr='postgresql://postgres:admin@localhost:5432/sdss', lyrName='layer', schema='try') And I tried to run this code from the terminal, (python test_lib.py), it shows the following error, Traceback (most recent call last): File "test_lib.py", line 2, in <module> loadshp(r'F:\SDSS\1. code\data\Country_border.shp', File "F:\SDSS\1. code\django\venv\lib\site-packages\RiskChanges\load_SHP.py", line 39, in loadshp geodataframe = geopandas.read_file(shpInput) File "F:\SDSS\1. code\django\venv\lib\site-packages\geopandas\io\file.py", line 139, in _read_file return GeoDataFrame.from_features( File "F:\SDSS\1. code\django\venv\lib\site-packages\geopandas\geodataframe.py", line 427, in from_features "geometry": shape(feature["geometry"]) if feature["geometry"] else None File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\geo.py", line 105, in shape return Polygon(ob["coordinates"][0], ob["coordinates"][1:]) File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\polygon.py", line 243, in __init__ ret = geos_polygon_from_py(shell, holes) File "F:\SDSS\1. code\django\venv\lib\site-packages\shapely\geometry\polygon.py", line 509, in geos_polygon_from_py ret = geos_linearring_from_py(shell) File "shapely\speedups\_speedups.pyx", line 408, in shapely.speedups._speedups.geos_linearring_from_py ValueError: GEOSGeom_createLinearRing_r returned a NULL pointer If I tried to run the same thing through django shell, it worked fine without any error message, >>> python manage.py shell >>> from RiskChanges.load_SHP import loadshp >>> loadshp(r'F:\SDSS\1. code\data\Country_border.shp', connstr='postgresql://postgres:admin@localhost:5432/sdss', lyrName='layer', schema='try') Please help me to find out the actual error. -
Adding an `if` statement to send an Email when the count of Likes reaches a certain No
I am trying to add an IF statement so that when the Like Count reaches 2 an email is sent. I have written the codes but it is not working, I am trying with the below but it is not working. My question is how to add an if statement so that when any item with likes more the 2 an email is sent a specific email. Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField( User, related_name='liked', blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() Here is the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def LikeView(request): # … -
Django variable creation issue
I have an custom template tag with something like this: @register.simple_tag def getLikesByUser(likedFilter, loggedInUserID): likedPeople = likedFilter personLoggedIn = loggedInUserID for personLiked in likedPeople: if personLoggedIn == personLiked.id: return True return False this will return true or false in my template, is there an option to set this return to an variable in my template? this is how a call this: {% getLikesByUser Post.likes.filter request.user.id %} I would like to have this in a variable so I can further check if is true show button if false don't. I tried this, from suggestion from my previews post: {% with likes_by_user=Post.likes.filter|getLikesByUser:request.user.id %}{% endwith %} and no luck. thanks -
Html Form does not make post request on submit
My html form won't make post request unless I comment out div with id="empty_form". This div is used to create new empty form when add more is clicked. I found that solution here. It seems like that div is marked as required field when I submit form, because when I click add more after trying to submit, new form is highlighted as red indicating required field. I am not sure why this div (id="empty_form") is required when I have not even clicked add more button. Here is my html code: <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {% for form in recipeform %} <div class="row spacer"> <div class="col-2"> <label>{{form.label}}</label> </div> <div class="col-4"> <div class="input-group"> {{ form }} </div> </div> </div> {% endfor %} {{ formset.management_form }} <div> <fieldset id="form_set"> {{ formset.management_form }} <div> <a href="#" class="remove_form">Remove</a> <fieldset> {% for form in formset.forms %} <table class='no_error'> {{ form.as_table }} </table> {% endfor %} </fieldset> </div> <div id="empty_form" style="display:none"> <div> <a href="#" class="remove_form">Remove</a> <fieldset> <table class='no_error'> {{ formset.empty_form.as_table }} </table> </fieldset> </div> </div> <input type="button" value="Add More" id="add_more"> </fieldset> </div> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script type="text/javascript"> $('#add_more').click(function() { …