Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The use of form Form object and how to build complex QuerySet

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to use the form Form object and how to build a complex QuerySet. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

First, create a form using Django

Django contains two base classes to build forms, as follows:

Form can build standard forms

ModelForm can build a form associated with a model instance

1. Standard form Form

First, create the forms.py file in the application directory as follows:

From django import formsclass EmailPostForm (forms.Form): name = forms.CharField (max_length=25) email = forms.EmailField () to = forms.EmailField () comments = forms.CharField (required=False, widget=forms.Textarea)

CharField the field type is displayed as

Widget is the plug-in used for the field, and the Textarea plug-in is used in the comments field

EmailField needs to use a valid email address; otherwise, field validation will throw a forms.ValidationError exception

Required indicates whether this field is required

For a list of valid form fields, please see: click here

Next, use the Form form object in views.py

From .forms import EmailPostFormdef post_share (request, post_id): post = get_object_or_404 (Post, id=post_id, status='published') if request.method = 'POST': form = EmailPostForm (request.POST) if form.is_valid (): cd = form.cleaned_data #... Else: form = EmailPostForm () return render (request, 'blog/post/share.html', {' post': post, 'form': form})

The above view works as follows:

Defines the post_share view and accepts request objects and post_id variables as parameters

Use the get_object_or_404 shortcut and retrieve posts through ID to ensure that the status of the retrieval is published

Distinguish between POST requests and GET requests according to the request.method = = 'POST' method

The form processing flow is as follows:

When the view is a GET request, create a new form instance and use it to display the empty form in the template: form = EmailPostForm ()

When requesting for POST, generate a form instance from the submitted data contained in request.POST: form = EmailPostForm (request.POST)

Validate the submitted data using the form is_valid () method. If a field contains invalid data, False is returned. You can view the list of validation errors by visiting form.errors

If the form is correct, the validated data will be retrieved by accessing form.cleaned_data. This property is represented as a dictionary of form fields and their corresponding values.

Finally, use the Form object in the HTML template:

{% extends "blog/base.html"%} {% block title%} Share a post {% endblock%} {% block content%} {% if sent%} E-mail successfully sent

"{{post.title}}" was successfully sent to {{form.cleaned_data.to}}.

{% else%} Share "{{post.title}}" by e-mail {{form.as_p} {% csrf_token%} {% endif%} {% endblock%}

Django is informed here to use the as_p method to display the field as

The fields in the. In addition, you can use as_ul as an unordered list to display the form, or as_table as a table to display. If you need to display each field, you can traverse the relevant fields, as follows:

{% for field in form%} {{field.errors}} {{field.label_tag}} {{field}} {% endfor%} 2. Model form ModelForm

First, create a model for comment posts:

Class Comment (models.Model): post = models.ForeignKey (Post, on_delete=models.CASCADE, related_name='comments') name= models.CharField (max_length=80) email = models.EmailField () body = models.TextField () created = models.DateTimeField (auto_now_add=True) updated = models.DateTimeField (auto_now=True) active = models.BooleanField (default=True) class Meta: ordering = ('created' ) def _ str__ (self): return 'Comment by {} on {}' .format (self.name, self.post)

ForeignKey uses foreign keys to associate posts

Related_name can query the corresponding tables across tables. After the definition is completed, the post of the comment object can be retrieved through comment.post, or all comments of a post can be retrieved using post.comments.all (). If this value is not defined, Django will name the related object manager in the form of model name _ set (such as comment_set).

For more information about the many-to-one relationship, click here

Then create the form in the model, edit the forms.py file in the application directory, and add the following code:

From .models import Commentclass CommentForm (forms.ModelForm): class Meta: model = Comment fields = ('name',' email', 'body')

Model specifies which model to use to create the form

Fields explicitly tells the current framework which fields you want to include in the form, or uses exclude to define the fields you want to exclude.

Then, using ModelForms in the view View, modify the post_detail () method of the views.py file as follows:

From. Models import Post, Commentfrom. Forms import EmailPostForm, CommentFormdef post_detail (request, year, month, day, post): post = get_object_or_404 (Post, slug=post, status='published', publish__year=year, publish__month=month) Publish__day=day) # find the associated comment object through the post object comments = post.comments.filter (active=True) new_comment = None if request.method = = 'POST': comment_form = CommentForm (data=request.POST) if comment_form.is_valid (): new_comment = comment_form.save (commit=False) new_ Comment.post = post new_comment.save () else: comment_form = CommentForm () return render (request 'blog/post/detail.html', {' post': post, 'comments': comments,' new_comment': new_comment, 'comment_form': comment_form})

Comments = post.comments.filter (active=True) uses the post_detail view to display posts and their comments, and adds QuerySet to the post to filter and retrieve comments

New_comment = comment_form.save (commit=False) creates the model instance linked by the form. If you use commit=False, an instance of the model will be created, but it will not be saved to the database

New_comment.post = post modifies the attribute value of ModelForms

New_comment.save () is saved to the database

Finally, it is shown in the HTML template:

{% with comments.count as total_comments%} {{total_comments}} comment {{total_comments | pluralize}} {% endwith%} {% for comment in comments%} Comment {{forloop.counter}} by {{comment.name} {{comment.created}}

{{comment.body | linebreaks}} {% empty%}

There are no comments yet.

{% endfor%} {% if new_comment%} Your comment has been added. {else%} Add a new comment {{comment_form.as_p}} {% csrf_token%}

{% endif%}

The {% with%} tag assigns a value to a new available variable until the {% endwith%} tag is encountered.

The pluralize filter returns a complex numeric string containing the letter s.

Second, use django-taggit to add tags

Django-taggit source code address

1. Install django-taggitpip/pipenv install django_taggit2. Register taggiaINSTALLED_APPS = [... in the settings.py file. 'taggit',] 3. Add the TaggableManager manager provided by djnago-taggit to the model that needs to use tag from taggit.managers import TaggableManagerclass Post (models.Model):... Tags = TaggableManager () 4. Generate database migration python manage.py makemigrations blog (application name) python manage.py migrate

After the migration is complete, run the server, and you can manage all tags (tags) in the Django management page.

5. Examine how to use tags Manager in shell > from blog.models import Post > post = Post.objects.get (id=1) > post.tags.add ('music',' jazz', 'django') > post.tags.all () > post.tags.remove (' django') > post.tags.all () 6. Display TagsTags: {{post.tags.all | join: ","}} in the HTML template

The join template filter is similar to the join () method of a string and adds the specified string to the related element.

7. Using Tags in View Views

Modify the views.py file of the application directory as follows:

From taggit.models import Tagdef post_list (request, tag_slug=None): object_list = Post.published.all () tag = None if tag_slug: tag = get_object_or_404 (Tag, slug=tag_slug) object_list = object_list.filter (tags__in= [tag]) paginator = Paginator (object_list 3) # 3 records per page page = request.GET.get ('page') try: posts = paginator.page (page) except PageNotAnInteger: # if the page number is invalid, jump to page 1 posts = paginator.page (1) except EmptyPage: # if the number of pages is out of range, jump to the last page posts = paginator.page (paginator.num_pages) return render (request 'blog/post/list.html', {' posts': posts, 'page': page,' tag': tag})

Post_list receives an optional tag_slug parameter, which defaults to None and is included in the URL

After building the initial QuerySet and retrieving all posts published, if there is a tag slug, the Tag object will be obtained through get_object_or_404 ().

The list of posts is then filtered through slug.

Finally, adjust the render () function below the view to add the tag variable to the HTML template.

Add an additional URL path to list posts through the tag:

Path ('tag//', views.post_list, name='post_list_by_tag')

The HTML template code of the front end face is modified as follows:

{% extends "blog/base.html"%} {block title%} My Blog {% endblock%} {% block content%} My Blog {% if tag%} Posts tagged with "{{tag.name}}" {% endif%} {% for post in posts%} {{post.title}} Tags: {% for tag in post.tags.all%} {{tag.name}} {% if not forloop.last%} {endif} {endfor}

Published {{post.publish}} by {{post.author}}

{{post.body | truncatewords:30 | linebreaks}} {% include 'pagination.html' with page=posts%} {% endfor%} {% endblock%}

{% url "blog:post_list_by_tag" tag.slug%} has the URL name and slug tag as its parameters

Third, build a complex QuerySet

We will build the complex QuerySet in the post_detail view, modify the views.py file in the application directory, and add the following code:

From django.db.models import Count

Count is the Count aggregate function in Django ORM. Other aggregate functions can access the following address

Before render (), add the following code to the post_detail view:

Post_tag_ids = post.tags.values_list ('id', flat=True) similar_posts = Post.published.filter (tags__in=post_tag_ids). Steps (id=post.id) similar_posts = similar_posts.annotate (same_tags=Count (' tags')). Order_by ('- same_tags','- publish') [: 4] return render (request, 'blog/post/detail.html', {' post': post, 'comments': comments 'new_comment': new_comment,' comment_form': comment_form, 'similar_posts': similar_posts})

The above code does the following:

For the tag of the current post, tag Python ID list. Values_list () returns the tuple containing the specified field. The introduction of flat=True, can be obtained in the form of [1] A list of.

Get all posts that contain such tags and exclude the current post itself.

Use the Count function to generate a calculated field, same_tags. This field contains the tag number common to all query tags

Sort the results by label number and release date. Only the first four posts are retrieved here.

Put the similar_posts in the context dictionary.

Finally, it is shown in the HTML template:

Similar posts {% for post in similar_posts%}

{{post.title}}

{% empty%} There are no similar posts yet. {% endfor%}

At this point, you can recommend the function of posts with similar tags to users.

The above is the use of form Form objects and how to build complex QuerySet. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report