Comparing Data in Django Form Validation

Seeking help with forms and validation in Django using Python.

I have a form with a single field where users can input names. However, I need to ensure that only names supported by a third-party website can be entered. Here is my current forms.py:

class MyModelForm(forms.ModelForm):

    class Meta:

        model = MyModel
        fields = ('title', )


    def clean_title(self):
        cd = self.cleaned_data

        # The following line checks if the name inserted is supported by a 3rd party database.
        # cleaned_data should contain the name inserted by the user.

        fields = client.search(cleaned_data).name

        # If the client returns the same name as the one inserted by the user,
        # the post is considered valid.
        # If the user inserts a name not found in the 3rd party db, the client sends an error response and the post is rejected.

        if (self.cleaned_data.get('title') != fields)

            raise ValidationError(
                "This name is not supported"
            )

        return self.cleaned_data

The code may seem messy due to various attempts I've made to achieve this functionality.

Here is views.py

def add_model(request):

if request.method == "POST":
    form = MyModelForm(request.POST)
    if form.is_valid():

        # Setting commit=False ensures the form doesn't save immediately.
        # By default, commit is set to True which saves normally.
        model_instance = form.save(commit=False)
        model_instance.timestamp = timezone.now()
        model_instance.save()
        return HttpResponseRedirect('/polls/thanks')
else:
    form = MyModelForm()

return render(request, "polls/polls.html", {'form': form})

and models.py

class MyModel(models.Model):
title = models.CharField(max_length=25, unique=True, error_messages={'unique':"This name has already been added."})
timestamp = models.DateTimeField()

These are provided just in case they're needed.

I hope you understand my goal and appreciate any tips or examples of code you may provide. Thank you! :)

Answer №1

The value of the field in the clean_ method can be accessed using self.cleaned_data['field_name']:

class UserForm(forms.ModelForm):

    class Meta:    
        model = UserModel
        fields = ('username', )

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            email = user.search(email).address
        except HTTPError:
            raise ValidationError("Unable to verify the address. Please try again later")
        if email != address:
            raise ValidationError("This email is not valid")
        return username

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for displaying a function's arguments in the proper sequence?

I've been working on creating a Python function that, when called inside another function, prints the name of the function followed by the parameters it was called with. I used sys and accessed sys._getframe(1).f_code.co_name to get the function' ...

Dropdown menu of countries created with Material UI

I have been working on creating a dropdown menu in my form that lists all countries. I used an Array of strings with country names and mapped through it to generate the options for the select dropdown. However, the dropdown menu does not seem to be worki ...

What is the best way to create a generator expression in a single line for generating these distinct lists?

As I develop a program to analyze lists similar to this one, ['ecl:gry', 'pid:860033327', 'eyr:2020', 'hcl:#fffffd', 'byr:1937', 'iyr:2017', 'cid:147', 'hgt:183cm'] I aim to c ...

What is the best method for effortlessly integrating a sub_axes with precise placement and dimensions in matplotlib and cartopy?

When trying to add a second axes at the top right corner of a first axes in Matplotlib and Cartopy, I came across two methods: fig.add_axes() and mpl_toolkits.axes_grid.inset_locator.inset_axes. However, using fig.add_axes() resulted in an error because it ...

A foolproof method for safeguarding the JWT secret key utilized for encoding and decoding token information

I have a Python application in the works with FastApi, utilizing JWT and OAuth2 password flow for user authentication. Following their documentation, upon user login, a token is issued using the HS256 algorithm along with a specific user secret key. This t ...

Remove an additional bracket from a given list

I am working with a list in Python that looks like this: results = [[['New','York','intrepid', 'bumbling']], [['duo', 'deliver', 'good', 'one']]] My goal is to transform it i ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

Exploring the connection between Django and AngularJS: delving into the router functionality and how Django variables are assigned

As a beginner in IONIC, AngularJS, and Django, I recently attempted to host an IONIC project within Django. While both Django and AngularJS are excellent frameworks individually, integrating them has left me feeling confused. Question 1: How can I effecti ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

What is the best way to avoid the "/" character when using send_keys?

When running a script that writes code into a textarea on a website, I encountered an issue. The first four lines were being written correctly until var url = "https:, at which point the cursor would jump to the upper left of the text area before continuin ...

Adding Arrow annotations with an offset to a Bokeh plot that has a datetime x-axis can enhance the visualization

Is there a way to visually represent when the short moving average crosses above the long moving average, like with an arrow or dots? I attempted to use the code below to plot this on a datetime axis, but encountered errors. #plot short ma and long ma p.li ...

Ordering of components following transformation in Principal Component Analysis

I have been utilizing the PCA class from sklearn.decomposition to reduce the dimensionality of my feature space for visualization purposes. I have a question about the outcome: Upon implementing the fit and transform functions of the PCA class, I receive ...

What is the best way to implement a function in a discord.py command that restricts the use of a command to only once per minute?

What is the best way to ensure a command in discord.py can only be used once every minute? @bot.command() async def busk(ctx): member = ctx.message.author.id #gets the user ID, which i use as the _id in pymongo because everyones is different. ...

Scraping HTML data without <div> tags with Scrapy - how to do it?

After spending hours attempting to extract a specific data set for use with Scrapy in a web scraping project, here is the current python code: bedrooms_info = house_listing.css( '.search-results-listings-list__item-description__charact ...

What could be causing my sjoin() function to produce an empty GeoDataFrame?

I'm currently working on a spatial join operation between two GeoDataFrames. The first GeoDataFrame contains the coordinates of points associated with specific names. The second GeoDataFrame consists of polygons derived from the French cadastre data. ...

Tips for transforming user-provided variables into numeric values

Consider the code snippet provided: steak = 40.00 pepsi = 3.45 order1 = input("Please enter your first order:") order2 = input("Please enter your second order:") total = order1 + order2 I am looking for a way to convert order1 and order2 into numerical v ...

Discover the elements that possess the ::after pseudo-element

I'm looking to extract specific labels from a list of labels. <div> <label class="search-reusables__value-label"> ::before <p class="display-flex">...</p> </label> <label class=" ...

Saving series data into a CSV file using Python

I need help writing two 'Series' objects into a normal csv file with date and value columns. Here are the objects: https://i.stack.imgur.com/FRDih.png Unfortunately, my code (shown below) only includes the value and not the date along with it: h ...

Tips for arranging the angles in a polar plot in a clockwise direction with the starting angle set at 0 degrees on top

I am currently using matplotlib and numpy to generate a polar plot within my project. Below is a snippet of the code I've been working with: import numpy as np import matplotlib.pyplot as plt angle = np.arange(0, 360, 10, dtype=float) * np.pi / 180. ...

Issue with Objects in a Lexicon in Ursina Programming Language

Looking to create a grid of various entities without having to write an excessive amount of code, I've opted to utilize a dictionary to automatically generate them. This saves me from manually coding 1521 lines for each individual entity. To handle i ...