Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django) automatic record creation for checklist?
I would like the user to be able to select a checklist for a project, however I believe the connection needs to be between the project and a checklist's items, not the checklist itself. This is to allow for an additional boolean field to mark whether an item has been completed for a specific project. However I only want the user to select the checklist name - so how would I code the app to automatically create the appropriate junction_project_checks records upon selecting a checklist? project(models.Model): name = models.CharField(max_length=100) checklist = models.ManyToManyField(checklist) checklist(models.Model): name = models.CharField(max_length=100) checks = models.ManyToManyField(checks, through='junction_checklist_checks') checks(models.Model): name = models.CharField(max_length=100) body = models.TextField() junction_checklist_checks(models.Model): checklist_id = models.ForeignKey(checklist, on_delete=models.CASCADE) checks_id = models.ForeignKey(checks, on_delete=models.CASCADE) junction_project_checks(models.Model): checks_id = models.ForeignKey(checks, on_delete=models.CASCADE) project_id = models.ForeignKey(project, on_delete=models.CASCADE) checkbox = models.BooleanField(default=False) -
How to create a selection based (multiple apps) experiment task in Django?
I am working at an experiment design and want to ask about your opinion and the feasibility with Django. We want to simplify our online experiments (university) and want to create a platform for our researchers to select settings for an online task (Picture 1). These are existing apps like a chatbot. There are also different settings / treatments like the collection of badges. Based on the selection, a website with its selected content and one or more links are generated to send out to a test person (Picture 2). I have some questions about this: How can I display all apps/experiments on one homepage (Picture 1) and generate sites for the selection (Picture 2)? How can I generate unique links for the sites to send them out to probands? Is Django the right option? I now that some of these questions are more opinion-based and I appreciate every answer on that! -
I was redirecting to same login page again and again and it's not even authenticating the credentials
my login page: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Page Title</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel='stylesheet' type='text/css' media='screen' href='main.css'> <script src='main.js'></script> </head> <body> <form action="login" media="post"> {% csrf_token %} <input type="text" name="username" placeholder="username"><be> <input type="password" name="password" placeholder="password"><be> <input type="Submit"> </form> </body> </html> views.py : from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth from django.contrib.auth import authenticate # Create your views here. def homepage(request): return render(request, 'homepage.html') def login(request): if request.method== 'POST': username = request.POST.get(username) password = request.POST.get(password) user = authenticate(username='username', password='password') if user is not None: auth.login(request, user) return redirect("/") else: messages.success(request,'password not matching') return redirect('home') else: return render(request,'login.html') my urls.py: from django.urls import path from . import views urlpatterns = [ path('',views.homepage, name='homepage'), path('login',views.login, name='login'), path('registration',views.registration, name='registration'), ] every single time this login page is redirecting to same login page, whether I enter wrong credentials or the right one, I think its not even verifying the credentials that whether they are right or wrong. please help me out. -
invalid parameter error on stripe payment creation
In the class below i am trying to create a stripe payment charge but i keep getting an exception that is in the except block (the stripe.error.InvalidRequestError) and it keeps telling me invalid parameters when i try to create a payment. here is the class. class PaymentView(View): def get(self, *args, **kwargs): # equipment_order return render(self.request, "payment.html") def post(self, *args, **kwargs): equipment_order = models.EquipmentOrder.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(equipment_order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, #cents currency="usd", source=token ) # create payment payment = models.Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = equipment_order.get_total() payment.save() # assign payment to order equipment_order.ordered = True equipment_order.payment = payment equipment_order.save() messages.success(self.request, "Your order was successful!") return redirect("create:equipment_home_page") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") return redirect("create:equipment_home_page") ... except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid parameters") return redirect("create:equipment_home_page") ... -
using signals in django application code suggestion
Hello everyone I want to do charts based on my models the count of mail_items sent per countries , in my model you will see Country_origine the idea is I want to do another model that has 2 columns ' country ' and ' mail_items_count ' then I want to make a signal when new item saved to ' mail_items ' the signal will update the ' country+mail_items_count ' increase the ' mail_items_count ' by one , also I want to make a function to sum all counts in the ' mail_item_count ' column . in my views.py I want to make a view that query all countries with their ratio : ( I have to make a dictionary, I have to loop throw each object in the query , and take the country name as the key in the dictionary , and take the counter (integer) divided by the output of the sum function to calculate the ratio of each country , and append in the dictionnary ... to send the response with all coutries and ratio dictionnary) models.py class mail_items(models.Model): mail_item_fid = models.OneToOneField(Mail_item_Event,on_delete=models.CASCADE) Event_code = models.OneToOneField(Mail_item_Event,on_delete=models.CASCADE,related_name="mail_item_event_cd") office_Evt_cd = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Ev') Date_Evt = models.DateTimeField() Country_origine = models.ForeignKey(Pays, on_delete=models.CASCADE ,related_name='paysOrigine') … -
Django comment adding
''' views.py I want to add comment in my blog. It shows problem. How to get rid of ''' class PostDetail(View): def get(self, request, slug): detail = BlogSlider.objects.get(slug=slug) form = CommentForm() return render(self.request, 'blogdetails.html', {'detail': detail, 'form':form}) def post(self, request, *args, **kwargs): form = CommentForm(request.POST, request.FILES or None) if form.is_valid(): message = form.cleaned_data['message'] comment = Comment( message=message, user=self.request.user, ) comment.save() ''' models.py ''' class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(BlogSlider, on_delete=models.CASCADE) message = models.CharField(max_length=1000) def __str__(self): return self.user.username ''' forms.py ''' class CommentForm(ModelForm): class Meta: model = Comment fields = ('message',) -
AttributeError: module 'posts.views' has no attribute 'add_comment_to_post'
hello iam new to python and while adding comment option to my djang project while editing the views.py its show as following: and while typing python3 manage.py runserver **the terminal shows the following:**** File "/home/user/Documents/DJANGO-COURSE-2.xx/DJANGO_COURSE_2.xx/21-Social_Clone_Project/simplesocial/posts/urls.py", line 12 , in path('post//comment/', views.add_comment_to_post, name='add_comment_to_post'), AttributeError: module 'posts.views' has no attribute 'add_comment_to_post' and the views.py and urls.py file is given below: image description is of view.py file image description of urls hope that i will get convenient answer ASAP -
Django url can't find attribute of related view function
I have the following view that returns a user sign up form with an e-mail validation logic. views.py from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render, redirect from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from users.forms import SignUpForm from .tokens import account_activation_token def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SignUpForm() return render(request, 'users/signup.html', {'form': form}) and according url mapping that shall redirect the user upon submitting the registration to the mail activation information page. urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('register/', views.signup, name='signup'), url(r'^account_activation_sent/$', views.account_activation_sent, name='account_activation_sent'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ] now the url module throws this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Jonas\Desktop\CFD\CFD\CFD\urls.py", … -
Original exception text was: 'QuerySet' object has no attribute 'client'
I Got AttributeError when attempting to get a value for field client on serializer ClientSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance models.py class Box(models.Model): box = models.IntegerField() controller = models.ForeignKey(Controller, related_name='boxes', on_delete=models.CASCADE) def __str__(self): return str(self.box) class Client(models.Model): client = models.CharField(max_length=30) cpf = models.IntegerField() box = models.OneToOneField( Box, on_delete=models.CASCADE, primary_key=True ) def __str__(self): return self.client serializers.py class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = [ "id", "client", "cpf", "box", ] class BoxSerializer(serializers.ModelSerializer): class Meta: model = Box fields = [ "id", "box", "controller" ] views.py class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() def list(self, request, store_pk=None, locker_pk=None, controller_pk=None, box_pk=None): queryset = Client.objects.filter(box=box_pk, box__controller=controller_pk, box__controller__locker=locker_pk, box__controller__locker__store=store_pk) serializer = ClientSerializer(queryset, context={'request': request}) return Response(serializer.data) def retrieve(self, request, store_pk=None, locker_pk=None, controller_pk=None, box_pk=None): queryset = Client.objects.filter(box=box_pk, box__controller=controller_pk, box__controller__locker=locker_pk, box__controller__locker__store=store_pk) client = get_object_or_404(queryset) serializer = ClientSerializer(client, context={'request': request}) return Response(serializer.data) I'm trying to get the object client on lockers/1/controllers/1/boxes/1/client/ which is OneToOneField relations with boxes and It's in a nested router I already tried use decorator @action but yet didn't work Anyone know why it's not finding the correct object attribute -
Enable Django support in IntelliJ?
I saw this question, but it doesn't help. I just made a new project in IntelliJ, (Community 2020.1 EAP). This is a Linux OS (Mint 18.3). In the left-hand panel I chose "Python". When I have created it I go File --> Project structure. I click "Facets" in the left-hand panel. In the middle panel it says "No facets are configured" and under that "Detection". I click the "+" sign and then where it says "Buildout Support facet will be added to the selected module" I click OK. After that, in the middle panel, Buildout Support is highlighted, and in the right-hand part it says "Use paths from script:" (with a blank text field) and under the field "Set to <buildout-dir>/bin/django.py for proper Django support". This leaves me very puzzled. It suggests that there is a setting "buildout-dir", and even supposing I can find a file "django.py" in a directory "bin" I haven't got a clue what I'm meant to enter in that box: the full path to "django.py"? The full path above "bin"? Then I go looking on my machine for django.py: 369] mike@M17A ~/IdeaProjects/TempDjango $ locate django.py /home/mike/.local/share/JetBrains/IdeaIC2020.1/python-ce/helpers/pycharm/teamcity/django.py /home/mike/python_venvs/test_venv369/lib/python3.6/site-packages/django/template/backends/django.py Neither looks at all promising. Naturally I have tried … -
API endpoint for recent/new events in Django Rest Framework
I am trying to make an API endpoint for a mobile app in Django Rest Framework. The challenge I am facing is how to structure and Endpoint that will return the new events. So basically what I want to do is to make requests from the app every 5 seconds to fetch any new events. The events would be e.g a model is created, a model is updated, a model is delete and so on. -
Reduce database hits for Django podcast app
I'm building a podcast directory where episodes can be categorized. The code to generate a page for the podcast, a list of episodes, and a list of categories within each episode. A podcast can have a "Sports" and "News" category. And one episode might have "Sports", while another might have "Sports" and "News" as categories. The problem: I'm battering the database with looping within loops. I know there's a way more efficient way. Here's generally how the models are connected: class Podcast(models.Model): ... class Category(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) ... class Episode(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) categories = models.ManyToManyField(Category, blank=True) ... Then, when I load the podcast page and want to put a list of categories and episodes within it: class Podcast(models.Model): ... @property def get_categories(self): return self.category_set.all() @property def episodes_by_category(self): episodes_by_category = [] for category in self.get_categories: episodes = self.episode_set.all().filter(categories=category) episodes_by_category.append({ 'category': category, 'episodes': episodes, 'count': len(episodes), }) sorted_episodes_by_category = sorted(episodes_by_category, key = lambda i: i['count'],reverse=True) return sorted_episodes_by_category Then, when I load an episode page, I show other episodes that share the same categories: class Episode(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) categories = models.ManyToManyField(Category, blank=True) ... @property def get_categories(self): return self.categories.all().prefetch_related('episode_set').select_related('podcast') @property def related_episodes_by_category(self): episodes_by_category = [] for category in … -
Django third-party backends Access to API
This is my first project with python, and I am building an app with Django Rest Framework. I have made a lot of things in this project, but now I am stuck. I want to generate keys so third-party backends can have access to part of my API and I don’t know how to. For example: someone buys my product (done) and can generate x keys to give access to that API (then I will use DRF throttling to limit the requests). Do I generate keys like tokens and then they have to put it in the header to access? Or is it with Django REST Framework API Key ( https://florimondmanca.github.io/djangorestframework-api-key/ )? Any suggestions? Thanks, Pablo -
Get position of regex matches in database objects using Django
I have a Django app with a Postgres database that takes in user input, makes a regex based on this input, and returns the database entries that match this regex and the start and end positions of this match. The current implementation is something along the lines of: models.py: class SampleInputModel(models.Model): target_field = models.CharField() class SampleInputModelForm(ModelForm): class Meta: model = SampleInputModel fields = '__all__' class RecordObject(models.Model): record_name = models.TextField() record_string = models.TextField() views.py: find_regex_match(form_dict, one_record, terminating_word='keyword'): import re search_pattern = f'({form_dict['target_field']}).*(terminating_word)' for match in re.finditer(search_pattern, one_record.record_string): return '{}\t{}\t{}\t{}\n'.format( one_record.record_name, match.start(), match.end(), one_record.record_string[match.start():match.end()] ) def home(request): if request.method == 'POST': form = SampleInputModelForm(request.POST) if form.is_valid(): form = form.save(commit=False) form = model_to_dict(form) results = '' for one_record in RecordObject.objects.all(): results += find_regex_match(form_dict, one_record) return render(request, 'results.html', {'results': results}) else: form = SampleInputModelForm() return render(request, 'home.html', {'form': form}) This works and takes ~1.2 seconds on average to complete. However, I feel like there's a better way to handle the results instead of just passing a huge raw string to the template to render. I wanted to switch over to using some of the Django API for database filtering so that I can pass query sets to the templates. The new version of the … -
How to Stream mp4 from private bucket using django as a proxy?
I try to return a response to stream a video from a private bucket. To do that my django server will get the video from S3 and return a response. def get_video_from_fragment(self, request, custom_id=None): s3 = AmazonApi() streaming_body = s3.get_file_to_stream(fragment.video.file) if streaming_body is None: return Response({'details': "error retreiving the video"}, status=500) response = StreamingHttpResponse(streaming_content=streaming_body) response['Content-Disposition'] = f'attachment; filename="{fragment.video.filename}"' return response It work well for Chrome and Firefox but not for Safari. I read for Safari that the content need to be delivered with a 206 status code. The things is that my Nginx already deliver well the statics files (mp4 in this case) but not this kind of response. I tried to add response = StreamingHttpResponse(streaming_content=streaming_body, status=206) but in fact, it doesn't change anything. I test with a curl like they do on their documentation (from apple) I suppose that my nginx (or django) know how to manage my .mp4 files but don't know how to do with call that return a StreamingHttpResponse. Also I check how others website deliver their content and I see on my Safari console network tab a difference on the status. For example google website has a status code on Response Headers but mine are … -
Tell me correctly to display a detailed description
I don’t know how I used to live without this forum :) Tell me please, where did I go wrong? I created a behavior model in the views, created a URL, but when I click on the title, it does not go to a detailed description of the event. Could there be an error in what I inherit in DetailViews? I am attaching the code below Views: from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView from django.views.generic.base import View from .models import Blog, Event # Create your views here. class EventView(View): def get(self, request): events = Event.objects.all() posts = Blog.objects.all() return render(request, "home/home.html", {"events": events, "posts":posts}) class BlogDetailView (View): def get(self, request, slug): posts = Blog.objects.get(url=slug) return render(request, "home/blog-detail.html", {"posts": posts}) class EventViewDetail(DetailView): model = Event template_name = "event/event-detail.html" slug_field = "name" Urls: from django.urls import path from . import views urlpatterns = [ path("", views.EventView.as_view()), path("<slug:slug>/", views.BlogDetailView.as_view(), name="home_detail"), path("event/<str:slug>/", views.EventViewDetail.as_view(), name="event_detail") ] HTML: <!-- Latest-Events-Sermons --> <section class="section-padding latest_event_sermons m-0"> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-5"> <div class="heading"> <h3>Анонс событий</h3> <a href="#" class="btn btn-secondary btn-md pull-right">Показать все</a> </div> <div class="event_list"> <ul> {% if events %} {% for e in events %} <li> <div class="event_info"> <div class="event_date"> <span>{{ … -
Is it possible to write a site in html, and from django make databases?
If there is such an opportunity, then you can drop the link please, and if not, then explain how you can do this in python -
Django 3.x - which ASGI server (Uvicorn vs. Daphne)
I have a simple API-based web application written in Django, and I decided to upgrade Django from 2.x to 3.x. In Django docs there's a documentation page about ASGI servers, and two options are mentioned: Daphne and Uvicorn. Unfortunately they do not provide any benefits regarding a particular choice, so I'm confused when it comes to select one of them. I would like to hear opinions of people who have experience with both libraries, and I would like to ask mainly for opinion on performance and stability. And, basically, is it a big difference to use Uvicorn instead of Daphne? My server is running on Ubuntu, so Daphne seems to be the right choice, as it's designed to be used on UNIX system. -
django.core.exceptions.FieldError: Unknown field(s) (groups) specified for Account
Hi I was making a wagtail app but I have a problem overriding the user model with the abstract user and the BaseUserManager, trying to make migrations but it crashes and show this error on console: django.core.exceptions.FieldError: Unknown field(s) (groups) specified for Account It uses a package from django_countries And a choice to the account type Models.py from django.db import models from django_countries.fields import CountryField from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user( self, email, username, country, password=None ): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') if not country: raise ValueError('Users must have country') user = self.model( email=self.normalize_email(email), username=username, country=country ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, country, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, country=country, account_type='MTR' ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): class AccountTypes(models.TextChoices): MASTER = 'MTR', _('Master') ADMINISTRATOR = 'ADM', _('Administrator') MODERATOR = 'MOD', _('Moderator') USER = 'USR', _('User') email = models.EmailField( verbose_name="email", max_length=60, unique=True, null=False, blank=False) username = models.CharField( max_length=30, unique=True, null=False, blank=False) photo = models.ImageField( verbose_name='photo', upload_to='profile_photos', null=True, blank=True) country = CountryField() account_type = models.CharField(max_length = … -
Django - sqlite - Delete attribute from model
I am a beginner in Django and up to now I was amazed how simple it was. I am running django 3 with an sqlite3 DB. I want to remove an attribute of one of my models. In this particular case it's "slug". models.py class Recipe(models.Model): title = models.CharField(max_length=100) creator = models.CharField(max_length=42) content = models.TextField(null=True) creation_date = models.DateTimeField(default=timezone.now, verbose_name="Creation date") photo = models.ImageField(upload_to="photos/") main_ingredient = models.ManyToManyField('Ingredient', related_name='recipes') slug = models.SlugField(max_length=100) class Meta: verbose_name = "recipe" ordering = ['creation_date'] def __str__(self): return self.title I just delete the line and ran python manage.py makemigration I got the following error SystemCheckError: System check identified some issues: ERRORS: <class 'recipes.admin.RecipeAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'recipes.Recipe'. I suppose django does not want to delete the line from the DB. I have to do it manually then I tried this But it does not work for sqlite as explained here So far I was amazed by Django and this is a major drawback. Is there an easier way? what am I doing wrong? Thank you for your help -
Django Postgres search with SearchVectorField and TrigramSimilarity
I'd like to do efficient partial word matches with a large data set. I'm able to use SearchVectorField for speed and as a way to collect data from a few different fields. search_vector = SearchVectorField(editable=False) Thing.objects.update(search_vector=various_fields_vector) Thing.objects.filter(search_vector="something") Works quickly. However it doesn't perform partial word matches. Thing.objects.filter(search_vector="omething") Yields no results. I want to do something like Thing.objects.annotate(rank=TrigramSimilarity("search_vector", "omething")) However I get: No function matches the given name and argument types. You might need to add explicit type casts. Is there a way to index in some manner to perform these searches faster? -
Does Heroku WEB_CONCURRENCY need to account for ALL processes spawned by both Django AND task queue (such as; Huey, Celery) on the same dyno?
I am trying to deploy Django and Huey async task queue to the same dyno. I understand that people usually deploy a task queue to a separate dyno/container for independent scaling and what not. That reason for me doing this is because Huey is a light weight task queue and as such if there is a need for some async works or occasional scheduling, it could handle it (no need for heavy-weight like Celery in a separate dyno). Here is what sample Huey configuration in Django settings.py look like. I have used "process" as worker type and there are 3 of them (plus 1 mandatory consumer process) for a total of 4 for Huey. My question, do I have to account for that number in addition to Django process when setting WEB_CONCURRENCY? Or does the WEB_CONCURRENCY only apply to Django web request handler. I am not entirely how Gunicorn handle Django. -
(Django) How to reference through multiple layers of relationships? (potentially complex)
The following is a for a creative writing app. All aspects (characters, scenes, projects etc.) are recorded in the same model to allow for a simple sidebar directory. Each have extension models to add specific fields, so when an element is selected in the sidebar, the extension model is loaded as a form on the right. Extension model additional fields and universe model excluded for clarity. The problem is, I'm really stuck with restricting choices on a specific ManytoMany field. MODELS.PY user_information <only 1 record> current_universe <will be changed through a signal depending on the universe loaded> elements_type name <e.g. ID 1 = character, ID 2 = project, ID 3 = scene, ID 4 = draft> elements name = models.CharField(max_length=100) elements_type = models.ForeignKey(elements_type, on_delete=models.CASCADE) universe = models.PositiveSmallIntegerField() <default value will be set automatically to match current_universe> parent_ID models.ForeignKey('self', on_delete=models.CASCADE) <if the element is a scene, this will identify its draft; likewise with a draft and its project> extension_projects name elements_id = models.ForeignKey(elements, on_delete=models.CASCADE) characters = models.ManyToManyField(elements, limit_choices_to={'elements_type': 1, 'universe': ? User_information’s current_universe – record 1}) <don't know how to do this at the moment but that's not part of the question> extension_drafts name elements_id extension_scenes name elements_id characters = models.ManyToManyField(elements, … -
Template tag variables at django are not displayed
I’m building a blog and I’m new to django. I’m trying to build a post display page but tag variables are not working. urls.py urlpatterns = [ . . . path('post/<slug>/', views.post_detail, name='post_detail'), ] views.py . . . def post_detail(request, slug): all_posts= Post.objects.all() this_post = Post.objects.filter(post_slug=slug) return render(request = request, template_name = 'blog/post_detail.html', context = {'this_post':this_post, 'all_posts':all_posts}) . . . post_detail.html {% extends 'blog/header.html' %} {% block content %} <div class="row"> <div class="s12"> <div class="card grey lighten-5 hoverable"> <div class="card-content teal-text"> <span class="card-title">{{ this_post.post_title }}</span> <p style="font-size:70%">Published {{ this_post.post_published }}</p> <p>{{ this_post.post_content }}</p> </div> </div> </div> {% endblock %} Thanks from now! -
run a javascript function inside a python
I'm working on a project. I have a strings.py which has dicts like below: def bar(self): #do something STRINGS_ENGLISH = { 'title': 'foo' 'function': bar } then I wanna use this string in my Django template, I'll pass it through my context in the template named string. I know that If I wanna print the title in the HTML it's enough to write {{strings.title}}, but about the function I want to pass it to a button like that: <button onclick="{function()}">Do Something</button> but it's a python function! not a js function. so what should I do?