Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Field 'activity_id' expected a number but got <QueryDict: Django

I’m creating a small django CRUD project and working on creating the create functionality, however everytime I try to create an activity through teh sites frontend I get the following error

Field 'activity_id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['DnM8yrfIrvYgvN6rShEOtR9DFwjpryNtHHs6ytHK1CSAYg3G9sm7YjkcHlpejJDt'], 'host': ['1'], 'name': ['testing testing'], 'date': ['2022-06-28'], 'start_time': ['19:20:58'], 'end_time': ['19:52:50'], 'location': ['test Location'], 'description': ['ewerwerwerwe']}>.

When I create somethign through the /admin panel, it works as expected.

here is my forms.py file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from django import forms
from .models import Activity

class ActivityForm(forms.ModelForm):
    class Meta:
        model = Activity
        fields = ('host', 'name', 'date',
                  'start_time', 'end_time', 
                  'location', 'description')

    def __init__(self, *args, **kwargs):
        """
        Add placeholders and classes, remove auto-generated
        labels and set autofocus on first field
        """
        super().__init__(*args, **kwargs)
        placeholders = {
            'name': 'Activity Type',
            'date': 'Date of Activity',
            'start_time': 'Start Time',
            'end_time': 'End Time',
            'location': 'Location',
            'description': 'Description',
            'host': 'Host',
        }

        for field in self.fields:
            if self.fields[field].required:
                placeholder = f'{placeholders[field]} *'
            else:
                placeholder = placeholders[field]
            self.fields[field].widget.attrs['placeholder'] = placeholder
            self.fields[field].label = False

this is the models.py file

class Activity(models.Model):
    class Meta:
        verbose_name_plural = 'Activities'

    activity_id = models.AutoField(primary_key=True)
    host = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    name = models.CharField(max_length=254, null=False, blank=False)
    date = models.DateField()
    start_time =models.TimeField()
    end_time = models.TimeField()
    location = models.CharField(max_length=40, null=False, blank=False)
    description = models.CharField(max_length=140, null=False, blank=False)
    available = models.BooleanField(default=True)

    def __str__(self):
        return str(self.activity_id)

and the views:

def create_activity(request):
    if request.method == "POST":
        form_data = request.POST
        form = Activity(form_data)
        print(form_data)
        form.save()
    else:
        form = ActivityForm()
        context = {
        'form': form,
    }
        return render(request, 'activities/new_listing.html', context)

>Solution :

You create an ActivityForm with the form_data, so:

def create_activity(request):
    if request.method == 'POST':
        form = ActivityForm(request.POST)  # 🖘 ActivityForm
        if form.is_valid():
            form.save()
            return redirect('name-of-some-view')
    else:
        form = ActivityForm()
    context = {
        'form': form,
    }
    return render(request, 'activities/new_listing.html', context)

Note: In case of a successful POST request, you should make a redirect
[Django-doc]

to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading