Add ?q=search+term in django url - django

I want to integrate elastic search with django but first I need to get a nice parameter in url
http://127.0.0.1:8000/search?q=search+term
urls.py (of the view)
urlpatterns = [
path('?q=', SearchIndexView.as_view(), name="search-index"),
]
urls.py (of the app)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
path('u/', include('user.urls')),
path('search', include('search.urls')),
]
That is what I have so far but I cant figure out how to make it work.
I want to use tha path() and not url() if possible

HTML FORM
<form action="{%url 'search' %}" method="get">
<input type="text" name="q" placeholder="Search...">
<button type="submit"></button>
</form>
urls
path('search/',views.search,name='search')
views
def search(request):
query = request.GET.get('q')
if query:
print("do your stuff here")

You don't need to define url query strings in urls.py. You can keep the url like this:
path('', SearchIndexView.as_view(), name="search-index"),
and in SearchIndexView you can do it like this:
q = request.GET.get('q')

keep your url like this
urlpatterns = [
path('', SearchIndexView.as_view(), name="search-index"),
]
in the html form
<form method='GET'>
and in the input put name="q"

in Django generic views you can create search views as follows for model Blog
class SearchResultView(ClientMixin, TemplateView):
template_name = 'clienttemplates/clientsearchresult.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
query = self.request.GET.get('q')
if query:
lookup = Q(title__icontains=query)
search_list = Blog.objects.filter(lookup)
context["slist"] = searchlist
return context
in html simply put name='q' inside input tag
<input type="text" class="search-field " placeholder="Search Blog..." value="" name='q'>
in urls.py
path('search/result', SearchResultView.as_view(), name="searchresult"),
in clientsearchresult.html you can simply add
{% if slist %}
{% for blog in slist %}
{{blog.title|title}}
{{bog.content|safe}}
{% endfor %}... and so on
{% endif %}

Related

CS50w - Project 1 - 404 page shown instead of search page

I try to solve cs50w project 1. But I faced an error in the project.
This is the layout.html file. I have a form action: go to search, and the name is q
enter image description here
<form action="{% url 'search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("<str:title>/", views.title, name="title"),
path("search/", views.search, name="search"),
]
views.py
def search(request):
if request.method == "POST":
entry_search = request.POST['q']
html_content = markdown2.markdown(util.get_entry(entry_search))
if html_content is not None:
return render(request, "encyclopedia/title.html", {
"content": html_content,
"title": entry_search,
})
When I start my project and type something in the search bar, it sends me to the error.html page.
enter image description here
But it needs to take me to the title.html page.
Can you help me with this problem?
I need to face with title.html page, but it redirects to error.html

Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<item_id>[^/]+)/$']

I cant seem to add products/plans to my cart page im getting this error.
This is my views
def add_to_cart(request, item_id):
""" Add plan to shopping cart """
cart = request.session.get('cart', {})
cart[item_id] = cart.get(item_id, 1)
request.session['cart'] = cart
return redirect(reverse('plans'))
This is my plans.html - this is a button where im trying to a plan to my cart
<form method="post" action="{% url 'add_to_cart' item.id %}">
{% csrf_token %}
<div class="text-center">
<span class="input-group-btn">
<button class="btn btn-light color-orange " type="submit">
Add to Cart
</button>
</span>
</div>
</form>
And this is my urls from my cart app
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.view_cart, name='view_cart'),
path('add/<item_id>/', views.add_to_cart, name='add_to_cart'),
]
Would be great if someone could guide me
urlpatterns = [
path('', views.view_cart, name='view_cart'),
# path('add/<item_id>/', views.add_to_cart, name='add_to_cart'),
path('add/<int:item_id>/', views.add_to_cart, name='add_to_cart'),
]
Make sure that you are passing a value with key "item" to the context data in your form HTML, or else "item.id" will be None.

Log out when sending a form

I've created an app where you can make comment (which sends a form to a database and saves it) if you're login on only, but when I press the button "Create" instead of redirecting me to the page where it show all the comments, it logs me out and bring me back to the "log out" view (which is / )
the create Template:
{% extends 'base.html' %}
{% block content %}
<div class="create_comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
The Views of Create:
#login_required(login_url='/userprofile/login/')
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
form.save()
return redirect('/usercomments')
else:
form = forms.CreateComment()
return render(request,'usercomments/comments_create.html', {'form':form})
Log out view:
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/')
else:
pass
usercomments Urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
userprofile urls.py:
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

the image uploaded is not stored on the database

i'm creating a 'create an account view ' which the user can store his image, name ,lastname ....
on my database the name,lastname... are registred but the image is not stored.why?
in models.py:
from django.db import models
class information(models.Model):
name=models.CharField(max_length=50)
lastname=models.CharField(max_length=50)
email=models.CharField(max_length=50)
password=models.CharField(max_length=50)
img=models.ImageField(upload_to='media',blank=True)
in forms.py:
from app1.models import information
from django import forms
class create_form(forms.ModelForm):
class Meta:
model=information
fields=[
'name',
'lastname',
'email',
'password',
'img'
]
in views.py:
def create_view(request,*args,**kwargs):
my_form=create_form(request.POST or None)
if my_form.is_valid():
my_form.save()
print(my_form.cleaned_data['img'])**#########print :None**
context={"form":my_form}
return render(request,'first create.html',context )
in templates:
<main>
<section>
<form action="" method="Post"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="save"/>
</form>
</section>
</main>
url.py
from django.contrib import admin
from django.urls import path
from app1 import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', views.firstview, name='home'),
path('Create/', views.create_view, name='create'),
path('home/main/', views.homeview, name='main')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You made two mistakes here. First of all, you need to pass request.FILES to the form:
from django.shortcuts import redirect
def create_view(request,*args,**kwargs):
if request.method == 'POST':
my_form=create_form(request.POST, request.FILES)
if my_form.is_valid():
my_form.save()
return redirect('some-view')
else:
my_form = create_form()
context={'form': my_form}
return render(request,'first create.html', context)
and furthermore you need to specify enctype="multipart/form-data" in your <form> tag:
<main>
<section>
<form action="" method="Post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="save"/>
</form>
</section>
</main>
Note that you better implement the Post/Redirect/Get pattern [wiki] and thus make a redirect(..) [Django-doc] in case of a succesful POST request.

Behaviour of Create Views in Django

I am a newbie in Django pretty much. Since I want to step my game up now, I want to dive into generic class based views. I already figured out how to use template views, but now I want to go for the create views.
I have these forms:
class LearningObjectiveForm(ModelForm):
class Meta:
exclude = ['trainee']
These models:
class LearningObjective(models.Model):
trainee = models.ForeignKey(Trainee, blank = True)
learning_objective = models.TextField()
class Trainee(models.Model):
username = models.TextField()
...
class Topic(models.Model):
trainee = models.ForeignKey(Trainee, blank = True)
learning_objective = models.ManyToManyField(LearningObjective, blank = True, null = True)
topic = models.TextField()
And this create view:
class CreateLearningObjective(CreateView):
model = LearningObjective
form = LearningObjectiveForm
def form_valid(self, form):
self.object = form.save(commit=False)
if self.request.user.is_authenticated():
self.object.trainee = self.request.user
self.object.save()
return super(CreateLearningObjective, self).form_valid(form)
My urls:
from django.conf.urls import patterns, url
from programm import views
from .views import LearningObjectiveView, CreateLearningObjective
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^learning_objective/$', LearningObjectiveView.as_view(), name = 'learning_objective'),
url(r'^learning_objective_add/$', CreateLearningObjective.as_view(), name = 'learning_objective_add'),
)
Template:
<form action="{% url 'learning_objective_add' %}" method="post">
{% csrf_token %}
<textarea name="learning_objective" rows="4"></textarea>
<p><select name="topic" size="6" multiple>
{% for lO in learning_objectives %}
{% for t in lO.topic_set.all %}
<option>{{ t.topic }}</option>
{% endfor %}
{% endfor %}
</select></p>
<input type="submit" value="Absenden"/>
</form>
unfortunately when I try to submit a post, I just receive a Cannot assign None: "LearningObjective.trainee" does not allow null values. Error. Can anybody please help me?? I am really stuck and clueless what I should do right here :/
Change your urls.py to:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^learning_objective/$', LearningObjectiveView.as_view(), name = 'learning_objective'),
url(r'^learning_objective_add/$', CreateLearningObjective.as_view(), name = 'learning_objective_add'),
)
The error is that your second url ('^learning_objective') intercepts the post request to the third url. This is why you should add $ at the end of regex.
And / slash is also required for POST views because of APPEND_SLASH setting.