Home > Enterprise >  django form not saving despite success message
django form not saving despite success message

Time:08-06

I have been trying to teach myself something new this week by following various tutorials on Google APIs. I am hitting a wall on the form saving bit, so helping you can help.

Basically, I am trying to offer user the possibility to enter their first line of address for Google to then submit suggestions of addresses.

This first bit works (when I enter the first line of an address, I get generated a list of suggestions).

However, when I am trying to save the form, this doesn't seem to be saved anywhere. And I am not getting any error message either (if anything I am getting the a "success message" I am supposed to receive when the form is successfully submit).

I thought there might be a field that is not getting being populated in the html. So I tried to empty one and tried to save. But on this occasion I received an error message, saying the field is missing. Which makes me thing this hasnt anything to do with the fields in the form but probably how I save my form in the views.py.

I must admit I am way out of my comfort zone here (this ajax thing proved to be difficult to make work, and all I had to do was to follow a tutorial..), so I wouldnt be surprised I am not capturing all the code needed for you to help. If so let me know what you need to see.

Views.py

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def profile(request):
    result = "Error"
    message = "There was an error, please try again"
    form = profileform(instance = request.user) 
    Profile.objects.get_or_create(user=request.user)
    if is_ajax(request=request):
        form = profileform(data = request.POST, instance = request.user)
        if form.is_valid():
            obj = form.save()
            obj.has_profile = True
            obj.save()
            result = "Success"
            message = "Your profile has been updated"
        else:
            message = FormErrors(form)
        data = {'result': result, 'message': message}
        return JsonResponse(data)

    else:

        context = {'form': form}
        context['google_api_key'] = settings.GOOGLE_API_KEY
        context['base_country'] = settings.BASE_COUNTRY

    return render(request, 'main/profile.html', context)

Froms.py

from .models import Profile
class ProfileForm(forms.ModelForm):
    address = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
    town = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
    county = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
    post_code = forms.CharField(max_length=8, required=True, widget = forms.HiddenInput())
    country = forms.CharField(max_length=40, required=True, widget = forms.HiddenInput())
    longitude = forms.CharField(max_length=50, required=True, widget = forms.HiddenInput())
    latitude = forms.CharField(max_length=50, required=True, widget = forms.HiddenInput())
    class Meta:
        model = Profile
        fields = ['address','town','county','post_code','country','longitude','latitude']

Models.py

class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True)
    town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True)
    county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True)
    post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True)
    country = models.CharField(verbose_name="Country",max_length=100, null=True, blank=True)
    longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True)
    latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True)
    captcha_score = models.FloatField(default = 0.0)
    has_profile = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

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

CodePudding user response:

Interesting that you're getting to your success message. Your issue might be that you're passing a user instance to a form that expects a profile model (not sure why this doesn't throw an error though):

# capture the profile that is created with get_or_create
profile, created = Profile.objects.get_or_create(user=request.user)

if is_ajax(request=request):
    form = profileform(data = request.POST, instance=profile) # change instance

CodePudding user response:

Instead of

else:
    message = FormErrors(form)

Try this

else:
    message = form.errors
  • Related