Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
change some django settings variables on runtime
I read some old answers but there is no way I understand so I want to learn if a new solution found. I use django-rest-framework backend with react. Some apps like mailgun or django-storages variables configured from settings.py like secretkeys or app-ids. So on production, I want that users can enter the keys from admin panel or a form. I try django-constance and django-extra-settings but I can not re-define variables with them. I try to django.conf.settings but there is a warning about alter variables on runtime So is there anyway to re-define a variable in settings.py -
how to link foreign key with to models
I have Class called Item , and this item some time linked to Category and some time linked to SubCategory , class Category(models.Model): name = models.CharField(max_length=255) rank = models.IntegerField() def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.PROTECT,related_name='sub_category') rank = models.IntegerField() def __str__(self): return self.name class Item(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) category = models.ForeignKey(<<-- Category or subCategory -->>, on_delete=models.PROTECT,) I need to link Item with tow models , so i can use sort_by rank field -
redirecionamento para a pagina payents [closed]
Estou com o seguinte problema. Estou integrando o mercado pago SDK juntamente com Django. Quando faço o pagamento com fazer o redirecionamento para a resultpayment. Para ver o código inteiro CLIQUE AQUI.GITHUB Minha views está assim. import json import os import mercadopago from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from django.views.decorators.csrf import csrf_exempt sdk = mercadopago.SDK(settings.ACCESS_TOKEN) # Create your views here. def home(request): if request.method == 'GET': template_name = 'payments/pages/home.html' context = { 'public_key': os.environ.get('PUBLIC_KEY'), } return render(request, template_name, context) def processpayment(request): if request.method == 'POST': data_json = request.body data = json.loads(data_json) payment_data = { "transaction_amount": float(data["transaction_amount"]), "installments": 1, "payment_method_id": data["payment_method_id"], "payer": { "email": data["payer"]["email"], "identification": { "type": "CPF", "number": "191191191-00", } } } payment_response = sdk.payment().create(payment_data) payment = payment_response["response"] print("status =>", payment["status"]) print("status_detail =>", payment["status_detail"]) print("id =>", payment["id"]) return redirect(f'/pending/?payment_id={payment["id"]}') def resultpayment(request): template_name = 'payments/pages/resultpayments.html' context = { 'public_key': os.environ.get('PUBLIC_KEY'), } return render(request, template_name, context) No terminal fica assim. enter image description here E no navegador fica assim. enter image description here Tentei back_urls do mercado pago dentro da views do django e do javascripts. tentei redirect. tentei render. tentei HttoResponse. tentei windows.location do javascript. todas elas recebem o get do terminal mais … -
Issue with displaying timer which uses django modle attributes
I'm trying to use django to build a phase timer app for myself. I want a timer to run for each phase, then reset to zero and run for the next phase for n-cycles. I've tried asking 'Friend computer' for help but am still struggling. Here's the model. from django.db import models # Create your models here. class Cycle(models.Model): name = models.CharField(max_length=100) instructions = models.TextField() phase_1_time = models.PositiveIntegerField() phase_1_hold_time = models.PositiveIntegerField() phase_2_time = models.PositiveIntegerField() phase_2_hold_time = models.PositiveIntegerField() recovery_time = models.PositiveIntegerField() max_cycles = models.PositiveIntegerField() def __str__(self): return self.name And here's the view ''' View for the cycle app.''' from django.shortcuts import render from .models import Cycle def exercise_list(request): exercises = Cycle.objects.all() return render(request, 'cycles/exercise_list.html', {'exercises': exercises}) def exercise_detail(request, exercise_id): exercise = Cycle.objects.get(id=exercise_id) phase_1_duration = exercise.phase_1_time phase_1_pause_duration = exercise.phase_1_pause_time phase_2_duration = exercise.phase_2_time phase_2_pause_duration = exercise.phase_2_pause_time recovery = exercise.recovery_time max_cycles = exercise.max_cycles return render(request, 'cycles/exercise_detail.html', { 'exercise': exercise, 'phase_1_duration': phase_1_duration, 'phase_1_pause_duration': phase_1_pause_duration, 'phase_2_duration': phase_2_duration, 'phase_2_pause_duration': phase_2_pause_duration, 'recovery': recovery, 'max_cycles': max_cycles, and the html <html> <head> <title>{{exercise.name}}</title> </head> <body> <h1>{{ exercise.name }}</h1> <p>Instructions: {{ exercise.instructions }}</p> <p>Phase 1 Time: {{ exercise.Phase_1_time }}</p> <p>Phase 1 pause Time: {{ exercise.phase_1_pause_time }}</p> <p>Phase2 Time: {{ exercise.Phase_2_time }}</p> <p>Phase 2 pause Time: {{ exercise.phase_2_pause_time }}</p> <p>Long pause Time: … -
Django_Quill not showing css in Django template
Here is output of my admin panel where the input of django quill field is visible admin image but in my html file no styling is seen html image Here is my model.py from django.db import models from django_quill.fields import QuillField class Blog(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) body = QuillField() def __str__(self): return self.title def summary(self): return self.body[:100] def pub_date_pretty(self): return self.date.strftime('%b %e %Y') Here is my views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def all_blogs(request): blogs = Blog.objects.order_by('-date') return render(request, 'blog/all_blogs.html', {'blogs': blogs}) def detail(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/detail.html', {'blog': blog}) Here is my template html code {% extends 'base.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>{% block title %} Detailed Blog {% endblock %}</title> </head> <body> {% block content %} <h1 class="text-center mt-5" id="blogdetailtitle" style="font-size: 3rem">{{ blog.title }}</h1> <h5 class="text-center text-muted mt-2 mb-5">{{ blog.date|date:'F jS Y' }}</h5> <div class="container">{{ blog.body.html | safe }}</div> {% endblock %} </body> </html> I tried all the solutions given in github and here also about .html | safe This isn't issue here I think. What's wrong here... -
MultiSelectField in django dont show only text data but not numbers its showing None
when i try to show the product size data in my template as a number for example 42 i have None as a return value any ideas about this pleas this is what i get MultiSelectField -
Is there a way to hook into DRF ListAPIView to make additional queries for all instances at once?
I am using the Django REST Framework ListAPIView class to represent a collection of model instances and handle pagination automatically. It's great when you have all the data in the queryset or can grab related data with select_related/prefetch_related to add to the same queryset but when you need to gather more data for each model instance in a different way because there is no direct db relationship, you end up making queries for each instance in the serializer, resulting in a n+1 queries problem. Is there a way to hook into ListAPIView at a point where all the instances of the current page being returned are known so that more processing/queries can be done at once to fetch the additional data for all instances and add it to the response? class Gift(models.Models): ... class SearchList(ListAPIView): serializer_class = SearchGiftSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): return Gift.objects.all() -
django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.AppName' after upgrade to django 4
I have upgraded a django app which worked ok for years on django 3 to 4.1.4 and now it fails an error. I anonymized the names. In settings I have: INSTALLED_APPS = [ 'foldername' I've figured out that I needed to add Meta.app_label, can someone confirm? So in foldername/apps.py I have now this: class MyApp(AppConfig): name = 'apps.MyApp' class Meta: app_label = 'apps.MyApp' I'm not sure if the name needs to be apps.MyApp or just MyApp. I also have seen others posted to have foldername.apps.MyApp and have put the full name into INSTALLED_APP= (not just project/folder name). I wonder what's right. Well, when I run: python manage.py, I get the stack trace: ....bla bla... strack trace ends with... django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.MyApp'. Check that 'foldername.apps.MyApp.name' is correct. Can anyone spot the problem? I have spent so much time and don't know what to try. I've tried so much and rolled back again. Any feedback will make me happy at this point! :-) David Tried various combinations of: foldername.apps.MyApp (short, medium, long version) in name= in app_label, in moduleName and in INSTALLED_APPS. Tried adding in models.ypy: class BaseModel(models.Model): class Meta: abstract = True # specify this model as an Abstract Model … -
html page working independently without views.py in django
I'm developing a project in django for the 1st time. I have created a html file 'templates/app/token.html' ` <form action="{% url 'token' %}" method="post" name="portalForm" onsubmit="return validatePortalForm();"> <h3>Generate a new token</h3> <table> <tr><td><b>Select Portal Name</b></td><br></tr> <td><select name="portal"> <option value=""> Please select Portal name </option> {% for option in portalname %} <option value={{option}} >{{option}}</option> {% endfor %} </select></td> <td><input type="submit" value="Generate token"></td> </table> </form> <script type="text/javascript"> function validatePortalForm() { let portal = document.portalForm.portal.value; if (portal === null || portal === "") { alert("Select a portal from the list"); return false; } } </script> and added a function in '**views.py**'def token: context = { 'portalnames':portalList} return render(request,'PIM/token.html',context) ` Here there is an ambiguity in data. I'm passing 'portalnames' in views function and trying to access 'portalname' in html page. But it is working and even after tried removing the token function, the html page is not affected and it is able to produce portalnames option in html successfully. Note: I'm using the same 'portalname' in other view and other html page. So will this html page got affected by that or how is it able to work even after removing the views function -
How to query in one-to-many relationship in Django
Let's assume I have the following models: class Team(models.Model): name = CharField(max_length=100) class Employee(models.Model): name = CharField(max_length=100) profession = CharField(max_length=100) team = models.ForeignKey(Team) I have one team in the database and four employees with the following professions: developer, tester, tester, tester. I need to filter for teams that have at least one employee with a given profession. E. g. the expected inputs and the corresponding outputs would be: tester -> [team1] developer -> [team1] devops -> [] My attempt based on the documentation is: queryset = Team.filter(employee__profession='given_proffesion') The input and output for my code are: tester -> [] developer -> [team1] devops -> [] Interestingly, when I set the first employee to be a tester, it finds the result only if the input is 'tester', so it checks only one related entry. What am I doing wrong? -
DRF getting unneccessary data while querying
I have Category model and am querying through this model to list all categories. Im using django-silk to see how many queries got executed. It shows, category and Accounts. Accounts model has no relation with Catgeory. Below are the results. It shows accounts on the list of queries Im not requesting any data from Accounts Model. #Views.py class ListCategory(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer #Serializer.py class CategorySerializer(ModelSerializer): class Meta: model = Category fields = [ "category_name", "slug", "title", "description", "category_image", ] #Models.py class Category(models.Model): category_name = models.CharField(max_length=15, unique=True) slug = models.SlugField(max_length=100, unique=True) title = models.CharField(max_length=25) description = models.CharField(max_length=300) category_image = models.ImageField(upload_to="photos/category") class Meta: verbose_name_plural = "Category" def __str__(self): return self.category_name It's not only limited to this API, In all API it shows account. I have exactly no idea why this happens. -
'NoneType' object is not callable error when I submite a form Django
When I press the submite button of my form, an error is displayed : 'NoneType' object is not callable error. The form appears correctly, but when posting I get this error error Globally, I'm trying to have two forms in one (by using get_context_data) for an update page where I can modify bio, user names.... Template : {% extends 'main.html' %} {% load crispy_forms_tags %} {% block title %} Register {% endblock %} {% block body_content %} <h1>Update your profile</h1> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <fieldset class=form-group"> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class=form-group"> <button class="btn" type="submit">Update</button> </div> </form> {% endblock %} View : from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import FormView from django.urls import reverse from users.forms.forms import UserUpdateForm, ProfileUpdateForm from users.models.users import Profile from django.contrib import messages class UpdateUserView(LoginRequiredMixin, FormView): template_name = 'base/profile.html' model = User, Profile redirect_authenticated_user = True form_classes = {'u_form': UserUpdateForm, 'p_form': ProfileUpdateForm} def form_valid(self, form): if self.request.method == 'POST': u_form = UserUpdateForm(self.request.user, self.request.POST, self.request.FILES, instance=self.request.user) p_form = ProfileUpdateForm(self.request.user.profile, self.request.POST, self.request.FILES, instance=self.request.user.profile) if u_form is not None and p_form is not None and u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(self.request, f'Your account has been updated!') return super().form_valid(form) else: … -
Google Calendar API authentication in Python working on localhost but not working in Production
I have checked my redirect URI's, they are working perfectly in localhost but in production on button click instead of going to the authentication page it redirects to the same page without displaying any error. I tried to create a try except block to log any errors but even the log file was empty. def create_workshop(request): try: flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'static//client_secret_xxxx.json', scopes=['https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/calendar']) flow.redirect_uri = CALENDAR_REDIRECT_URI authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') return redirect(authorization_url) except Exception as e: logging.basicConfig(filename="testing.log", format='%(asctime)s %(message)s', filemode='w') logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.error(e) I have looked at all the solutions, and it displayed the same code as solution but I'm not sure why isn't it redirecting. -
Django: why is django form not submitting when trying to update a model?
I am trying to update some models in my code, there is Student model and a Marks model, the Marks have a Fkey to the Student and i am using inline formset to add more dynamic forms to the marks model, i have written the logic to create student and mark from one view, when trying to update the model, the page just refreshes and nothing happens. when i hit f5 on my keyboard to refresh the page, it shows this: and nothing gets updated in the model. def edit(request, id): student = Student.objects.get(id=id) marks = Marks.objects.filter(student=student) context = {} MarksFormset = modelformset_factory(Marks, form=MarksForm) form = StudentForm(request.POST or None, instance=student) formset = MarksFormset(request.POST or None, queryset= Marks.objects.filter(student=student), prefix='marks') if request.method == "POST": if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): student = form.save(commit=False) student.save() for mark in formset: data = mark.save(commit=False) data.student = student data.save() except IntegrityError: print("Error Encountered") return redirect('multi_forms:list') context['formset'] = formset context['form'] = form return render(request, 'multi_forms/create.html', context) -
I'm a beginner and I didn't understand about get_absolute_url [closed]
I'm very new on django I was follow the guide on the link below https://www.geeksforgeeks.org/createview-class-based-views-django/ after submit button on page "geeksmodel_form.html", I get error get_absolute_url. I know this article guideline code isn't fully completed but I already try to solve by myself but I can't. Please help me to understand this. Thank you. -
createListing() missing 1 required positional argument: 'request'
so Im still learing to code and looking for some help. Im building realestate website and im working on my CRUD functionality. When im trying to render out the basic structure of the CRUD admin page im getting an error of " createListing() missing 1 required positional argument: 'request' " Its should take in two arguments to show the web page but i dont know what arguments those are. views.py def createListing(request): form = createListing() context = {'form': form} return render(request, 'accounts/create_listing.html') forms.py from django.forms import ModelForm from listings.models import Listing class listingForm(ModelForm): class Meta: model = Listing fields = '__all__' models.py from django.db import models from datetime import datetime from realtors.models import Realtor class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title create_listing.html {% extends 'base.html' %} {% block content … -
Retrieving Stripe metadata and process it
I am sending cart data from the cookies to Stripe and retrieving it, but I am unable to find a solution to process it correctly. Please help! I am learning Django and wanted to save the cart items of non-logged users into the cookies and send it to Stripe, as Metadata. From there retrieve it and if the checkout is completed to process the order, but I am unsuccessful to process the data that is retrieved to be able to save the order. Stripe Checkout Session: @csrf_exempt def create_checkout_session(request): stripe.api_key = settings.STRIPE_SECRET_KEY domain_url = 'http://localhost:8000/checkout/' if request.user.is_authenticated: customer = request.user.customer else: data = json.loads(request.body) total = data['form']['total'].replace('.', '') email = data['form']['email'] first_name = data['form']['first_name'] last_name = data['form']['last_name'] customer, created = Customer.objects.get_or_create( email=email ) customer.first_name = first_name customer.last_name = last_name customer.save() cart_info = cart_details(request) cart_items = cart_info['cart_items'] order = cart_info['order'] items = cart_info['items'] print(items) if request.method == 'GET': checkout_session = stripe.checkout.Session.create( shipping_address_collection={ "allowed_countries": ["US", "CA", "NL", "GB"] }, client_reference_id=request.user.id, customer_email=request.user.email, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], mode='payment', line_items=[ { 'name': 'Kenpachi Katana Store', 'quantity': 1, 'currency': 'usd', 'amount': int(order.get_cart_total*100), } ] ) return JsonResponse({'sessionId': checkout_session['id']}) else: checkout_session = stripe.checkout.Session.create( shipping_address_collection={ "allowed_countries": ["US", "CA", "NL"] }, **metadata=[items]**, client_reference_id=customer.id, customer_email=email, success_url=domain_url + … -
console error output not showing the line with the error
Please I really need help, I do not know what could be going on in my program, initialy if there was an error it just simply point where an error is in my code e.g. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python_files\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\python_files\venv\lib\site-packages\channels\management\commands\runserver.py", line 75, in inner_run self.check(display_num_errors=True) File "C:\python_files\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\python_files\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\python_files\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\python_files\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\python_files\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\python_files\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module 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 … -
how to get data from choice field of form from html to views in django
i am not able to fetch or get data from html post request to form i want to give selection option to use to choose any single data and i want that data in my database my html file <div class="col-md-4"> <div class="form-group"> <label>Gender</label> <form action="{% url 'my_view' %}" method="POST"> {% csrf_token %} <select name="gender" class="selectpicker" data-title="Select Gender" data-style="btn-default btn-block" data-menu-style="dropdown-blue"> {% for x,y in form.fields.gender.choices %} <option value="{{ x }}"{% if form.fields.gender.value == x %} selected{% endif %}>{{ y }}</option> {% endfor %} </select> <button type="submit">submit</button> </form> </div> </div> my forms.py class UserForm(forms.ModelForm): def __init__(self, *args, **kargs): super(UserForm, self).__init__(*args, **kargs) class Meta: model = models.User fields = '__all__' my models.py gender = ( ('x', 'filled'), ('y', 'notfilled'), ) class User(models.Model): lat = models.DecimalField(('Latitude'), max_digits=10, decimal_places=8,null=True) lng = models.DecimalField(('Longitude'), max_digits=11, decimal_places=8,null=True) gender = models.CharField(max_length=60, blank=True, default='',choices=gender,verbose_name="gender") answer me what to write in views.py please my views.py def bins(request): form = UserForm() return render(request ,'bins.html',{'form': form}) def my_view(request): form = UserForm(request.POST or None) answer = form.cleaned_data.get('gender') if form.is_valid() else '' return redirect('/') -
ElastiCache Redis, Django celery, how to on EC2 instance AWS?
So I have set up redis with django celery on aws so that when I run the task manually eg: $ python manage.py shell from myapp.tasks import my_task it works fine. Now of course I want to run that on deploy and perhaps making sure they always run especially on deploy . But when I start the beat from ym ec2 the same way I do locally it starts but triggers are not happening . why exactly I would like to run those at deploy for example : command : /var/app/current/celery -A project worker -l info command : /var/app/current/celery -A project beat -l info -
Best way to grant access to users after they purchase something
I am building an e-learning platform using Django and as part of the platform one can buy online courses. For each course I have a manytomany field of users and every time a user purchases a course I add them to the field. Is this a good approach to give users access to the course? What would your approach be in this case? -
Distributing static package data as separate Python package?
My Python + Django application has quite a lot of CSS/JS dependencies, which change quite seldom. I was thinking about separating the two. My package with the dependencies takes 2x more space than without them (with deps 8.7 MB, without deps about 4.3 MB). Those dependencies are crucial to run the application and I would not exactly like the idea of building them on a production server, as it introduces another possible point of failure. Also, having a comfort of pip install or even pipx install is a valuable thing for an application, so I thought about making them a dependency of the "main" app package. Are there any official, sanctioned methods to build separate static data package for an app? Or, are there any other sensible ways of building such data? I was looking into building another, separate static-data package with Poetry, but it does not look like an easy task. I would also like to build that data-package from the same source tree, as Django already collects the static files for me. In my Django app I already use an approach similar to django-yarnpkg , which is I keep a list of yarn-installable packages and use a custom … -
Django queryset fuzzy search
I hope you can help me - I am not sure what to search to find the answer. I have a Django queryset returned to my HTML template. I want to have an autocomplete search based on that queryset. So if I have 'Banana', 'Apple' and 'Orange' as my query results, when someone types Or it should show Orange as an example. How would I even go about doing that? Can javascript interact with the queryset objects or is there a simple way to do it? Thanks for any advice -
django-filters form not showing(only the submit button does)
template <form method="get"> {{ filter.form.as_p }} <input type="submit" value="Press" /> </form> {% for obj in filter.qs %} {{ obj.WorkType }} - ${{ gender.price }}<br /> {% endfor %} views @login_required(login_url='login') def ListingsPage(request): review = Review.objects.all() filter = Profilefilter(request.GET, queryset=Profile.objects.all()) context = {"profile":profile,"review":review,"filter":filter} return render(request,"base/Listings.html",context) filters.py import django_filters from .models import Profile class Profilefilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = Profile fields = ['WorkType', 'gender'] It is supposed to be showing the filters but doesn't render anything, only the submit button shows up. I think it is something to do with passing the context, not sure tho -
Reverse for 'exam-detail' with arguments '(4,)' not found. 1 pattern(s) tried
When rendering a template django returns this error: NoReverseMatch at /user/admin/package/1/ Reverse for 'exam-detail' with arguments '(4,)' not found. 1 pattern(s) tried: ['user/(admin|staff)/exam/(?P<pk>[0-9]+)/$'] html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{object.name}} {{object.price}} {% for exam in object.exams.all %} <p><a href="{% url 'exam-detail' exam.pk %}">{{exam.name}}</a></p> {% endfor %} </body> </html> urls.py: re_path(r'^(admin|staff)/exam/(?P<pk>[0-9]+)/$',ExamDetail.as_view(),name='exam-detail'), When I change the path to the following the error is resolved: path('admin/exam/<int:pk>/',ExamDetail.as_view(),name="exam-detail"),