Tuesday, March 24, 2020

Re: django search page not found error

Add null=True to manytomany field


On Wed, 25 Mar 2020, 2:02 am omid jahadi, <omidjahadii@gmail.com> wrote:
Hello everybody! I want to search in a ManyToManyField in the DetailView. It works fine if a user with the same query exist, but if there isn't a user, i get page not found error.

models.py:

class agents(models.Model):      agent_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True)      name = models.CharField(max_length=100)      users = models.ManyToManyField(user_models.users, through='user_agent')

views.py:

class AgentDetailView(LoginRequiredMixin, generic.DetailView):      model = models.agents      template_name = 'agent/agent_detail.html'        def get_queryset(self):          query = self.request.GET.get('q')          if query:              return models.agents.objects.filter(Q(users__user__first_name__contains=query)                                                  | Q(users__user__last_name__contains=query)                                                  | Q(users__id_number__contains=query)                                                  | Q(users__mobile__contains=query))          else:              return models.agents.objects.all()

agent_detail.html:

<h1>name: {{ agents.name }}</h1>      <form method="GET" action="" id="searchform">          <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search..."/>          <button name="search" type="submit" value="{{ request.GET.q }}">Search</button>      </form>      {% if agents.users %}          <p><strong>Users:</strong>              <br>              {% for users in agents.users.all %}                  <li>{{ users }}</li>                  <hr>              {% endfor %}          </p>      {% else %}          <p>There are no user for this agent in database.</p>      {% endif %}

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/54061fa4-2412-424a-8887-916dcc10c051%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHV4E-cFxyjJDsbx%2BPODBMpMVrAZ2pseYpzM5kEdNAcwK3gMBw%40mail.gmail.com.

No comments:

Post a Comment