Solve the problem that Vim fails to automatically complete the models fields in Django.

Source: Internet
Author: User

First, I used the latest version 0.9 of pythoncomplete, added django_settings_module = settings to the environment variable, and set export pythonpath = ~ /Workspace/my_project/src. At this time, I write a model class, for example:

# File :~ /Workspace/my_project/src/main/models. py

Class book (models. Model ):

Name = models. charfield (max_length = 100)

Title = 'book title'

 

Create a TT. py file in the same directory to create an instance of this class.

From Main. Models import *

 

B = book ()

B. <c-x> <c-o>

 

At this time, only the title field is prompted, but the name field is not displayed. I have tried this problem multiple times and found that it has nothing to do with pythonpath and tags settings. But the pythoncomplete plug-in has a problem. If you do not allow the book to inherit models. the model is a common object that prompts the name field, and its code is not very clear, so I just used a patch to solve this problem. Open the $ Vim/vim72/autoload/pythoncomplete. Vim file and edit the get_completions function in

 

Match = stmt [ridx + 1:]

Stmt = _ sanitize (stmt [: ridx])

Result = eval (stmt, self. compldict)

All = Dir (result)

 

 

Add:

 

If result. _ class _. _ name _ = 'modelbase ':

Module_name = result. _ module __

Class_name = result. _ name __

Module_instance = _ import _ (module_name, {}, {}, [class_name])

Class_instance = getattr (module_instance, class_name)

Instance = class_instance ()

Result = instance

All = Dir (Instance)

 

 

The result here is the object instance B, and all is all its attributes. In the above code, I first determine whether the base class of result is Django. DB. models. base. modelbase then dynamically creates an instance based on book's _ module _, so that all fields can be obtained. You can manually modify the following to see if it is really effective. If it works, you should not be too happy, because this completes the first step, do not believe you put B = book () put it in a function, such as our views. in the frequently defined functions in Py, you will find that the code above has no effect. After repeated use of the print stunt, the problem is finally located, in the code of the evalsource function:

 

For l in SC. Locals:

Try:

Exec (l) in self. compldict

Except t:

Print "locals: % s, % s [% s]" % (SYS. exc_info () [0], SYS. exc_info () [1], L)

Dbg ("locals: % s, % s [% s]" % (SYS. exc_info () [0], SYS. exc_info () [1], L ))

 

 

Print is added to facilitate viewing of specific errors. The error "nameerror" should be reported. An undefined book is used. After experiment, we found that it would be normal to add import to a function, for example:

Def index (request ):

 

From Main. Models import *

B = book ()

This is because exec needs to combine context during execution. If you do not import the required module in the index function, the book must be undefined. Therefore, solving this problem is actually very simple, change the above section:

 

Namespace = []

 

 

Def evalsource (self, text, line = 0 ):

SC = self. parser. parse (text, line)

Src = SC. get_code ()

Dbg ("Source: % s" % SRC)

Try: exec (SRC) in self. compldict

Partition T: dbg ("Parser: % s, % s" % (SYS. exc_info () [0], SYS. exc_info () [1])

# Patch for model subclass in fuction

If not namespace:

For item in SRC. Split ('/N '):

If item. startswith ('from') or item. startswith ('import '):

Namespace. append (item)

 

For l in SC. Locals:

Try:

Namespace. append (l)

L = '/N'. Join (namespace)

Exec (l) in self. compldict

Except t:

Print "locals: % s, % s [% s]" % (SYS. exc_info () [0], SYS. exc_info () [1], L)

Dbg ("locals: % s, % s [% s]" % (SYS. exc_info () [0], SYS. exc_info () [1], L ))

 

 

 

Because the SRC variable already contains the source code, you can simply filter out all the import and from statements in your source file, then add the namespace to the front of the exec every time.

 

It is easy to say and difficult to do. I had to deal with these two small issues for two days. I think the above Code should have performance problems. Fortunately, the neocomplcache plug-in's cache won't make Vim's response too slow. The last question is that the index function is too simple, because normal encoding will take values from the database, for example:

B = book. Object. Get (ID = 1)

At this time, there is certainly no prompt. Of course, there is a weakness solution to prompt that the code is written after defining a B = book (), and then the sentence is deleted. However, a better solution should be to find a way for pythoncomplete to dynamically obtain the instance object after the query based on Django's source code. This problem will be solved after I have the enthusiasm and energy. I am satisfied with this prompt function.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.