OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How do I resolve a FieldError(Cannot resolve keyword '...' into field.) in Django?

  • Thread starter Thread starter Allan Almax
  • Start date Start date
A

Allan Almax

Guest
I am trying to have clients search for service providers in my search.html stored in the database that only belong to a specific category of services.

This is the snippet from the template handling the search:

Code:
<form method="get" action="{% url 'search' %}">
  <select name="category" id="category">
    <option value="">Select a category</option>
    {% for category_key, category_name in service_categories %}
    <option value="{{ category_key }}">{{ category_name }}</option>
    {% endfor %}
  </select>
 <button type="submit">Search</button>
</form>

This is the current logic in the views.py for the search template.

Code:
def search(request):
    # Capture search criteria from request parameters
    category = request.GET.get('category')
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')

    # Initialize search results
    search_results = None

    if category or (start_time and end_time):
        # Filter providers based on category and availability
        query = ServiceProvider.objects.all()
        if category:
            query = query.filter(services__category=category)
        if start_time and end_time:
            try:
                start_time = datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S')
                end_time = datetime.strptime(end_time, '%Y-%m-%dT%H:%M:%S')
                query = query.filter(
                    availabilities__start_time__lte=end_time,
                    availabilities__end_time__gte=start_time
                )
            except Exception as e:
                print(f"Error processing availability: {e}")
        search_results = query.distinct()

    # Fetch Popular or Featured Providers (modify based on your logic)
    popular_providers = ServiceProvider.objects.filter(is_featured=True)[:3]

    service_categories = Service.service_categories

    context = {
        'search_results': search_results,
        'popular_providers': popular_providers,
        'service_categories': service_categories
    }

    return render(request, 'search.html', context)

These are the related models for ServiceProvider and Service:

Code:
class ServiceProvider(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='service_provider')
    location = models.CharField(max_length=255)
    average_rating = models.FloatField(default=0.0, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)])
    name = models.CharField(max_length=255, default='Provider name')
    image_url = models.URLField(blank=True)  # Optional field for service provider image URL
    description = models.TextField(blank=True)  # Optional field for service provider description
    offers = models.TextField(blank=True)  # Field to store offered services (comma-separated or JSON format)
    pricing = models.TextField(blank=True)  # Field to store pricing information (text or JSON format)
    availability_description = models.TextField(blank=True)  # Text field for general availability info (e.g., "Weekdays 9am-5pm")
    is_featured = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

Code:
class Service(models.Model):
    service_categories = [
        ('Dance', 'Dance'),
        ('Music', 'Music'),
        ('MC', 'Master of Ceremonies'),
        # Add more categories as needed
    ]
    name = models.CharField(max_length=255)
    provider = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='services')
    location = models.CharField(max_length=255, default='')
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.CharField(max_length=50, choices=service_categories)

    def __str__(self):
        return f"{self.name} by {self.provider.user.username}"

So the error came from this particular line query = query.filter(category__services=category) in the views.py. I decided to post the full code of the view function for context.

I was expecting the code to return a list of service providers under a particular category, for example, 'Dance' but instead raised this error:

Cannot resolve keyword 'services' into field. Choices are: availabilities, availability_description, average_rating, description, id, image_url, is_featured, location, name, offers, pricing, user, user_id

I have a feeling the issue could be something small but I've personally failed to figure it out.

PS: Apologies if I've provided a lot of unnecessary code, it's my first time posting a question here. Also, if there is any more explanation required, I can provide it.
<p>I am trying to have clients search for service providers in my <code>search.html</code> stored in the database that only belong to a specific category of services.</p>
<p>This is the snippet from the template handling the search:</p>
<pre><code><form method="get" action="{% url 'search' %}">
<select name="category" id="category">
<option value="">Select a category</option>
{% for category_key, category_name in service_categories %}
<option value="{{ category_key }}">{{ category_name }}</option>
{% endfor %}
</select>
<button type="submit">Search</button>
</form>
</code></pre>
<p>This is the current logic in the <code>views.py</code> for the search template.</p>
<pre><code>def search(request):
# Capture search criteria from request parameters
category = request.GET.get('category')
start_time = request.GET.get('start_time')
end_time = request.GET.get('end_time')

# Initialize search results
search_results = None

if category or (start_time and end_time):
# Filter providers based on category and availability
query = ServiceProvider.objects.all()
if category:
query = query.filter(services__category=category)
if start_time and end_time:
try:
start_time = datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S')
end_time = datetime.strptime(end_time, '%Y-%m-%dT%H:%M:%S')
query = query.filter(
availabilities__start_time__lte=end_time,
availabilities__end_time__gte=start_time
)
except Exception as e:
print(f"Error processing availability: {e}")
search_results = query.distinct()

# Fetch Popular or Featured Providers (modify based on your logic)
popular_providers = ServiceProvider.objects.filter(is_featured=True)[:3]

service_categories = Service.service_categories

context = {
'search_results': search_results,
'popular_providers': popular_providers,
'service_categories': service_categories
}

return render(request, 'search.html', context)
</code></pre>
<p>These are the related models for <code>ServiceProvider</code> and <code>Service</code>:</p>
<pre><code>class ServiceProvider(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='service_provider')
location = models.CharField(max_length=255)
average_rating = models.FloatField(default=0.0, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)])
name = models.CharField(max_length=255, default='Provider name')
image_url = models.URLField(blank=True) # Optional field for service provider image URL
description = models.TextField(blank=True) # Optional field for service provider description
offers = models.TextField(blank=True) # Field to store offered services (comma-separated or JSON format)
pricing = models.TextField(blank=True) # Field to store pricing information (text or JSON format)
availability_description = models.TextField(blank=True) # Text field for general availability info (e.g., "Weekdays 9am-5pm")
is_featured = models.BooleanField(default=False)

def __str__(self):
return self.user.username
</code></pre>
<pre><code>class Service(models.Model):
service_categories = [
('Dance', 'Dance'),
('Music', 'Music'),
('MC', 'Master of Ceremonies'),
# Add more categories as needed
]
name = models.CharField(max_length=255)
provider = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='services')
location = models.CharField(max_length=255, default='')
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.CharField(max_length=50, choices=service_categories)

def __str__(self):
return f"{self.name} by {self.provider.user.username}"
</code></pre>
<p>So the error came from this particular line <code>query = query.filter(category__services=category)</code> in the <code>views.py</code>. I decided to post the full code of the view function for context.</p>
<p>I was expecting the code to return a list of service providers under a particular category, for example, 'Dance' but instead raised this error:</p>
<p><strong>Cannot resolve keyword 'services' into field. Choices are: availabilities, availability_description, average_rating, description, id, image_url, is_featured, location, name, offers, pricing, user, user_id</strong></p>
<p>I have a feeling the issue could be something small but I've personally failed to figure it out.</p>
<p>PS: Apologies if I've provided a lot of unnecessary code, it's my first time posting a question here. Also, if there is any more explanation required, I can provide it.</p>
 
Top