Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
installed django-redis in python virtualenv, redis-cli command not found
I just install redis-cli using pip in python virtualenv,but when I type redis-cli, shows me redis-cli command not found. I'm pretty much sure redis-cli has been installed sucessfully. need your help thx in advance -
django redirects not working in electronjs
I am creating an account management app for my father's company. I integrated Django with electron like this=> mainWindow.loadURL('http://localhost:8000') And in package.json. I did this in scripts => "start": "start python manage.py runserver && start electron ." In my createView, DetailView, DeleteView. I added this => success_url = reverse_lazy('home') If i open this in chrome browser it works absolutely fine no worries. But if i do this in electron. It show this msg => Page not found (404) Request Method: GET Request URL: http://localhost:8000/delete/11 Raised by: accounts.views.EntryDeleteView plz help! -
ModuleNotFoundError psycopg2 when deploying in heroku even though psycopg2 is installed
I migrated my website from sqlite3 to postgresql. I'm deploying my website in heroku but this error came up when I'm executing command push heroku master -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.3 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.7.2 -----> Installing pip -----> Installing dependencies with Pipenv 2018.5.18… Installing dependencies from Pipfile… -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
in Django where we call function or class
def display(request): return render(request, 'base.html') I have curiosity about where we call this is working why not need to call the function -
Angular 8: not able to get message from Rest Api
Following those links https://grokonez.com/python/django-angular-6-example-django-rest-framework-mysql-crud-example-part-2-django-server and https://grokonez.com/frontend/django-angular-6-example-django-rest-framework-angular-crud-mysql-example-part-3-angular-client I created a django rest API and angular app that calls this rest. Considering that I'm new in such kind of development I created as a first step an App that just displays customers list. Django rest API is fine working. I tested it with the browser: But my problem is with the angular app, seems that it's not able to get message with the same URL: http://localhost:8000/customers Below is my angular code: app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule, routingComponents } from './app-routing.module'; import { AppComponent } from './app.component'; import { CustomersListComponent } from './customers-list/customers-list.component'; @NgModule({ declarations: [ AppComponent, routingComponents, CustomersListComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CustomersListComponent } from './customers-list/customers-list.component'; const routes: Routes = [ { path: 'customers', component: CustomersListComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } customer.ts export class Customer { id: number; name: string; age: number; active: boolean; } customer.service.ts import { … -
chat socket is closing unexpectedly (django-channels)?
i have gone through as it mentioned in the docs(channels) it worked fine until i pasted the code of channel_layers in settings.py i installed all the specifications mentioned in channel_layers ASGI_APPLICATION = 'mysite.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } why is my chat_server closing unexpectedly -
Submit a form after two clicks on submit Django
I'm doing a quiz site, and I have several questions. I currently access a certain category and is shown one question after another after clicking submit. But I would like to click once, show the response on the same screen, and after clicking it again go to the next question. How would I do that? This is my views.py file: class Perguntas(FormView): form_class = QuestaoForm template_name = 'certificacoes/pergunta.html' template_name_result = 'certificacoes/finalizado.html' def dispatch(self, request, *args, **kwargs): self.dominio = get_object_or_404(Dominio, slug=self.kwargs['slug_dominio']) try: self.user_logado = self.request.user.is_authenticated() except TypeError: self.user_logado = self.request.user.is_authenticated if self.user_logado: self.sessao = Sessao.objects.usuario_sessao(request.user, self.dominio) return super(Perguntas, self).dispatch(request, *args, **kwargs) def get_form(self, *args, **kwargs): if self.user_logado: self.questao = self.sessao.pegar_primeira_questao() form_class = self.form_class return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): kwargs = super(Perguntas, self).get_form_kwargs() return dict(kwargs, questao=self.questao) def form_valid(self, form): if self.user_logado: self.form_valid_usuario(form) if self.sessao.pegar_primeira_questao() is False: return self.resultado_final_usuario() self.request.POST = {} return super(Perguntas, self).get(self, self.request) def form_valid_usuario(self, form): progresso = Progresso.objects.get_or_create(usuario=self.request.user) hipotese = form.cleaned_data['respostas'] is_correta = self.questao.checar_correta(hipotese) if is_correta is True: self.sessao.adicionar_ponto(1) else: self.sessao.add_incorreta(self.questao) # Tenho que mexer aqui para gerar uma nova questão self.anterior = { 'resposta_escolhida': self.questao.alternativa_escolhida(hipotese), 'resposta_correta': is_correta, 'questao_resposta': self.questao.enunciado, 'respostas': self.questao.pegar_alternativas(), 'alternativa_correta': self.questao.alternativa_correta(), 'fundamento': self.questao.alternativa_fundamento(hipotese) } self.sessao.add_usuario_resposta(self.questao, hipotese) self.sessao.remover_primeira_questao() def get_context_data(self, **kwargs): context = super(Perguntas, self).get_context_data(**kwargs) context['questao'] = self.questao … -
Django: Get dropdown value and select dynamic form fields for Class Based views
I would like to ask how I can retrieve a drop-down GET value to be used as a Form select logic within a Class Based FormView. By calling the Context as a function works fine (see fully functional code below) but I cannot retrieve the GET value to be used within a logic for a Class Based View. E.g. now I call it as a function: path('cooking/', cooking, name="cooking") But would like to call it as a Class Based FormView instead, such as: path('cooking/', CookingView.as_view(), name="cooking") I am struggling to translate the GET select logic (see code below) into my new CookingView(FormView): class CookingView(FormView): form_class = CookingForm template_name = 'form/cooking.html' def get_context_data(self, **kwargs): """ # some logic to get a desired form, such as ingredients_form = [] if recipe_choice == '1': ingredients_form = HamburgerForm(request.POST) elif recipe_choice == '2': ingredients_form = PancakeForm(request.POST) """ context = super(CookingView, self).get_context_data(**kwargs) context['ingridients_form'] = ingredients_form return context **Below I provide complete code that works. views.py def cooking(request): context = {} recipe_choice = request.GET.get('recipe_select', False) ingredients_form = [] if recipe_choice == '1': ingredients_form = HamburgerForm(request.POST) elif recipe_choice == '2': ingredients_form = PancakeForm(request.POST) context['cookbook_form'] = CookingForm(request.GET or None) context['ingridients_form'] = ingredients_form return render(request, 'form/cooking.html', context) models.py class Ingridients(models.Model): … -
Django, CBVs and pk_url_kwarg is missing
I am learning django. I have the latest django and Python 3.7.x. I have a question about self.pk_url_kwarg and how it is created and when. I have seen the doc at: https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-single-object/ but am not finding the answer I hope for. Specifically, I have an entry in a url.py file like: ... path( 'Student/createFromProfile/<uuid:profile_id>', student.CreateFromProfile.as_view(), name="student_create_from_profile" ), ... I have a CBV for this that starts: @method_decorator(verified_email_required, name='dispatch') class CreateFromProfile(CreateView): model = Profile success_url = '/Members' def get(self, request, *args, **kwargs): try: account_holder = Profile.objects.get( id=self.kwargs["profile_id"] ) except ObjectDoesNotExist: messages.error( request, "Unknown Profile ID." ) return HttpResponseRedirect(self.success_url) Notice in the get method the try and the section id=self.kwargs["profile_id"]. I was trying to use id=self.kwargs[self.pk_url_kwarg] but I get a django debug page that says that it has no idea what pk_url_kwarg is. I can stop in the PyCharm debugger and inspect self and indeed, it has no entry for pk_url_kwarg. This is extra special strange because I am using this in other views. What am I missing? -
Django Signal.disconnect raises 'function' object has no attribute 'lock' error
I have a function that is the receiver of signals from all models of the system. I want the signals to be interrupted when I am making an database dump population through a Django command, so it wouldn't be invoked when model instances are created by this mean. This is my receiver function: @receiver(post_save) def trigger_payment(sender, instance=None, created=False, **kwargs): from TreasuryManagementApp.models import PaymentApplicationTrigger if instance.__class__.__name__ not in trigger_models: return strategies = EventStrategies() application_triggers = PaymentApplicationTrigger.objects.filter(event_name__in=trigger_models[instance.__class__.__name__]['event_names']) for application_trigger in application_triggers: strategies.execute(application_trigger, instance) And this is the code of my command where I attempt to disconnect the function from signals: class Command(BaseCommand): help = _("""Run this command to import partners and operators from plane files""") def execute(self, *args, **kwargs): from TreasuryManagementApp.controllers import trigger_payment Signal.disconnect(trigger_payment) self.import_partners() self.import_operators() self.import_dead_ones() The problem is that this call to Signals.disconnect() raises the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/taxistas/GeneralApp/management/commands/startdatabase.py", lin e 21, in execute call_command('import_people') File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/taxistas/GeneralApp/management/commands/import_people.py", lin e 433, in execute Signal.disconnect(trigger_payment) … -
How to prevent Django form being reset after clicking page buttons
I have a Django form that takes input values from users. The values are then used in making query to a table, which finally returns a list of filtered results. Since the results might be a long list, I added a pagination function with "Prev" and "Next" buttons. My problem is that when I click "Prev" or "Next" button, the form gets restored into default values. How do I prevent this from happening? I think the form gets reset because of "form1 = QueryForm()" when a request is not "POST". However I just have difficulty coming up with a neat solution. In views.py: def search(request): if request.method == "POST": form1 = QueryForm(data=request.POST) layer_dict = [] if form1.is_valid(): inp_ct = form1.cleaned_data['country'] q1 = ResourceBase.objects.filter(country_name__iexact=inp_ct) for layer in q5: down_url = 'xxxxxxx'.format(layer.title) view_url = 'xxxxxxx'.format(layer.title) layer_dict.append((layer.title, down_url, view_url)) layer_dict = sorted(layer_dict, key = lambda x:x[0]) paginator = Paginator(layer_dict, 10) page = request.GET.get('page', 1) try: layers = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. layers = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. layers = paginator.page(paginator.num_pages) context = {'form1': form1, 'layers': layers} else: form1 = QueryForm() context … -
in django SignupForm signup method is not being overrided
I have this working SignupForm in Django==1.10.6. The form is working because when I change a label it gets reflected in the form, but the signup method is never executed. I've been struggling with this for a while now, what am I missing here? The output is never printed, the user is not saved properly and the ipdb module does not start. # -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field, Fieldset, ButtonHolder, Submit, HTML, Div from crispy_forms.bootstrap import TabHolder, Tab, Accordion, AccordionGroup from alistate.core.utils import LowerField from allauth.account.forms import SignupForm as SignupFormBase from django.contrib.auth import get_user_model class SignupForm(SignupFormBase): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div(Field('username'), css_class='col-md-12'), Div(Field('email'), css_class='col-md-12'), Div(Field('password1'), css_class='col-md-12'), Div(Field('password2'), css_class='col-md-12'), css_class='row'), Div( Div(Field('nombre1'), css_class='col-md-6'), Div(Field('apellido1'), css_class='col-md-6'), css_class='row'), Div( Div(Field('nombre2'), css_class='col-md-6'), Div(Field('apellido2'), css_class='col-md-6'), css_class='row'), Div( Div(Field('telefono'), css_class='col-md-12'), css_class='row'), Div( Div(Field('fecha_religiosa', css_class="datetimepicker-signup"), css_class='col-md-12'), css_class='row'), Div( Div(Field('como_conocio'), css_class='col-md-12 register-know'), css_class='row'), ) nombre1 = LowerField(label="Nombreeee 1 (novia/o).", required=True, max_length=50) apellido1 = LowerField(label="Apellido 1 (novia/o).", required=True, max_length=50) nombre2 = LowerField(label="Nombre 2 (novia/o).", required=True, max_length=50) apellido2 = LowerField(label="Apellido 2 (novia/o).", required=True, max_length=50) fecha_religiosa = forms.DateTimeField(required=True) telefono = LowerField(label=u"Teléfono", required=True, max_length=50) como_conocio = forms.CharField(label=u"¿Cómo … -
Javascript button not responding when clicked
I am attempting to use listjs in a django project i am making. But even when running a snippet taken from the documentation, django refused to run it properly. Take this pen for example. I copy this and put it in my html template. The template now has the following <script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script> <script type="text/javascript"> var options = { valueNames: [ 'name', 'born' ] }; var userList = new List('users', options); </script> <div id="users"> <input class="search" placeholder="Search" /> <button class="sort" data-sort="name"> Sort by name </button> <ul class="list"> <li> <h3 class="name">Jonny Stromberg</h3> <p class="born">1986</p> </li> <li> <h3 class="name">Jonas Arnklint</h3> <p class="born">1985</p> </li> <li> <h3 class="name">Martina Elm</h3> <p class="born">1986</p> </li> <li> <h3 class="name">Gustaf Lindqvist</h3> <p class="born">1983</p> </li> </ul> </div> Result is the page loads fine with no errors in the console but the button or the search do not work at all. I think it is something obvious i am missing here but cant seem to track it. -
pytest with database details from command line and fixtures
I am trying to initialize the db for pytest through values passed from command line. I cannot specify the values in a different test setting.py, nor can I specify it in TEST option in settings.py; it is only available through command line. I have setup extra command line options in confttest.py, to get the db details: def pytest_addoption(parser): parser.addoption( "--dbconnection", action="store", default = "novalue", help="test db value" ) Is there any way I can access these values in conftest.py? AFAIK, I can use fixtures to get the value in the test, but I would like to override django_db_modify_db_settings to change the database, with these command line arguments. Is this possible? Is the database initialized before the command line is processed? I tried some experiments and it does look so. Is there any other workaround to getting this working? -
How to protect SELECT * FROM var1 WHERE var2 statements from SQLInjection
I am making a website in django where I want the user to put in a table id and group id and then return the table and group that the put in. However, I have only found statements that are prone to SQL injection. Does anybody know how to fix this? mycursor = mydb.cursor() qry = "SELECT * from %s WHERE group_id = %i;" % (assembly_name, group_id) mycursor.execute(qry) return mycursor.fetchall() Or do something that achieves the same thing? -
Django-recurrence with Vuejs
I am using a django backend with a vuejs frontend and I am trying to get the django-recurrence form to work inside a vue template with no luck. I am trying to generate recurrences to send to the backend. Is there a way to make this work or would I need to create my own form just for generating the recurrence field? -
Factory Boy with Django ManyToMany models
I have 3 models on the same module, app.models.py, as following. Some other models may appear in code but it isn't relevant. Optionals class Optional(models.Model): name = models.CharField(_('Nome'), max_length=255) type = models.CharField(_('Tipo'), max_length=50, null=True, blank=True) description = models.TextField(_('Descrição'), null=True, blank=True) provider = models.ForeignKey('providers.Provider', null=True, blank=True) charge = models.ForeignKey('Charge', null=True, blank=True) def __str__(self): return self.name Coverage class Coverage(models.Model): code = models.CharField(_('Código'), max_length=20, null=True, blank=True) vehicle_code = models.CharField(_('Código do veículo (ACRISS)'), max_length=4, null=True, blank=True) charge = models.ForeignKey('Charge', null=True, blank=True) Vehicle class Vehicle(models.Model): code = models.CharField(_('Código'), max_length=100) description = models.CharField(_('Descrição'), max_length=255, null=True, blank=True) model = models.CharField(_('Modelo'), max_length=100, null=True, blank=True) brand = models.CharField(_('Fabricante'), max_length=100, null=True, blank=True) group = models.ForeignKey('Group', null=True, blank=True) optionals = models.ManyToManyField('Optional', related_name='vehicle_optional') coverages = models.ManyToManyField('Coverage', related_name='vehicle_coverage') def __str__(self): return self.code I'm trying create fixtures from this models using factory_boy. class CoverageFactory(factory.Factory): class Meta: model = Coverage charge = factory.SubFactory(ChargeFactory) class OptionalFactory(factory.Factory): class Meta: model = Optional provider = factory.SubFactory(ProviderFactory) charge = factory.SubFactory(ChargeFactory) class VehicleFactory(factory.Factory): class Meta: model = Vehicle group = factory.SubFactory(GroupFactory) optionals = factory.SubFactory(OptionalFactory) coverages = factory.SubFactory(CoverageFactory) On my tests it is instantiated this way: optional = OptionalFactory( name="GPS", type="13", description="", charge=charge, provider=provider ) coverage = CoverageFactory( code="ALI", vehicle_code="ABCD", charge=charge ) vehicle = VehicleFactory( code="ECMM", description="GRUPO AX - MOVIDA ON", … -
Django: NoReverseMatch not a valid function
Running my local Django dev server (2.2) in a virtual environment, I encounter a trace back. The essential keywords that are part of this error include “django.urls.exceptions.NoReverseMatch” and “not a valid view function or pattern name.” I’m doing a code-along kinda Udemy course by Nick Walter. Part of the course material involves writing a rudimentary blog using Django. I’m close to the end of Nick’s blog module. I figure I have referred to a function inaccurately somewhere or perhaps I have misconfigured my urlpattern. There are a few other SO members who have encountered similar errors with the resolution typically involving correcting a typo. I've tried removing the pluralization of my post_details views function. I’ve tried variations in my urls.py with different combinations of regular expressions (and without). I feel like I am overlooking something trivial here. It’s gotten to the point where I am comparing my code to the course instructor’s end-of-module source code and I can’t for the life of me figure out what I am doing wrong. Here is my code: urls.py: from django.urls import path, re_path # from . import views from posts.views import * from redactors.views import * from counters.views import * from django.conf.urls.static import … -
How to automatically update the exchange rate in django-currencies?
I use django-currencies to translate the price at the exchange rate on the templates. In order to update the exchange rate you need to enter the command: python manage.py updatecurrencies I set up celery to update the exchange rate once a day, but I don’t understand how exactly I should call this command? Perhaps there are other ideas how to update currency? -
Django App Not Communicating with JavaScript Code Block
I have a Django application that accepts an Elasticsearch query in a form and produces a downloadable report. An earlier iteration worked great, but we decided to add a component that checks every ten seconds if the report is done being created ([thank you to goudarziha][1]). Our ultimate goal is to have it check repeatedly for the completed report (and tell the user the report is still processing if not complete), and then either add a button to download the report or just have it automatically begin downloading. However, my application doesn't seem to be calling on the javascript block I have in my form.html. When I run this, it says {"file_created": False} until I manually refresh myself, then it switches to True. I tried the code commented out in check_progress (which is basically what my code in form.html does...) but it returned an error. How do I make them communicate? What am I missing? views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse, HttpResponseRedirect import os import threading from .forms import QueryForm from .models import * @login_required def get_query(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): query = form.cleaned_data["query"] t = threading.Thread(target=generate_doc, … -
Rawsql query array into formatted html table
I have done a rawsql query on a table in my database and gotten an array looking like this : [(19778, 4519, 'sp|P48740|MASP1_HUMAN', 5, 50, 'R'), (19779, 14872, 'sp|P48740|MASP1_HUMAN', 5, 54, 'R'), (19780, 1018, 'sp|P48740|MASP1_HUMAN', 5, 45, 'R'), (19781, 13685, 'sp|P48740|MASP1_HUMAN', 5, 51, 'R')] I want to format this into a html table which the 6 section within each set of parentheses each a column. Of course there will be an unknown amount of items in the array so explicitly calling each will not work. What is the best and most efficient way to do this? -
django how to add multi values to a many to many relationship
I have list of strings from POST request and I want to create blog object with many values of hashtags, with this method it only creates hashtag object with 1 value and then overrides it, what can i do? def myForm(request): tags = HashTags.objects.all() if request.method == 'POST': g = request.POST print(g) if g.get('title') and g.get('desc') and request.FILES.get('file'): obj = Blog.objects.create( title = g.get('title'), text = g.get('desc'), photo1 = request.FILES.get('file')) if g.get('VIN'): obj.Vin = g.get('VIN') if g.getlist('tags'): for i in g.getlist('tags'): print(i) a = HashTags.objects.filter(tag=i) obj.hashtag.tag = g.getlist('tags')[0] return redirect('blog:main') class HashTags(models.Model): tag = models.CharField(max_length=150,unique=True) #unique=True def __str__(self): return self.tag class Blog(models.Model): title = models.CharField(max_length=150) date = models.DateTimeField(auto_now_add=True) text = models.TextField() photo1 = models.ImageField() photo2 = models.ImageField(null=True,blank=True) videoURL = models.CharField(max_length = 5000) hashtag = models.ManyToManyField(HashTags) slug = models.SlugField(null=True,blank=True) pinVideo =models.BooleanField(null=True,blank=True,default=False) pinPhoto = models.BooleanField(null=True,blank=True,default=False) actual: randomtag2 expected: randomtag1 ,randomtag2 -
Making a custom filter and need it do a general search instead of an exact search
I am creating a custom filter class and instead of my search being exact I want it to be general or a contains Here's my code for the custom filter class: class ChoiceFilter(FilterSet): class Meta: model = Choice fields = '__all__' Whenever I try to search something I have to be exact and get the entire string for it to show data. I want it so it doesn't have to do that. For example: If I have answer called 'yes' if I search 'y' I want to the answer 'yes' to pop up instead of needing the entire word. -
Why aren't styles applied?
staticfiles connected. static is prescribed everywhere. Everything seems to be loading, but for some reason they don’t connect ... collectstatic did it successfully. my_project/ __my_project/ ____settings/ ____static/ ____assets/ __app/ __static/ settins.base.py STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( path('static'), ) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) 'django.template.context_processors.static', 'django.contrib.staticfiles', html <link href="{% static 'assets/fonts/stylesheet.css' %}" rel="stylesheet"> <link href="{% static 'assets/plugins/swipe_navigation/source/stylesheets/swipenavigation.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'assets/plugins/jqueryui/jquery-ui.css' %}" rel="stylesheet" type="text/css"> ... -
How to get into the details view using any primary key from a template to another template?
I make a list view and detail view using function..here i get the queryset..I get the query data in list view but I get the query data in list view in template passing pk in url section.. i put '''league//''' in path for detail view and in list view template put '''{% url 'league-detail' match.pk %}''' in href...bt an error occurs : league() got an unexpected keyword argument 'pk' urls: ''' path('leagues/', views.league, name='league'), path('league//', views.league_detail, name='league-detail'), ''' views: '''python match = Match.objects.all() ''' same for both list view and detail view templates: ''' {% url 'league-detail' match.pk %} ''' but error is: league() got an unexpected keyword argument 'pk' i need to go to the '''league-detail''' template by get actual data using queryset